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