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