Cope with using a distribution version of 0install
[0release.git] / release.py
blob14bb25604bafde39a6ff0c25ca2d0c6828aa639d
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 if not local_iface.feed_for:
136 raise SafeException("Feed %s missing a <feed-for> element" % local_iface.uri)
138 status = support.Status()
139 local_impl = support.get_singleton_impl(local_iface)
141 local_impl_dir = local_impl.id
142 assert local_impl_dir.startswith('/')
143 local_impl_dir = os.path.realpath(local_impl_dir)
144 assert os.path.isdir(local_impl_dir)
145 assert local_iface.uri.startswith(local_impl_dir + '/')
147 # From the impl directory to the feed
148 # NOT relative to the archive root (in general)
149 local_iface_rel_path = local_iface.uri[len(local_impl_dir) + 1:]
150 assert not local_iface_rel_path.startswith('/')
151 assert os.path.isfile(os.path.join(local_impl_dir, local_iface_rel_path))
153 phase_actions = {}
154 for phase in valid_phases:
155 phase_actions[phase] = [] # List of <release:action> elements
157 add_toplevel_dir = None
158 release_management = local_iface.get_metadata(XMLNS_RELEASE, 'management')
159 if len(release_management) == 1:
160 info("Found <release:management> element.")
161 release_management = release_management[0]
162 for x in release_management.childNodes:
163 if x.uri == XMLNS_RELEASE and x.name == 'action':
164 phase = x.getAttribute('phase')
165 if phase not in valid_phases:
166 raise SafeException("Invalid action phase '%s' in local feed %s. Valid actions are:\n%s" % (phase, local_iface.uri, '\n'.join(valid_phases)))
167 phase_actions[phase].append(x.content)
168 elif x.uri == XMLNS_RELEASE and x.name == 'add-toplevel-directory':
169 add_toplevel_dir = local_iface.get_name()
170 else:
171 warn("Unknown <release:management> element: %s", x)
172 elif len(release_management) > 1:
173 raise SafeException("Multiple <release:management> sections in %s!" % local_iface)
174 else:
175 info("No <release:management> element found in local feed.")
177 scm = get_scm(local_iface, options)
179 # Path relative to the archive / SCM root
180 local_iface_rel_root_path = local_iface.uri[len(scm.root_dir) + 1:]
182 def run_hooks(phase, cwd, env):
183 info("Running hooks for phase '%s'" % phase)
184 full_env = os.environ.copy()
185 full_env.update(env)
186 for x in phase_actions[phase]:
187 print "[%s]: %s" % (phase, x)
188 support.check_call(x, shell = True, cwd = cwd, env = full_env)
190 def set_to_release():
191 print "Snapshot version is " + local_impl.get_version()
192 suggested = support.suggest_release_version(local_impl.get_version())
193 release_version = raw_input("Version number for new release [%s]: " % suggested)
194 if not release_version:
195 release_version = suggested
197 scm.ensure_no_tag(release_version)
199 status.head_before_release = scm.get_head_revision()
200 status.save()
202 working_copy = local_impl.id
203 run_hooks('commit-release', cwd = working_copy, env = {'RELEASE_VERSION': release_version})
205 print "Releasing version", release_version
206 support.publish(local_iface.uri, set_released = 'today', set_version = release_version)
208 support.backup_if_exists(release_version)
209 os.mkdir(release_version)
210 os.chdir(release_version)
212 status.old_snapshot_version = local_impl.get_version()
213 status.release_version = release_version
214 status.head_at_release = scm.commit('Release %s' % release_version, branch = TMP_BRANCH_NAME, parent = 'HEAD')
215 status.save()
217 def set_to_snapshot(snapshot_version):
218 assert snapshot_version.endswith('-post')
219 support.publish(local_iface.uri, set_released = '', set_version = snapshot_version)
220 scm.commit('Start development series %s' % snapshot_version, branch = TMP_BRANCH_NAME, parent = TMP_BRANCH_NAME)
221 status.new_snapshot_version = scm.get_head_revision()
222 status.save()
224 def ensure_ready_to_release():
225 if not options.master_feed_file:
226 raise SafeException("Master feed file not set! Check your configuration")
228 scm.ensure_committed()
229 scm.ensure_versioned(os.path.abspath(local_iface.uri))
230 info("No uncommitted changes. Good.")
231 # Not needed for GIT. For SCMs where tagging is expensive (e.g. svn) this might be useful.
232 #run_unit_tests(local_impl)
234 scm.grep('\(^\\|[^=]\)\<\\(TODO\\|XXX\\|FIXME\\)\>')
236 def create_feed(target_feed, local_iface_path, archive_file, archive_name, main):
237 shutil.copyfile(local_iface_path, target_feed)
239 support.publish(target_feed,
240 set_main = main,
241 archive_url = get_archive_url(options, status, os.path.basename(archive_file)),
242 archive_file = archive_file,
243 archive_extract = archive_name)
245 def get_previous_release(this_version):
246 """Return the highest numbered verison in the master feed before this_version.
247 @return: version, or None if there wasn't one"""
248 parsed_release_version = model.parse_version(this_version)
250 if os.path.exists(options.master_feed_file):
251 master = model.Interface(os.path.realpath(options.master_feed_file))
252 reader.update(master, master.uri, local = True)
253 versions = [impl.version for impl in master.implementations.values() if impl.version < parsed_release_version]
254 if versions:
255 return model.format_version(max(versions))
256 return None
258 def export_changelog(previous_release):
259 changelog = file('changelog-%s' % status.release_version, 'w')
260 try:
261 try:
262 scm.export_changelog(previous_release, status.head_before_release, changelog)
263 except SafeException, ex:
264 print "WARNING: Failed to generate changelog: " + str(ex)
265 else:
266 print "Wrote changelog from %s to here as %s" % (previous_release or 'start', changelog.name)
267 finally:
268 changelog.close()
270 def fail_candidate(archive_file):
271 cwd = os.getcwd()
272 assert cwd.endswith(status.release_version)
273 support.backup_if_exists(cwd)
274 scm.delete_branch(TMP_BRANCH_NAME)
275 os.unlink(support.release_status_file)
276 print "Restored to state before starting release. Make your fixes and try again..."
278 def accept_and_publish(archive_file, archive_name, src_feed_name):
279 assert options.master_feed_file
281 if not options.archive_dir_public_url:
282 raise SafeException("Archive directory public URL is not set! Edit configuration and try again.")
284 if status.tagged:
285 print "Already tagged in SCM. Not re-tagging."
286 else:
287 scm.ensure_committed()
288 head = scm.get_head_revision()
289 if head != status.head_before_release:
290 raise SafeException("Changes committed since we started!\n" +
291 "HEAD was " + status.head_before_release + "\n"
292 "HEAD now " + head)
294 scm.tag(status.release_version, status.head_at_release)
295 scm.reset_hard(TMP_BRANCH_NAME)
296 scm.delete_branch(TMP_BRANCH_NAME)
298 status.tagged = 'true'
299 status.save()
301 if status.updated_master_feed:
302 print "Already added to master feed. Not changing."
303 else:
304 publish_opts = {}
305 if os.path.exists(options.master_feed_file):
306 # Check we haven't already released this version
307 master = model.Interface(os.path.realpath(options.master_feed_file))
308 reader.update(master, master.uri, local = True)
309 existing_releases = [impl for impl in master.implementations.values() if impl.get_version() == status.release_version]
310 if len(existing_releases):
311 raise SafeException("Master feed %s already contains an implementation with version number %s!" % (options.master_feed_file, status.release_version))
313 previous_release = get_previous_release(status.release_version)
314 previous_testing_releases = [impl for impl in master.implementations.values() if impl.get_version() == previous_release
315 and impl.upstream_stability == model.stability_levels["testing"]]
316 if previous_testing_releases:
317 print "The previous release, version %s, is still marked as 'testing'. Set to stable?" % previous_release
318 if support.get_choice(['Yes', 'No']) == 'Yes':
319 publish_opts['select_version'] = previous_release
320 publish_opts['set_stability'] = "stable"
322 # Merge the source and binary feeds together first, so
323 # that we update the master feed atomically and only
324 # have to sign it once.
325 shutil.copyfile(src_feed_name, 'merged.xml')
326 for b in compiler.get_binary_feeds():
327 support.publish('merged.xml', local = b)
329 support.publish(options.master_feed_file, local = 'merged.xml', xmlsign = True, key = options.key, **publish_opts)
330 os.unlink('merged.xml')
332 status.updated_master_feed = 'true'
333 status.save()
335 # Copy files...
336 uploads = [os.path.basename(archive_file)]
337 for b in compiler.get_binary_feeds():
338 stream = file(b)
339 binary_feed = model.ZeroInstallFeed(qdom.parse(stream), local_path = b)
340 stream.close()
341 impl, = binary_feed.implementations.values()
342 uploads.append(os.path.basename(impl.download_sources[0].url))
344 upload_archives(options, status, uploads)
346 assert len(local_iface.feed_for) == 1
347 feed_base = os.path.dirname(local_iface.feed_for.keys()[0])
348 feed_files = [options.master_feed_file]
349 print "Upload %s into %s" % (', '.join(feed_files), feed_base)
350 cmd = options.master_feed_upload_command.strip()
351 if cmd:
352 support.show_and_run(cmd, feed_files)
353 else:
354 print "NOTE: No feed upload command set => you'll have to upload them yourself!"
356 print "Push changes to public SCM repository..."
357 public_repos = options.public_scm_repository
358 if public_repos:
359 scm.push_head_and_release(status.release_version)
360 else:
361 print "NOTE: No public repository set => you'll have to push the tag and trunk yourself."
363 os.unlink(support.release_status_file)
365 if status.head_before_release:
366 head = scm.get_head_revision()
367 if status.release_version:
368 print "RESUMING release of %s %s" % (local_iface.get_name(), status.release_version)
369 elif head == status.head_before_release:
370 print "Restarting release of %s (HEAD revision has not changed)" % local_iface.get_name()
371 else:
372 raise SafeException("Something went wrong with the last run:\n" +
373 "HEAD revision for last run was " + status.head_before_release + "\n" +
374 "HEAD revision now is " + head + "\n" +
375 "You should revert your working copy to the previous head and try again.\n" +
376 "If you're sure you want to release from the current head, delete '" + support.release_status_file + "'")
377 else:
378 print "Releasing", local_iface.get_name()
380 ensure_ready_to_release()
382 if status.release_version:
383 if not os.path.isdir(status.release_version):
384 raise SafeException("Can't resume; directory %s missing. Try deleting '%s'." % (status.release_version, support.release_status_file))
385 os.chdir(status.release_version)
386 need_set_snapshot = False
387 if status.tagged:
388 print "Already tagged. Resuming the publishing process..."
389 elif status.new_snapshot_version:
390 head = scm.get_head_revision()
391 if head != status.head_before_release:
392 raise SafeException("There are more commits since we started!\n"
393 "HEAD was " + status.head_before_release + "\n"
394 "HEAD now " + head + "\n"
395 "To include them, delete '" + support.release_status_file + "' and try again.\n"
396 "To leave them out, put them on a new branch and reset HEAD to the release version.")
397 else:
398 raise SafeException("Something went wrong previously when setting the new snapshot version.\n" +
399 "Suggest you reset to the original HEAD of\n%s and delete '%s'." % (status.head_before_release, support.release_status_file))
400 else:
401 set_to_release() # Changes directory
402 assert status.release_version
403 need_set_snapshot = True
405 # May be needed by the upload command
406 os.environ['RELEASE_VERSION'] = status.release_version
408 archive_name = support.make_archive_name(local_iface.get_name(), status.release_version)
409 archive_file = archive_name + '.tar.bz2'
411 export_prefix = archive_name
412 if add_toplevel_dir is not None:
413 export_prefix += '/' + add_toplevel_dir
415 if status.created_archive and os.path.isfile(archive_file):
416 print "Archive already created"
417 else:
418 support.backup_if_exists(archive_file)
419 scm.export(export_prefix, archive_file, status.head_at_release)
421 has_submodules = scm.has_submodules()
423 if phase_actions['generate-archive'] or has_submodules:
424 try:
425 support.unpack_tarball(archive_file)
426 if has_submodules:
427 scm.export_submodules(archive_name)
428 run_hooks('generate-archive', cwd = archive_name, env = {'RELEASE_VERSION': status.release_version})
429 info("Regenerating archive (may have been modified by generate-archive hooks...")
430 support.check_call(['tar', 'cjf', archive_file, archive_name])
431 except SafeException:
432 scm.reset_hard(scm.get_current_branch())
433 fail_candidate(archive_file)
434 raise
436 status.created_archive = 'true'
437 status.save()
439 if need_set_snapshot:
440 set_to_snapshot(status.release_version + '-post')
441 # Revert back to the original revision, so that any fixes the user makes
442 # will get applied before the tag
443 scm.reset_hard(scm.get_current_branch())
445 #backup_if_exists(archive_name)
446 support.unpack_tarball(archive_file)
448 extracted_iface_path = os.path.abspath(os.path.join(export_prefix, local_iface_rel_root_path))
449 assert os.path.isfile(extracted_iface_path), "Local feed not in archive! Is it under version control?"
450 extracted_iface = model.Interface(extracted_iface_path)
451 reader.update(extracted_iface, extracted_iface_path, local = True)
452 extracted_impl = support.get_singleton_impl(extracted_iface)
454 if extracted_impl.main:
455 # Find main executable, relative to the archive root
456 abs_main = os.path.join(os.path.dirname(extracted_iface_path), extracted_impl.id, extracted_impl.main)
457 main = support.relative_path(archive_name + '/', abs_main)
458 if main != extracted_impl.main:
459 print "(adjusting main: '%s' for the feed inside the archive, '%s' externally)" % (extracted_impl.main, main)
460 if not os.path.exists(abs_main):
461 raise SafeException("Main executable '%s' not found after unpacking archive!" % abs_main)
462 else:
463 main = None
465 try:
466 if status.src_tests_passed:
467 print "Unit-tests already passed - not running again"
468 else:
469 run_unit_tests(extracted_iface_path, extracted_impl)
470 status.src_tests_passed = True
471 status.save()
472 except SafeException:
473 print "(leaving extracted directory for examination)"
474 fail_candidate(archive_file)
475 raise
476 # Unpack it again in case the unit-tests changed anything
477 shutil.rmtree(archive_name)
478 support.unpack_tarball(archive_file)
480 # Generate feed for source
481 stream = open(extracted_iface_path)
482 src_feed_name = '%s.xml' % archive_name
483 create_feed(src_feed_name, extracted_iface_path, archive_file, archive_name, main)
484 print "Wrote source feed as %s" % src_feed_name
486 # If it's a source package, compile the binaries now...
487 compiler = compile.Compiler(options, os.path.abspath(src_feed_name))
488 compiler.build_binaries()
490 previous_release = get_previous_release(status.release_version)
491 export_changelog(previous_release)
493 if status.tagged:
494 raw_input('Already tagged. Press Return to resume publishing process...')
495 choice = 'Publish'
496 else:
497 print "\nCandidate release archive:", archive_file
498 print "(extracted to %s for inspection)" % os.path.abspath(archive_name)
500 print "\nPlease check candidate and select an action:"
501 print "P) Publish candidate (accept)"
502 print "F) Fail candidate (untag)"
503 if previous_release:
504 print "D) Diff against release archive for %s" % previous_release
505 maybe_diff = ['Diff']
506 else:
507 maybe_diff = []
508 print "(you can also hit CTRL-C and resume this script when done)"
510 while True:
511 choice = support.get_choice(['Publish', 'Fail'] + maybe_diff)
512 if choice == 'Diff':
513 previous_archive_name = support.make_archive_name(local_iface.get_name(), previous_release)
514 previous_archive_file = '../%s/%s.tar.bz2' % (previous_release, previous_archive_name)
516 # For archives created by older versions of 0release
517 if not os.path.isfile(previous_archive_file):
518 old_previous_archive_file = '../%s.tar.bz2' % previous_archive_name
519 if os.path.isfile(old_previous_archive_file):
520 previous_archive_file = old_previous_archive_file
522 if os.path.isfile(previous_archive_file):
523 support.unpack_tarball(previous_archive_file)
524 try:
525 support.show_diff(previous_archive_name, archive_name)
526 finally:
527 shutil.rmtree(previous_archive_name)
528 else:
529 # TODO: download it?
530 print "Sorry, archive file %s not found! Can't show diff." % previous_archive_file
531 else:
532 break
534 info("Deleting extracted archive %s", archive_name)
535 shutil.rmtree(archive_name)
537 if choice == 'Publish':
538 accept_and_publish(archive_file, archive_name, src_feed_name)
539 else:
540 assert choice == 'Fail'
541 fail_candidate(archive_file)