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