release.py: sign tags when cutting releases.
[be.git] / release.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2009-2012 Chris Ball <cjb@laptop.org>
4 #                         W. Trevor King <wking@tremily.us>
5 #
6 # This file is part of Bugs Everywhere.
7 #
8 # Bugs Everywhere is free software: you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by the Free
10 # Software Foundation, either version 2 of the License, or (at your option) any
11 # later version.
12 #
13 # Bugs Everywhere is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
16 # more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
20
21 import optparse
22 import os
23 import os.path
24 import shutil
25 import string
26 import sys
27
28 from libbe.util.subproc import invoke
29
30
31 INITIAL_COMMIT = '1bf1ec598b436f41ff27094eddf0b28c797e359d'
32
33
34 def validate_tag(tag):
35     """
36     >>> validate_tag('1.0.0')
37     >>> validate_tag('A.B.C-r7')
38     >>> validate_tag('A.B.C r7')
39     Traceback (most recent call last):
40       ...
41     Exception: Invalid character ' ' in tag 'A.B.C r7'
42     >>> validate_tag('"')
43     Traceback (most recent call last):
44       ...
45     Exception: Invalid character '"' in tag '"'
46     >>> validate_tag("'")
47     Traceback (most recent call last):
48       ...
49     Exception: Invalid character ''' in tag '''
50     """
51     for char in tag:
52         if char in string.digits:
53             continue
54         elif char in string.letters:
55             continue
56         elif char in ['.','-']:
57             continue
58         raise Exception("Invalid character '%s' in tag '%s'" % (char, tag))
59
60 def pending_changes():
61     """Use `git diff`s output to detect change.
62     """
63     status,stdout,stderr = invoke(['git', 'diff', 'HEAD'])
64     if len(stdout) == 0:
65         return False
66     return True
67
68 def set_release_version(tag):
69     print "set libbe.version._VERSION = '%s'" % tag
70     invoke(['sed', '-i', "s/^[# ]*_VERSION *=.*/_VERSION = '%s'/" % tag,
71             os.path.join('libbe', 'version.py')])
72
73 def remove_makefile_libbe_version_dependencies(filename):
74     print "set %s LIBBE_VERSION :=" % filename
75     invoke(['sed', '-i', "s/^LIBBE_VERSION *:=.*/LIBBE_VERSION :=/",
76             filename])
77
78 def commit(commit_message):
79     print 'commit current status:', commit_message
80     invoke(['git', 'commit', '-a', '-m', commit_message])
81
82 def tag(tag):
83     print 'tag current revision', tag
84     invoke(['git', 'tag', '-s', '-m', 'version {}'.format(tag), tag])
85
86 def export(target_dir):
87     if not target_dir.endswith(os.path.sep):
88         target_dir += os.path.sep
89     print 'export current revision to', target_dir
90     status,stdout,stderr = invoke(
91         ['git', 'archive', '--prefix', target_dir, 'HEAD'],
92         unicode_output=False)
93     status,stdout,stderr = invoke(['tar', '-xv'], stdin=stdout)
94
95 def make_version():
96     print 'generate libbe/_version.py'
97     invoke(['make', os.path.join('libbe', '_version.py')])
98
99 def make_changelog(filename, tag):
100     """Generate a ChangeLog from the git history.
101
102     Not the most ChangeLog-esque format, but iterating through commits
103     by hand is just too slow.
104     """
105     print 'generate ChangeLog file', filename, 'up to tag', tag
106     invoke(['git', 'log', '--no-merges',
107             '%s..%s' % (INITIAL_COMMIT, tag)],
108            stdout=open(filename, 'w')),
109
110 def set_vcs_name(be_dir, vcs_name='None'):
111     """Exported directory is not a git repository, so set vcs_name to
112     something that will work.
113       vcs_name: new_vcs_name
114     """
115     for directory in os.listdir(be_dir):
116         if not os.path.isdir(os.path.join(be_dir, directory)):
117             continue
118         filename = os.path.join(be_dir, directory, 'settings')
119         if os.path.exists(filename):
120             print 'set vcs_name in', filename, 'to', vcs_name
121             invoke(['sed', '-i', "s/^vcs_name:.*/vcs_name: %s/" % vcs_name,
122                     filename])
123
124 def make_id_cache():
125     """Generate .be/id-cache so users won't need to.
126     """
127     invoke([sys.executable, './be', 'list'])
128
129 def create_tarball(tag):
130     release_name='be-%s' % tag
131     export_dir = release_name
132     export(export_dir)
133     make_version()
134     remove_makefile_libbe_version_dependencies(
135         os.path.join(export_dir, 'Makefile'))
136     print 'copy libbe/_version.py to %s/libbe/_version.py' % export_dir
137     shutil.copy(os.path.join('libbe', '_version.py'),
138                 os.path.join(export_dir, 'libbe', '_version.py'))
139     make_changelog(os.path.join(export_dir, 'ChangeLog'), tag)
140     make_id_cache()
141     print 'copy .be/id-cache to %s/.be/id-cache' % export_dir
142     shutil.copy(os.path.join('.be', 'id-cache'),
143                 os.path.join(export_dir, '.be', 'id-cache'))
144     set_vcs_name(os.path.join(export_dir, '.be'))
145     tarball_file = '%s.tar.gz' % release_name
146     print 'create tarball', tarball_file
147     invoke(['tar', '-czf', tarball_file, export_dir])
148     print 'remove', export_dir
149     shutil.rmtree(export_dir)
150
151 def test():
152     import doctest
153     doctest.testmod() 
154
155 def main(*args, **kwargs):
156     usage = """%prog [options] TAG
157
158 Create a git tag and a release tarball from the current revision.
159 For example
160   %prog 1.0.0
161
162 If you don't like what got committed, you can undo the release with
163   $ git tag -d 1.0.0
164   $ git reset --hard HEAD^
165 """
166     p = optparse.OptionParser(usage)
167     p.add_option('--test', dest='test', default=False,
168                  action='store_true', help='Run internal tests and exit')
169     options,args = p.parse_args(*args, **kwargs)
170
171     if options.test == True:
172         test()
173         sys.exit(0)
174
175     assert len(args) == 1, '%d (!= 1) arguments: %s' % (len(args), args)
176     _tag = args[0]
177     validate_tag(_tag)
178
179     if pending_changes() == True:
180         print "Handle pending changes before releasing."
181         sys.exit(1)
182     set_release_version(_tag)
183     print "Update copyright information..."
184     env = dict(os.environ)
185     pythonpath = os.path.abspath('update-copyright')
186     if 'PYTHONPATH' in env:
187         env['PYTHONPATH'] = '{}:{}'.format(pythonpath, env['PYTHONPATH'])
188     else:
189         env['PYTHONPATH'] = pythonpath
190     status,stdout,stderr = invoke([
191             os.path.join('update-copyright', 'bin', 'update-copyright.py')],
192             env=env)
193     commit("Bumped to version %s" % _tag)
194     tag(_tag)
195     create_tarball(_tag)
196
197
198 if __name__ == '__main__':
199     main()