Updated for Git 1.7
[0release.git] / release.py
blob53eb4558387fd916975e47382ccc7aa67cb3f73d
1 # Copyright (C) 2009, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import os, sys, subprocess, shutil, tempfile
5 from zeroinstall import SafeException
6 from zeroinstall.injector import reader, model, qdom
7 from logging import info, warn
9 import support, compile
10 from scm import get_scm
12 XMLNS_RELEASE = 'http://zero-install.sourceforge.net/2007/namespaces/0release'
14 valid_phases = ['commit-release', 'generate-archive']
16 TMP_BRANCH_NAME = '0release-tmp'
18 def run_unit_tests(local_feed, impl):
19 self_test = impl.metadata.get('self-test', None)
20 if self_test is None:
21 print "SKIPPING unit tests for %s (no 'self-test' attribute set)" % impl
22 return
23 print "Running self-test:", self_test
24 exitstatus = subprocess.call(['0launch', 'http://0install.net/2008/interfaces/0test.xml', local_feed])
25 if exitstatus:
26 raise SafeException("Self-test failed with exit status %d" % exitstatus)
28 def get_archive_url(options, status, archive):
29 archive_dir_public_url = options.archive_dir_public_url.replace('$RELEASE_VERSION', status.release_version)
30 if not archive_dir_public_url.endswith('/'):
31 archive_dir_public_url += '/'
32 return archive_dir_public_url + archive
34 def upload_archives(options, status, uploads):
35 # For each binary or source archive in uploads, ensure it is available
36 # from options.archive_dir_public_url
38 # We try to do all the uploads together first, and then verify them all
39 # afterwards. This is because we may have to wait for them to be moved
40 # from an incoming queue before we can test them.
42 def url(archive):
43 return get_archive_url(options, status, archive)
45 # Check that url exists and has the given size
46 def is_uploaded(url, size):
47 if url.startswith('http://TESTING/releases'):
48 return True
50 print "Testing URL %s..." % url
51 try:
52 actual_size = int(support.get_size(url))
53 except Exception, ex:
54 print "Can't get size of '%s': %s" % (url, ex)
55 return False
56 else:
57 if actual_size == size:
58 return True
59 print "WARNING: %s exists, but size is %d, not %d!" % (url, actual_size, size)
60 return False
62 # status.verified_uploads is an array of status flags:
63 description = {
64 'N': 'Upload required',
65 'A': 'Upload has been attempted, but we need to check whether it worked',
66 'V': 'Upload has been checked (exists and has correct size)',
69 if status.verified_uploads is None:
70 # First time around; no point checking for existing uploads
71 status.verified_uploads = 'N' * len(uploads)
72 status.save()
74 while True:
75 print "\nUpload status:"
76 for i, stat in enumerate(status.verified_uploads):
77 print "- %s : %s" % (uploads[i], description[stat])
78 print
80 # Break if finished
81 if status.verified_uploads == 'V' * len(uploads):
82 break
84 # Find all New archives
85 to_upload = []
86 for i, stat in enumerate(status.verified_uploads):
87 assert stat in 'NAV'
88 if stat == 'N':
89 to_upload.append(uploads[i])
90 print "Upload %s/%s as %s" % (status.release_version, uploads[i], url(uploads[i]))
92 cmd = options.archive_upload_command.strip()
94 if to_upload:
95 # Mark all New items as Attempted
96 status.verified_uploads = status.verified_uploads.replace('N', 'A')
97 status.save()
99 # Upload them...
100 if cmd:
101 support.show_and_run(cmd, to_upload)
102 else:
103 if len(to_upload) == 1:
104 print "No upload command is set => please upload the archive manually now"
105 raw_input('Press Return once the archive is uploaded.')
106 else:
107 print "No upload command is set => please upload the archives manually now"
108 raw_input('Press Return once the %d archives are uploaded.' % len(to_upload))
110 # Verify all Attempted uploads
111 new_stat = ''
112 for i, stat in enumerate(status.verified_uploads):
113 assert stat in 'AV', status.verified_uploads
114 if stat == 'A' :
115 if not is_uploaded(url(uploads[i]), os.path.getsize(uploads[i])):
116 print "** Archive '%s' still not uploaded! Try again..." % uploads[i]
117 stat = 'N'
118 else:
119 stat = 'V'
120 new_stat += stat
122 status.verified_uploads = new_stat
123 status.save()
125 if 'N' in new_stat and cmd:
126 raw_input('Press Return to try again.')
128 def do_release(local_iface, options):
129 assert options.master_feed_file
130 options.master_feed_file = os.path.abspath(options.master_feed_file)
132 if not options.archive_dir_public_url:
133 raise SafeException("Downloads directory not set. Edit the 'make-release' script and try again.")
135 status = support.Status()
136 local_impl = support.get_singleton_impl(local_iface)
138 local_impl_dir = local_impl.id
139 assert local_impl_dir.startswith('/')
140 local_impl_dir = os.path.realpath(local_impl_dir)
141 assert os.path.isdir(local_impl_dir)
142 assert local_iface.uri.startswith(local_impl_dir + '/')
144 # From the impl directory to the feed
145 # NOT relative to the archive root (in general)
146 local_iface_rel_path = local_iface.uri[len(local_impl_dir) + 1:]
147 assert not local_iface_rel_path.startswith('/')
148 assert os.path.isfile(os.path.join(local_impl_dir, local_iface_rel_path))
150 phase_actions = {}
151 for phase in valid_phases:
152 phase_actions[phase] = [] # List of <release:action> elements
154 add_toplevel_dir = None
155 release_management = local_iface.get_metadata(XMLNS_RELEASE, 'management')
156 if len(release_management) == 1:
157 info("Found <release:management> element.")
158 release_management = release_management[0]
159 for x in release_management.childNodes:
160 if x.uri == XMLNS_RELEASE and x.name == 'action':
161 phase = x.getAttribute('phase')
162 if phase not in valid_phases:
163 raise SafeException("Invalid action phase '%s' in local feed %s. Valid actions are:\n%s" % (phase, local_iface.uri, '\n'.join(valid_phases)))
164 phase_actions[phase].append(x.content)
165 elif x.uri == XMLNS_RELEASE and x.name == 'add-toplevel-directory':
166 add_toplevel_dir = local_iface.get_name()
167 else:
168 warn("Unknown <release:management> element: %s", x)
169 elif len(release_management) > 1:
170 raise SafeException("Multiple <release:management> sections in %s!" % local_iface)
171 else:
172 info("No <release:management> element found in local feed.")
174 scm = get_scm(local_iface, options)
176 # Path relative to the archive / SCM root
177 local_iface_rel_root_path = local_iface.uri[len(scm.root_dir) + 1:]
179 def run_hooks(phase, cwd, env):
180 info("Running hooks for phase '%s'" % phase)
181 full_env = os.environ.copy()
182 full_env.update(env)
183 for x in phase_actions[phase]:
184 print "[%s]: %s" % (phase, x)
185 support.check_call(x, shell = True, cwd = cwd, env = full_env)
187 def set_to_release():
188 print "Snapshot version is " + local_impl.get_version()
189 suggested = support.suggest_release_version(local_impl.get_version())
190 release_version = raw_input("Version number for new release [%s]: " % suggested)
191 if not release_version:
192 release_version = suggested
194 scm.ensure_no_tag(release_version)
196 status.head_before_release = scm.get_head_revision()
197 status.save()
199 working_copy = local_impl.id
200 run_hooks('commit-release', cwd = working_copy, env = {'RELEASE_VERSION': release_version})
202 print "Releasing version", release_version
203 support.publish(local_iface.uri, set_released = 'today', set_version = release_version)
205 support.backup_if_exists(release_version)
206 os.mkdir(release_version)
207 os.chdir(release_version)
209 status.old_snapshot_version = local_impl.get_version()
210 status.release_version = release_version
211 status.head_at_release = scm.commit('Release %s' % release_version, branch = TMP_BRANCH_NAME, parent = 'HEAD')
212 status.save()
214 def set_to_snapshot(snapshot_version):
215 assert snapshot_version.endswith('-post')
216 support.publish(local_iface.uri, set_released = '', set_version = snapshot_version)
217 scm.commit('Start development series %s' % snapshot_version, branch = TMP_BRANCH_NAME, parent = TMP_BRANCH_NAME)
218 status.new_snapshot_version = scm.get_head_revision()
219 status.save()
221 def ensure_ready_to_release():
222 if not options.master_feed_file:
223 raise SafeException("Master feed file not set! Check your configuration")
225 scm.ensure_committed()
226 scm.ensure_versioned(os.path.abspath(local_iface.uri))
227 info("No uncommitted changes. Good.")
228 # Not needed for GIT. For SCMs where tagging is expensive (e.g. svn) this might be useful.
229 #run_unit_tests(local_impl)
231 scm.grep('\(^\\|[^=]\)\<\\(TODO\\|XXX\\|FIXME\\)\>')
233 def create_feed(target_feed, local_iface_path, archive_file, archive_name, main):
234 shutil.copyfile(local_iface_path, target_feed)
236 support.publish(target_feed,
237 set_main = main,
238 archive_url = get_archive_url(options, status, os.path.basename(archive_file)),
239 archive_file = archive_file,
240 archive_extract = archive_name)
242 def get_previous_release(this_version):
243 """Return the highest numbered verison in the master feed before this_version.
244 @return: version, or None if there wasn't one"""
245 parsed_release_version = model.parse_version(this_version)
247 if os.path.exists(options.master_feed_file):
248 master = model.Interface(os.path.realpath(options.master_feed_file))
249 reader.update(master, master.uri, local = True)
250 versions = [impl.version for impl in master.implementations.values() if impl.version < parsed_release_version]
251 if versions:
252 return model.format_version(max(versions))
253 return None
255 def export_changelog(previous_release):
256 changelog = file('changelog-%s' % status.release_version, 'w')
257 try:
258 try:
259 scm.export_changelog(previous_release, status.head_before_release, changelog)
260 except SafeException, ex:
261 print "WARNING: Failed to generate changelog: " + str(ex)
262 else:
263 print "Wrote changelog from %s to here as %s" % (previous_release or 'start', changelog.name)
264 finally:
265 changelog.close()
267 def fail_candidate(archive_file):
268 cwd = os.getcwd()
269 assert cwd.endswith(status.release_version)
270 support.backup_if_exists(cwd)
271 scm.delete_branch(TMP_BRANCH_NAME)
272 os.unlink(support.release_status_file)
273 print "Restored to state before starting release. Make your fixes and try again..."
275 def accept_and_publish(archive_file, archive_name, src_feed_name):
276 assert options.master_feed_file
278 if not options.archive_dir_public_url:
279 raise SafeException("Archive directory public URL is not set! Edit configuration and try again.")
281 if status.tagged:
282 print "Already tagged in SCM. Not re-tagging."
283 else:
284 scm.ensure_committed()
285 head = scm.get_head_revision()
286 if head != status.head_before_release:
287 raise SafeException("Changes committed since we started!\n" +
288 "HEAD was " + status.head_before_release + "\n"
289 "HEAD now " + head)
291 scm.tag(status.release_version, status.head_at_release)
292 scm.reset_hard(TMP_BRANCH_NAME)
293 scm.delete_branch(TMP_BRANCH_NAME)
295 status.tagged = 'true'
296 status.save()
298 if status.updated_master_feed:
299 print "Already added to master feed. Not changing."
300 else:
301 publish_opts = {}
302 if os.path.exists(options.master_feed_file):
303 # Check we haven't already released this version
304 master = model.Interface(os.path.realpath(options.master_feed_file))
305 reader.update(master, master.uri, local = True)
306 existing_releases = [impl for impl in master.implementations.values() if impl.get_version() == status.release_version]
307 if len(existing_releases):
308 raise SafeException("Master feed %s already contains an implementation with version number %s!" % (options.master_feed_file, status.release_version))
310 previous_release = get_previous_release(status.release_version)
311 previous_testing_releases = [impl for impl in master.implementations.values() if impl.get_version() == previous_release
312 and impl.upstream_stability == model.stability_levels["testing"]]
313 if previous_testing_releases:
314 print "The previous release, version %s, is still marked as 'testing'. Set to stable?" % previous_release
315 if support.get_choice(['Yes', 'No']) == 'Yes':
316 publish_opts['select_version'] = previous_release
317 publish_opts['set_stability'] = "stable"
319 # Merge the source and binary feeds together first, so
320 # that we update the master feed atomically and only
321 # have to sign it once.
322 shutil.copyfile(src_feed_name, 'merged.xml')
323 for b in compiler.get_binary_feeds():
324 support.publish('merged.xml', local = b)
326 support.publish(options.master_feed_file, local = 'merged.xml', xmlsign = True, key = options.key, **publish_opts)
327 os.unlink('merged.xml')
329 status.updated_master_feed = 'true'
330 status.save()
332 # Copy files...
333 uploads = [os.path.basename(archive_file)]
334 for b in compiler.get_binary_feeds():
335 stream = file(b)
336 binary_feed = model.ZeroInstallFeed(qdom.parse(stream), local_path = b)
337 stream.close()
338 impl, = binary_feed.implementations.values()
339 uploads.append(os.path.basename(impl.download_sources[0].url))
341 upload_archives(options, status, uploads)
343 assert len(local_iface.feed_for) == 1
344 feed_base = os.path.dirname(local_iface.feed_for.keys()[0])
345 feed_files = [options.master_feed_file]
346 print "Upload %s into %s" % (', '.join(feed_files), feed_base)
347 cmd = options.master_feed_upload_command.strip()
348 if cmd:
349 support.show_and_run(cmd, feed_files)
350 else:
351 print "NOTE: No feed upload command set => you'll have to upload them yourself!"
353 print "Push changes to public SCM repository..."
354 public_repos = options.public_scm_repository
355 if public_repos:
356 scm.push_head_and_release(status.release_version)
357 else:
358 print "NOTE: No public repository set => you'll have to push the tag and trunk yourself."
360 os.unlink(support.release_status_file)
362 if status.head_before_release:
363 head = scm.get_head_revision()
364 if status.release_version:
365 print "RESUMING release of %s %s" % (local_iface.get_name(), status.release_version)
366 elif head == status.head_before_release:
367 print "Restarting release of %s (HEAD revision has not changed)" % local_iface.get_name()
368 else:
369 raise SafeException("Something went wrong with the last run:\n" +
370 "HEAD revision for last run was " + status.head_before_release + "\n" +
371 "HEAD revision now is " + head + "\n" +
372 "You should revert your working copy to the previous head and try again.\n" +
373 "If you're sure you want to release from the current head, delete '" + support.release_status_file + "'")
374 else:
375 print "Releasing", local_iface.get_name()
377 ensure_ready_to_release()
379 if status.release_version:
380 if not os.path.isdir(status.release_version):
381 raise SafeException("Can't resume; directory %s missing. Try deleting '%s'." % (status.release_version, support.release_status_file))
382 os.chdir(status.release_version)
383 need_set_snapshot = False
384 if status.tagged:
385 print "Already tagged. Resuming the publishing process..."
386 elif status.new_snapshot_version:
387 head = scm.get_head_revision()
388 if head != status.head_before_release:
389 raise SafeException("There are more commits since we started!\n"
390 "HEAD was " + status.head_before_release + "\n"
391 "HEAD now " + head + "\n"
392 "To include them, delete '" + support.release_status_file + "' and try again.\n"
393 "To leave them out, put them on a new branch and reset HEAD to the release version.")
394 else:
395 raise SafeException("Something went wrong previously when setting the new snapshot version.\n" +
396 "Suggest you reset to the original HEAD of\n%s and delete '%s'." % (status.head_before_release, support.release_status_file))
397 else:
398 set_to_release() # Changes directory
399 assert status.release_version
400 need_set_snapshot = True
402 # May be needed by the upload command
403 os.environ['RELEASE_VERSION'] = status.release_version
405 archive_name = support.make_archive_name(local_iface.get_name(), status.release_version)
406 archive_file = archive_name + '.tar.bz2'
408 export_prefix = archive_name
409 if add_toplevel_dir is not None:
410 export_prefix += '/' + add_toplevel_dir
412 if status.created_archive and os.path.isfile(archive_file):
413 print "Archive already created"
414 else:
415 support.backup_if_exists(archive_file)
416 scm.export(export_prefix, archive_file, status.head_at_release)
418 has_submodules = scm.has_submodules()
420 if phase_actions['generate-archive'] or has_submodules:
421 try:
422 support.unpack_tarball(archive_file)
423 if has_submodules:
424 scm.export_submodules(archive_name)
425 run_hooks('generate-archive', cwd = archive_name, env = {'RELEASE_VERSION': status.release_version})
426 info("Regenerating archive (may have been modified by generate-archive hooks...")
427 support.check_call(['tar', 'cjf', archive_file, archive_name])
428 except SafeException:
429 scm.reset_hard(scm.get_current_branch())
430 fail_candidate(archive_file)
431 raise
433 status.created_archive = 'true'
434 status.save()
436 if need_set_snapshot:
437 set_to_snapshot(status.release_version + '-post')
438 # Revert back to the original revision, so that any fixes the user makes
439 # will get applied before the tag
440 scm.reset_hard(scm.get_current_branch())
442 #backup_if_exists(archive_name)
443 support.unpack_tarball(archive_file)
445 extracted_iface_path = os.path.abspath(os.path.join(export_prefix, local_iface_rel_root_path))
446 assert os.path.isfile(extracted_iface_path), "Local feed not in archive! Is it under version control?"
447 extracted_iface = model.Interface(extracted_iface_path)
448 reader.update(extracted_iface, extracted_iface_path, local = True)
449 extracted_impl = support.get_singleton_impl(extracted_iface)
451 if extracted_impl.main:
452 # Find main executable, relative to the archive root
453 abs_main = os.path.join(os.path.dirname(extracted_iface_path), extracted_impl.id, extracted_impl.main)
454 main = support.relative_path(archive_name + '/', abs_main)
455 if main != extracted_impl.main:
456 print "(adjusting main: '%s' for the feed inside the archive, '%s' externally)" % (extracted_impl.main, main)
457 if not os.path.exists(abs_main):
458 raise SafeException("Main executable '%s' not found after unpacking archive!" % abs_main)
459 else:
460 main = None
462 try:
463 if status.src_tests_passed:
464 print "Unit-tests already passed - not running again"
465 else:
466 run_unit_tests(extracted_iface_path, extracted_impl)
467 status.src_tests_passed = True
468 status.save()
469 except SafeException:
470 print "(leaving extracted directory for examination)"
471 fail_candidate(archive_file)
472 raise
473 # Unpack it again in case the unit-tests changed anything
474 shutil.rmtree(archive_name)
475 support.unpack_tarball(archive_file)
477 # Generate feed for source
478 stream = open(extracted_iface_path)
479 src_feed_name = '%s.xml' % archive_name
480 create_feed(src_feed_name, extracted_iface_path, archive_file, archive_name, main)
481 print "Wrote source feed as %s" % src_feed_name
483 # If it's a source package, compile the binaries now...
484 compiler = compile.Compiler(options, os.path.abspath(src_feed_name))
485 compiler.build_binaries()
487 previous_release = get_previous_release(status.release_version)
488 export_changelog(previous_release)
490 if status.tagged:
491 raw_input('Already tagged. Press Return to resume publishing process...')
492 choice = 'Publish'
493 else:
494 print "\nCandidate release archive:", archive_file
495 print "(extracted to %s for inspection)" % os.path.abspath(archive_name)
497 print "\nPlease check candidate and select an action:"
498 print "P) Publish candidate (accept)"
499 print "F) Fail candidate (untag)"
500 if previous_release:
501 print "D) Diff against release archive for %s" % previous_release
502 maybe_diff = ['Diff']
503 else:
504 maybe_diff = []
505 print "(you can also hit CTRL-C and resume this script when done)"
507 while True:
508 choice = support.get_choice(['Publish', 'Fail'] + maybe_diff)
509 if choice == 'Diff':
510 previous_archive_name = support.make_archive_name(local_iface.get_name(), previous_release)
511 previous_archive_file = '../%s/%s.tar.bz2' % (previous_release, previous_archive_name)
513 # For archives created by older versions of 0release
514 if not os.path.isfile(previous_archive_file):
515 old_previous_archive_file = '../%s.tar.bz2' % previous_archive_name
516 if os.path.isfile(old_previous_archive_file):
517 previous_archive_file = old_previous_archive_file
519 if os.path.isfile(previous_archive_file):
520 support.unpack_tarball(previous_archive_file)
521 try:
522 support.show_diff(previous_archive_name, archive_name)
523 finally:
524 shutil.rmtree(previous_archive_name)
525 else:
526 # TODO: download it?
527 print "Sorry, archive file %s not found! Can't show diff." % previous_archive_file
528 else:
529 break
531 info("Deleting extracted archive %s", archive_name)
532 shutil.rmtree(archive_name)
534 if choice == 'Publish':
535 accept_and_publish(archive_file, archive_name, src_feed_name)
536 else:
537 assert choice == 'Fail'
538 fail_candidate(archive_file)