629ee25d2227929c85ddb4c726e41228faecd990
[rsync.git] / packaging / release-rsync
1 #!/usr/bin/env -S python3 -B
2
3 # This script expects the directory ~/samba-rsync-ftp to exist and to be a
4 # copy of the /home/ftp/pub/rsync dir on samba.org.  When the script is done,
5 # the git repository in the current directory will be updated, and the local
6 # ~/samba-rsync-ftp dir will be ready to be rsynced to samba.org.
7
8 import os, sys, re, argparse, glob, shutil, signal
9 from datetime import datetime
10 from getpass import getpass
11
12 sys.path = ['packaging'] + sys.path
13
14 from pkglib import *
15
16 os.environ['LESS'] = 'mqeiXR'; # Make sure that -F is turned off and -R is turned on.
17 dest = os.environ['HOME'] + '/samba-rsync-ftp'
18 ORIGINAL_PATH = os.environ['PATH']
19
20 def main():
21     now = datetime.now()
22     cl_today = now.strftime('* %a %b %d %Y')
23     year = now.strftime('%Y')
24     ztoday = now.strftime('%d %b %Y')
25     today = ztoday.lstrip('0')
26
27     mandate_gensend_hook()
28
29     curdir = os.getcwd()
30
31     signal.signal(signal.SIGINT, signal_handler)
32
33     gen_files = get_gen_files()
34
35     dash_line = '=' * 74
36
37     print(f"""\
38 {dash_line}
39 == This will release a new version of rsync onto an unsuspecting world. ==
40 {dash_line}
41 """)
42
43     if not os.path.isdir(dest):
44         die(dest, "dest does not exist")
45     if not os.path.isdir('.git'):
46         die("There is no .git dir in the current directory.")
47     if os.path.lexists('a'):
48         die('"a" must not exist in the current directory.')
49     if os.path.lexists('b'):
50         die('"b" must not exist in the current directory.')
51     if os.path.lexists('patches.gen'):
52         die('"patches.gen" must not exist in the current directory.')
53
54     check_git_state(args.master_branch, True, 'patches')
55
56     confversion = get_configure_version()
57
58     # All version values are strings!
59     lastversion, last_protocol_version = get_NEWS_version_info()
60     protocol_version, subprotocol_version = get_protocol_versions()
61
62     version = confversion
63     m = re.search(r'pre(\d+)', version)
64     if m:
65         version = re.sub(r'pre\d+', 'pre' + str(int(m[1]) + 1), version)
66     else:
67         version = version.replace('dev', 'pre1')
68
69     ans = input(f"Please enter the version number of this release: [{version}] ")
70     if ans == '.':
71         version = re.sub(r'pre\d+', '', version)
72     elif ans != '':
73         version = ans
74     if not re.match(r'^[\d.]+(pre\d+)?$', version):
75         die(f'Invalid version: "{version}"')
76
77     v_ver = 'v' + version
78     rsync_ver = 'rsync-' + version
79
80     if os.path.lexists(rsync_ver):
81         die(f'"{rsync_ver}" must not exist in the current directory.')
82
83     out = cmd_txt_chk(['git', 'tag', '-l', v_ver])
84     if out != '':
85         print(f"Tag {v_ver} already exists.")
86         ans = input("\nDelete tag or quit? [Q/del] ")
87         if not re.match(r'^del', ans, flags=re.I):
88             die("Aborted")
89         cmd_chk(['git', 'tag', '-d', v_ver])
90
91     version = re.sub(r'[-.]*pre[-.]*', 'pre', version)
92     if 'pre' in version and not confversion.endswith('dev'):
93         lastversion = confversion
94
95     ans = input(f"Enter the previous version to produce a patch against: [{lastversion}] ")
96     if ans != '':
97         lastversion = ans
98     lastversion = re.sub(r'[-.]*pre[-.]*', 'pre', lastversion)
99
100     rsync_lastver = 'rsync-' + lastversion
101     if os.path.lexists(rsync_lastver):
102         die(f'"{rsync_lastver}" must not exist in the current directory.')
103
104     m = re.search(r'(pre\d+)', version)
105     pre = m[1] if m else ''
106
107     release = '0.1' if pre else '1'
108     ans = input(f"Please enter the RPM release number of this release: [{release}] ")
109     if ans != '':
110         release = ans
111     if pre:
112         release += '.' + pre
113
114     finalversion = re.sub(r'pre\d+', '', version)
115     if protocol_version == last_protocol_version:
116         proto_changed = 'unchanged'
117         proto_change_date = ' ' * 11
118     else:
119         proto_changed = 'changed'
120         if finalversion in pdate:
121             proto_change_date = pdate[finalversion]
122         else:
123             while True:
124                 ans = input("On what date did the protocol change to {protocol_version} get checked in? (dd Mmm yyyy) ")
125                 if re.match(r'^\d\d \w\w\w \d\d\d\d$', ans):
126                     break
127             proto_change_date = ans
128
129     if 'pre' in lastversion:
130         if not pre:
131             die("You should not diff a release version against a pre-release version.")
132         srcdir = srcdiffdir = lastsrcdir = 'src-previews'
133         skipping = ' ** SKIPPING **'
134     elif pre:
135         srcdir = srcdiffdir = 'src-previews'
136         lastsrcdir = 'src'
137         skipping = ' ** SKIPPING **'
138     else:
139         srcdir = lastsrcdir = 'src'
140         srcdiffdir = 'src-diffs'
141         skipping = ''
142
143     print(f"""
144 {dash_line}
145 version is "{version}"
146 lastversion is "{lastversion}"
147 dest is "{dest}"
148 curdir is "{curdir}"
149 srcdir is "{srcdir}"
150 srcdiffdir is "{srcdiffdir}"
151 lastsrcdir is "{lastsrcdir}"
152 release is "{release}"
153
154 About to:
155     - tweak SUBPROTOCOL_VERSION in rsync.h, if needed
156     - tweak the version in configure.ac and the spec files
157     - tweak NEWS.md to ensure header values are correct
158     - generate configure.sh, config.h.in, and proto.h
159     - page through the differences
160 """)
161     ans = input("<Press Enter to continue> ")
162
163     specvars = {
164         'Version:': finalversion,
165         'Release:': release,
166         '%define fullversion': f'%{{version}}{pre}',
167         'Released': version + '.',
168         '%define srcdir': srcdir,
169         }
170
171     tweak_files = 'configure.ac rsync.h NEWS.md'.split()
172     tweak_files += glob.glob('packaging/*.spec')
173     tweak_files += glob.glob('packaging/*/*.spec')
174
175     for fn in tweak_files:
176         with open(fn, 'r', encoding='utf-8') as fh:
177             old_txt = txt = fh.read()
178         if 'configure' in fn:
179             x_re = re.compile(r'^(AC_INIT\(\[rsync\],\s*\[)\d.+?(\])', re.M)
180             txt = replace_or_die(x_re, r'\g<1>%s\2' % version, txt, f"Unable to update AC_INIT with version in {fn}")
181         elif '.spec' in fn:
182             for var, val in specvars.items():
183                 x_re = re.compile(r'^%s .*' % re.escape(var), re.M)
184                 txt = replace_or_die(x_re, var + ' ' + val, txt, f"Unable to update {var} in {fn}")
185             x_re = re.compile(r'^\* \w\w\w \w\w\w \d\d \d\d\d\d (.*)', re.M)
186             txt = replace_or_die(x_re, r'%s \1' % cl_today, txt, f"Unable to update ChangeLog header in {fn}")
187         elif fn == 'rsync.h':
188             x_re = re.compile('(#define\s+SUBPROTOCOL_VERSION)\s+(\d+)')
189             repl = lambda m: m[1] + ' ' + '0' if not pre or proto_changed != 'changed' else 1 if m[2] == '0' else m[2]
190             txt = replace_or_die(x_re, repl, txt, f"Unable to find SUBPROTOCOL_VERSION define in {fn}")
191         elif fn == 'NEWS.md':
192             efv = re.escape(finalversion)
193             x_re = re.compile(r'^<.+>\s+# NEWS for rsync %s \(UNRELEASED\)\s+Protocol: .+\n' % efv)
194             rel_day = 'UNRELEASED' if pre else today
195             repl = (f'<a name="{finalversion}"></a>\n\n# NEWS for rsync {finalversion} ({rel_day})\n\n'
196                 + f"Protocol: {protocol_version} ({proto_changed})\n")
197             good_top = re.sub(r'\(.*?\)', '(UNRELEASED)', repl, 1)
198             msg = f"The top lines of {fn} are not in the right format.  It should be:\n" + good_top
199             txt = replace_or_die(x_re, repl, txt, msg)
200             x_re = re.compile(r'^(\| )(\S{2} \S{3} \d{4})(\s+\|\s+%s\s+\| ).{11}(\s+\| )\S{2}(\s+\|+)$' % efv, re.M)
201             repl = lambda m: m[1] + (m[2] if pre else ztoday) + m[3] + proto_change_date + m[4] + protocol_version + m[5]
202             txt = replace_or_die(x_re, repl, txt, f'Unable to find "| ?? ??? {year} | {finalversion} | ... |" line in {fn}')
203         else:
204             die(f"Unrecognized file in tweak_files: {fn}")
205
206         if txt != old_txt:
207             print(f"Updating {fn}")
208             with open(fn, 'w', encoding='utf-8') as fh:
209                 fh.write(txt)
210
211     cmd_chk(['packaging/year-tweak'])
212
213     print(dash_line)
214     cmd_run("git diff --color | less -p '^diff .*'")
215
216     srctar_name = f"{rsync_ver}.tar.gz"
217     pattar_name = f"rsync-patches-{version}.tar.gz"
218     diff_name = f"{rsync_lastver}-{version}.diffs.gz"
219     srctar_file = f"{dest}/{srcdir}/{srctar_name}"
220     pattar_file = f"{dest}/{srcdir}/{pattar_name}"
221     diff_file = f"{dest}/{srcdiffdir}/{diff_name}"
222     lasttar_file = f"{dest}/{lastsrcdir}/{rsync_lastver}.tar.gz"
223
224     print(f"""\
225 {dash_line}
226
227 About to:
228     - git commit all changes
229     - generate the manpages
230     - merge the {args.master_branch} branch into the patch/{args.master_branch}/* branches
231     - update the files in the "patches" dir and OPTIONALLY
232       (if you type 'y') to launch a shell for each patch
233 """)
234     ans = input("<Press Enter OR 'y' to continue> ")
235
236     s = cmd_run(['git', 'commit', '-a', '-m', f'Preparing for release of {version}'])
237     if s.returncode:
238         die('Aborting')
239
240     cmd_chk('make reconfigure ; make gen')
241     cmd_chk(['rsync', '-a', *gen_files, 'SaVeDiR/'])
242
243     print(f'Creating any missing patch branches.')
244     s = cmd_run(f'packaging/branch-from-patch --branch={args.master_branch} --add-missing')
245     if s.returncode:
246         die('Aborting')
247
248     print('Updating files in "patches" dir ...')
249     s = cmd_run(f'packaging/patch-update --branch={args.master_branch}')
250     if s.returncode:
251         die('Aborting')
252
253     if re.match(r'^y', ans, re.I):
254         print(f'\nVisiting all "patch/{args.master_branch}/*" branches ...')
255         cmd_run(f"packaging/patch-update --branch={args.master_branch} --skip-check --shell")
256
257     cmd_run("rm -f *.[o15] *.html")
258     cmd_chk('rsync -a SaVeDiR/ .'.split())
259
260     if os.path.isdir('patches/.git'):
261         s = cmd_run(f"cd patches && git commit -a -m 'The patches for {version}.'")
262         if s.returncode:
263             die('Aborting')
264
265     print(f"""\
266 {dash_line}
267
268 About to:
269     - create signed tag for this release: {v_ver}
270     - create release diffs, "{diff_name}"
271     - create release tar, "{srctar_name}"
272     - generate {rsync_ver}/patches/* files
273     - create patches tar, "{pattar_name}"
274     - update top-level README.md, NEWS.md, TODO, and ChangeLog
275     - update top-level rsync*.html manpages
276     - gpg-sign the release files
277     - update hard-linked top-level release files{skipping}
278 """)
279     ans = input("<Press Enter to continue> ")
280
281     # TODO: is there a better way to ensure that our passphrase is in the agent?
282     cmd_run("touch TeMp; gpg --sign TeMp; rm TeMp*")
283
284     out = cmd_txt(f"git tag -s -m 'Version {version}.' {v_ver}", capture='combined')
285     print(out, end='')
286     if 'bad passphrase' in out or 'failed' in out:
287         die('Aborting')
288
289     if os.path.isdir('patches/.git'):
290         out = cmd_txt(f"cd patches && git tag -s -m 'Version {version}.' {v_ver}", capture='combined')
291         print(out, end='')
292         if 'bad passphrase' in out or 'failed' in out:
293             die('Aborting')
294
295     os.environ['PATH'] = ORIGINAL_PATH
296
297     # Extract the generated files from the old tar.
298     tweaked_gen_files = [ f"{rsync_lastver}/{x}" for x in gen_files ]
299     cmd_run(['tar', 'xzf', lasttar_file, *tweaked_gen_files])
300     os.rename(rsync_lastver, 'a')
301
302     print(f"Creating {diff_file} ...")
303     cmd_chk(['rsync', '-a', *gen_files, 'b/'])
304
305     sed_script = r's:^((---|\+\+\+) [ab]/[^\t]+)\t.*:\1:' # CAUTION: must not contain any single quotes!
306     cmd_chk(f"(git diff v{lastversion} {v_ver} -- ':!.github'; diff -upN a b | sed -r '{sed_script}') | gzip -9 >{diff_file}")
307     shutil.rmtree('a')
308     os.rename('b', rsync_ver)
309
310     print(f"Creating {srctar_file} ...")
311     cmd_chk(f"git archive --format=tar --prefix={rsync_ver}/ {v_ver} | tar xf -")
312     cmd_chk(f"support/git-set-file-times --quiet --prefix={rsync_ver}/")
313     cmd_chk(['fakeroot', 'tar', 'czf', srctar_file, '--exclude=.github', rsync_ver])
314     shutil.rmtree(rsync_ver)
315
316     print(f'Updating files in "{rsync_ver}/patches" dir ...')
317     os.mkdir(rsync_ver, 0o755)
318     os.mkdir(f"{rsync_ver}/patches", 0o755)
319     cmd_chk(f"packaging/patch-update --skip-check --branch={args.master_branch} --gen={rsync_ver}/patches".split())
320
321     cmd_run("rm -f *.[o15] *.html")
322     cmd_chk('rsync -a SaVeDiR/ .'.split())
323     shutil.rmtree('SaVeDiR')
324     cmd_chk('make gen'.split())
325
326     print(f"Creating {pattar_file} ...")
327     cmd_chk(['fakeroot', 'tar', 'chzf', pattar_file, rsync_ver + '/patches'])
328     shutil.rmtree(rsync_ver)
329
330     print(f"Updating the other files in {dest} ...")
331     md_files = 'README.md NEWS.md'.split()
332     html_files = [ fn for fn in gen_files if fn.endswith('.html') ]
333     cmd_chk(['rsync', '-a', *md_files, *html_files, dest])
334     cmd_chk(["packaging/md2html"] + [ dest +'/'+ fn for fn in md_files ])
335
336     cmd_chk(f"git log --name-status | gzip -9 >{dest}/ChangeLog.gz")
337
338     for fn in (srctar_file, pattar_file, diff_file):
339         asc_fn = fn + '.asc'
340         if os.path.lexists(asc_fn):
341             os.unlink(asc_fn)
342         res = cmd_run(['gpg', '--batch', '-ba', fn])
343         if res.returncode != 0 and res.returncode != 2:
344             die("gpg signing failed")
345
346     if not pre:
347         for find in f'{dest}/rsync-*.gz {dest}/rsync-*.asc {dest}/src-previews/rsync-*diffs.gz*'.split():
348             for fn in glob.glob(find):
349                 os.unlink(fn)
350         top_link = [
351                 srctar_file, f"{srctar_file}.asc",
352                 pattar_file, f"{pattar_file}.asc",
353                 diff_file, f"{diff_file}.asc",
354                 ]
355         for fn in top_link:
356             os.link(fn, re.sub(r'/src(-\w+)?/', '/', fn))
357
358     print(f"""\
359 {dash_line}
360
361 Local changes are done.  When you're satisfied, push the git repository
362 and rsync the release files.  Remember to announce the release on *BOTH*
363 rsync-announce@lists.samba.org and rsync@lists.samba.org (and the web)!
364 """)
365
366
367 def replace_or_die(regex, repl, txt, die_msg):
368     m = regex.search(txt)
369     if not m:
370         die(die_msg)
371     return regex.sub(repl, txt, 1)
372
373
374 def signal_handler(sig, frame):
375     die("\nAborting due to SIGINT.")
376
377
378 if __name__ == '__main__':
379     parser = argparse.ArgumentParser(description="Prepare a new release of rsync in the git repo & ftp dir.", add_help=False)
380     parser.add_argument('--branch', '-b', dest='master_branch', default='master', help="The branch to release. Default: master.")
381     parser.add_argument("--help", "-h", action="help", help="Output this help message and exit.")
382     args = parser.parse_args()
383     main()
384
385 # vim: sw=4 et ft=python