Release 0.10
[0release.git] / release.py
blob85c40d72f761d2e4f40b5d90e035fd065a7eeff2
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 self_test_dir = os.path.dirname(os.path.join(impl.id, self_test))
24 print "Running self-test:", self_test
25 exitstatus = subprocess.call(['0launch', '--main', self_test, local_feed], cwd = self_test_dir)
26 if exitstatus:
27 raise SafeException("Self-test failed with exit status %d" % exitstatus)
29 def upload_archives(options, status, uploads):
30 # For each binary or source archive in uploads, ensure it is available
31 # from options.archive_dir_public_url
33 # We try to do all the uploads together first, and then verify them all
34 # afterwards. This is because we may have to wait for them to be moved
35 # from an incoming queue before we can test them.
37 # Ensure URL stem ends with a slash
38 archive_dir_public_url = options.archive_dir_public_url
39 if not archive_dir_public_url.endswith('/'):
40 archive_dir_public_url += '/'
42 def url(archive):
43 return archive_dir_public_url + 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 = options.archive_dir_public_url + '/' + 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 if os.path.exists(options.master_feed_file):
302 # Check we haven't already released this version
303 master = model.Interface(os.path.realpath(options.master_feed_file))
304 reader.update(master, master.uri, local = True)
305 existing_releases = [impl for impl in master.implementations.values() if impl.get_version() == status.release_version]
306 if len(existing_releases):
307 raise SafeException("Master feed %s already contains an implementation with version number %s!" % (options.master_feed_file, status.release_version))
309 # Merge the source and binary feeds together first, so
310 # that we update the master feed atomically and only
311 # have to sign it once.
312 shutil.copyfile(src_feed_name, 'merged.xml')
313 for b in compiler.get_binary_feeds():
314 support.publish('merged.xml', local = b)
316 support.publish(options.master_feed_file, local = 'merged.xml', xmlsign = True, key = options.key)
317 os.unlink('merged.xml')
319 status.updated_master_feed = 'true'
320 status.save()
322 # Copy files...
323 uploads = [os.path.basename(archive_file)]
324 for b in compiler.get_binary_feeds():
325 stream = file(b)
326 binary_feed = model.ZeroInstallFeed(qdom.parse(stream), local_path = b)
327 stream.close()
328 impl, = binary_feed.implementations.values()
329 uploads.append(os.path.basename(impl.download_sources[0].url))
331 upload_archives(options, status, uploads)
333 assert len(local_iface.feed_for) == 1
334 feed_base = os.path.dirname(local_iface.feed_for.keys()[0])
335 feed_files = [options.master_feed_file]
336 print "Upload %s into %s" % (', '.join(feed_files), feed_base)
337 cmd = options.master_feed_upload_command.strip()
338 if cmd:
339 support.show_and_run(cmd, feed_files)
340 else:
341 print "NOTE: No feed upload command set => you'll have to upload them yourself!"
343 print "Push changes to public SCM repository..."
344 public_repos = options.public_scm_repository
345 if public_repos:
346 scm.push_head_and_release(status.release_version)
347 else:
348 print "NOTE: No public repository set => you'll have to push the tag and trunk yourself."
350 os.unlink(support.release_status_file)
352 if status.head_before_release:
353 head = scm.get_head_revision()
354 if status.release_version:
355 print "RESUMING release of %s %s" % (local_iface.get_name(), status.release_version)
356 elif head == status.head_before_release:
357 print "Restarting release of %s (HEAD revision has not changed)" % local_iface.get_name()
358 else:
359 raise SafeException("Something went wrong with the last run:\n" +
360 "HEAD revision for last run was " + status.head_before_release + "\n" +
361 "HEAD revision now is " + head + "\n" +
362 "You should revert your working copy to the previous head and try again.\n" +
363 "If you're sure you want to release from the current head, delete '" + support.release_status_file + "'")
364 else:
365 print "Releasing", local_iface.get_name()
367 ensure_ready_to_release()
369 if status.release_version:
370 if not os.path.isdir(status.release_version):
371 raise SafeException("Can't resume; directory %s missing. Try deleting '%s'." % (status.release_version, support.release_status_file))
372 os.chdir(status.release_version)
373 need_set_snapshot = False
374 if status.tagged:
375 print "Already tagged. Resuming the publishing process..."
376 elif status.new_snapshot_version:
377 head = scm.get_head_revision()
378 if head != status.head_before_release:
379 raise SafeException("There are more commits since we started!\n"
380 "HEAD was " + status.head_before_release + "\n"
381 "HEAD now " + head + "\n"
382 "To include them, delete '" + support.release_status_file + "' and try again.\n"
383 "To leave them out, put them on a new branch and reset HEAD to the release version.")
384 else:
385 raise SafeException("Something went wrong previously when setting the new snapshot version.\n" +
386 "Suggest you reset to the original HEAD of\n%s and delete '%s'." % (status.head_before_release, support.release_status_file))
387 else:
388 set_to_release() # Changes directory
389 assert status.release_version
390 need_set_snapshot = True
392 archive_name = support.make_archive_name(local_iface.get_name(), status.release_version)
393 archive_file = archive_name + '.tar.bz2'
395 export_prefix = archive_name
396 if add_toplevel_dir is not None:
397 export_prefix += '/' + add_toplevel_dir
399 if status.created_archive and os.path.isfile(archive_file):
400 print "Archive already created"
401 else:
402 support.backup_if_exists(archive_file)
403 scm.export(export_prefix, archive_file, status.head_at_release)
405 has_submodules = scm.has_submodules()
407 if phase_actions['generate-archive'] or has_submodules:
408 try:
409 support.unpack_tarball(archive_file)
410 if has_submodules:
411 scm.export_submodules(archive_name)
412 run_hooks('generate-archive', cwd = archive_name, env = {'RELEASE_VERSION': status.release_version})
413 info("Regenerating archive (may have been modified by generate-archive hooks...")
414 support.check_call(['tar', 'cjf', archive_file, archive_name])
415 except SafeException:
416 scm.reset_hard(scm.get_current_branch())
417 fail_candidate(archive_file)
418 raise
420 status.created_archive = 'true'
421 status.save()
423 if need_set_snapshot:
424 set_to_snapshot(status.release_version + '-post')
425 # Revert back to the original revision, so that any fixes the user makes
426 # will get applied before the tag
427 scm.reset_hard(scm.get_current_branch())
429 #backup_if_exists(archive_name)
430 support.unpack_tarball(archive_file)
432 extracted_iface_path = os.path.abspath(os.path.join(export_prefix, local_iface_rel_root_path))
433 assert os.path.isfile(extracted_iface_path), "Local feed not in archive! Is it under version control?"
434 extracted_iface = model.Interface(extracted_iface_path)
435 reader.update(extracted_iface, extracted_iface_path, local = True)
436 extracted_impl = support.get_singleton_impl(extracted_iface)
438 if extracted_impl.main:
439 # Find main executable, relative to the archive root
440 abs_main = os.path.join(os.path.dirname(extracted_iface_path), extracted_impl.main)
441 main = support.relative_path(archive_name + '/', abs_main)
442 if main != extracted_impl.main:
443 print "(adjusting main: '%s' for the feed inside the archive, '%s' externally)" % (extracted_impl.main, main)
444 if not os.path.exists(abs_main):
445 raise SafeException("Main executable '%s' not found after unpacking archive!" % abs_main)
446 else:
447 main = None
449 try:
450 if status.src_tests_passed:
451 print "Unit-tests already passed - not running again"
452 else:
453 run_unit_tests(extracted_iface_path, extracted_impl)
454 status.src_tests_passed = True
455 status.save()
456 except SafeException:
457 print "(leaving extracted directory for examination)"
458 fail_candidate(archive_file)
459 raise
460 # Unpack it again in case the unit-tests changed anything
461 shutil.rmtree(archive_name)
462 support.unpack_tarball(archive_file)
464 # Generate feed for source
465 stream = open(extracted_iface_path)
466 src_feed_name = '%s.xml' % archive_name
467 create_feed(src_feed_name, extracted_iface_path, archive_file, archive_name, main)
468 print "Wrote source feed as %s" % src_feed_name
470 # If it's a source package, compile the binaries now...
471 compiler = compile.Compiler(options, os.path.abspath(src_feed_name))
472 compiler.build_binaries()
474 previous_release = get_previous_release(status.release_version)
475 export_changelog(previous_release)
477 if status.tagged:
478 raw_input('Already tagged. Press Return to resume publishing process...')
479 choice = 'Publish'
480 else:
481 print "\nCandidate release archive:", archive_file
482 print "(extracted to %s for inspection)" % os.path.abspath(archive_name)
484 print "\nPlease check candidate and select an action:"
485 print "P) Publish candidate (accept)"
486 print "F) Fail candidate (untag)"
487 if previous_release:
488 print "D) Diff against release archive for %s" % previous_release
489 maybe_diff = ['Diff']
490 else:
491 maybe_diff = []
492 print "(you can also hit CTRL-C and resume this script when done)"
494 while True:
495 choice = support.get_choice(['Publish', 'Fail'] + maybe_diff)
496 if choice == 'Diff':
497 previous_archive_name = support.make_archive_name(local_iface.get_name(), previous_release)
498 previous_archive_file = '../%s/%s.tar.bz2' % (previous_release, previous_archive_name)
500 # For archives created by older versions of 0release
501 if not os.path.isfile(previous_archive_file):
502 old_previous_archive_file = '../%s.tar.bz2' % previous_archive_name
503 if os.path.isfile(old_previous_archive_file):
504 previous_archive_file = old_previous_archive_file
506 if os.path.isfile(previous_archive_file):
507 support.unpack_tarball(previous_archive_file)
508 try:
509 support.show_diff(previous_archive_name, archive_name)
510 finally:
511 shutil.rmtree(previous_archive_name)
512 else:
513 # TODO: download it?
514 print "Sorry, archive file %s not found! Can't show diff." % previous_archive_file
515 else:
516 break
518 info("Deleting extracted archive %s", archive_name)
519 shutil.rmtree(archive_name)
521 if choice == 'Publish':
522 accept_and_publish(archive_file, archive_name, src_feed_name)
523 else:
524 assert choice == 'Fail'
525 fail_candidate(archive_file)