1 # Copyright (C) 2009, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import os
, subprocess
, shutil
5 from zeroinstall
import SafeException
6 from zeroinstall
.injector
import model
7 from zeroinstall
.support
import ro_rmtree
8 from logging
import info
, warn
10 import support
, compile
11 from scm
import get_scm
13 XMLNS_RELEASE
= 'http://zero-install.sourceforge.net/2007/namespaces/0release'
15 valid_phases
= ['commit-release', 'generate-archive']
17 TMP_BRANCH_NAME
= '0release-tmp'
19 test_command
= os
.environ
['0TEST']
21 def run_unit_tests(local_feed
):
22 print "Running self-tests..."
23 exitstatus
= subprocess
.call([test_command
, '--', local_feed
])
25 print "SKIPPED unit tests for %s (no 'self-test' attribute set)" % local_feed
28 raise SafeException("Self-test failed with exit status %d" % exitstatus
)
30 def upload_archives(options
, status
, uploads
):
31 # For each binary or source archive in uploads, ensure it is available
32 # from options.archive_dir_public_url
34 # We try to do all the uploads together first, and then verify them all
35 # afterwards. This is because we may have to wait for them to be moved
36 # from an incoming queue before we can test them.
39 return support
.get_archive_url(options
, status
.release_version
, archive
)
41 # Check that url exists and has the given size
42 def is_uploaded(url
, size
):
43 if url
.startswith('http://TESTING/releases'):
46 print "Testing URL %s..." % url
48 actual_size
= int(support
.get_size(url
))
50 print "Can't get size of '%s': %s" % (url
, ex
)
53 if actual_size
== size
:
55 print "WARNING: %s exists, but size is %d, not %d!" % (url
, actual_size
, size
)
58 # status.verified_uploads is an array of status flags:
60 'N': 'Upload required',
61 'A': 'Upload has been attempted, but we need to check whether it worked',
62 'V': 'Upload has been checked (exists and has correct size)',
65 if status
.verified_uploads
is None:
66 # First time around; no point checking for existing uploads
67 status
.verified_uploads
= 'N' * len(uploads
)
71 print "\nUpload status:"
72 for i
, stat
in enumerate(status
.verified_uploads
):
73 print "- %s : %s" % (uploads
[i
], description
[stat
])
77 if status
.verified_uploads
== 'V' * len(uploads
):
80 # Find all New archives
82 for i
, stat
in enumerate(status
.verified_uploads
):
85 to_upload
.append(uploads
[i
])
86 print "Upload %s/%s as %s" % (status
.release_version
, uploads
[i
], url(uploads
[i
]))
88 cmd
= options
.archive_upload_command
.strip()
91 # Mark all New items as Attempted
92 status
.verified_uploads
= status
.verified_uploads
.replace('N', 'A')
97 support
.show_and_run(cmd
, to_upload
)
99 if len(to_upload
) == 1:
100 print "No upload command is set => please upload the archive manually now"
101 raw_input('Press Return once the archive is uploaded.')
103 print "No upload command is set => please upload the archives manually now"
104 raw_input('Press Return once the %d archives are uploaded.' % len(to_upload
))
106 # Verify all Attempted uploads
108 for i
, stat
in enumerate(status
.verified_uploads
):
109 assert stat
in 'AV', status
.verified_uploads
111 if not is_uploaded(url(uploads
[i
]), os
.path
.getsize(uploads
[i
])):
112 print "** Archive '%s' still not uploaded! Try again..." % uploads
[i
]
118 status
.verified_uploads
= new_stat
121 if 'N' in new_stat
and cmd
:
122 raw_input('Press Return to try again.')
124 def do_release(local_feed
, options
):
125 assert options
.master_feed_file
126 options
.master_feed_file
= os
.path
.abspath(options
.master_feed_file
)
128 if not options
.archive_dir_public_url
:
129 raise SafeException("Downloads directory not set. Edit the 'make-release' script and try again.")
131 if not local_feed
.feed_for
:
132 raise SafeException("Feed %s missing a <feed-for> element" % local_feed
.local_path
)
134 status
= support
.Status()
135 local_impl
= support
.get_singleton_impl(local_feed
)
137 local_impl_dir
= local_impl
.id
138 assert local_impl_dir
.startswith('/')
139 local_impl_dir
= os
.path
.realpath(local_impl_dir
)
140 assert os
.path
.isdir(local_impl_dir
)
141 assert local_feed
.local_path
.startswith(local_impl_dir
+ '/')
143 # From the impl directory to the feed
144 # NOT relative to the archive root (in general)
145 local_iface_rel_path
= local_feed
.local_path
[len(local_impl_dir
) + 1:]
146 assert not local_iface_rel_path
.startswith('/')
147 assert os
.path
.isfile(os
.path
.join(local_impl_dir
, local_iface_rel_path
))
150 for phase
in valid_phases
:
151 phase_actions
[phase
] = [] # List of <release:action> elements
153 add_toplevel_dir
= None
154 release_management
= local_feed
.get_metadata(XMLNS_RELEASE
, 'management')
155 if len(release_management
) == 1:
156 info("Found <release:management> element.")
157 release_management
= release_management
[0]
158 for x
in release_management
.childNodes
:
159 if x
.uri
== XMLNS_RELEASE
and x
.name
== 'action':
160 phase
= x
.getAttribute('phase')
161 if phase
not in valid_phases
:
162 raise SafeException("Invalid action phase '%s' in local feed %s. Valid actions are:\n%s" % (phase
, local_feed
.local_path
, '\n'.join(valid_phases
)))
163 phase_actions
[phase
].append(x
.content
)
164 elif x
.uri
== XMLNS_RELEASE
and x
.name
== 'add-toplevel-directory':
165 add_toplevel_dir
= local_feed
.get_name()
167 warn("Unknown <release:management> element: %s", x
)
168 elif len(release_management
) > 1:
169 raise SafeException("Multiple <release:management> sections in %s!" % local_feed
)
171 info("No <release:management> element found in local feed.")
173 scm
= get_scm(local_feed
, options
)
175 # Path relative to the archive / SCM root
176 local_iface_rel_root_path
= local_feed
.local_path
[len(scm
.root_dir
) + 1:]
178 def run_hooks(phase
, cwd
, env
):
179 info("Running hooks for phase '%s'" % phase
)
180 full_env
= os
.environ
.copy()
182 for x
in phase_actions
[phase
]:
183 print "[%s]: %s" % (phase
, x
)
184 support
.check_call(x
, shell
= True, cwd
= cwd
, env
= full_env
)
186 def set_to_release():
187 print "Snapshot version is " + local_impl
.get_version()
188 release_version
= options
.release_version
189 if release_version
is None:
190 suggested
= support
.suggest_release_version(local_impl
.get_version())
191 release_version
= raw_input("Version number for new release [%s]: " % suggested
)
192 if not release_version
:
193 release_version
= suggested
195 scm
.ensure_no_tag(release_version
)
197 status
.head_before_release
= scm
.get_head_revision()
200 working_copy
= local_impl
.id
201 run_hooks('commit-release', cwd
= working_copy
, env
= {'RELEASE_VERSION': release_version
})
203 print "Releasing version", release_version
204 support
.publish(local_feed
.local_path
, set_released
= 'today', set_version
= release_version
)
206 support
.backup_if_exists(release_version
)
207 os
.mkdir(release_version
)
208 os
.chdir(release_version
)
210 status
.old_snapshot_version
= local_impl
.get_version()
211 status
.release_version
= release_version
212 status
.head_at_release
= scm
.commit('Release %s' % release_version
, branch
= TMP_BRANCH_NAME
, parent
= 'HEAD')
215 def set_to_snapshot(snapshot_version
):
216 assert snapshot_version
.endswith('-post')
217 support
.publish(local_feed
.local_path
, set_released
= '', set_version
= snapshot_version
)
218 scm
.commit('Start development series %s' % snapshot_version
, branch
= TMP_BRANCH_NAME
, parent
= TMP_BRANCH_NAME
)
219 status
.new_snapshot_version
= scm
.get_head_revision()
222 def ensure_ready_to_release():
223 if not options
.master_feed_file
:
224 raise SafeException("Master feed file not set! Check your configuration")
226 scm
.ensure_committed()
227 scm
.ensure_versioned(os
.path
.abspath(local_feed
.local_path
))
228 info("No uncommitted changes. Good.")
229 # Not needed for GIT. For SCMs where tagging is expensive (e.g. svn) this might be useful.
230 #run_unit_tests(local_impl)
232 scm
.grep('\(^\\|[^=]\)\<\\(TODO\\|XXX\\|FIXME\\)\>')
234 def create_feed(target_feed
, local_iface_path
, archive_file
, archive_name
, main
):
235 shutil
.copyfile(local_iface_path
, target_feed
)
237 support
.publish(target_feed
,
239 archive_url
= support
.get_archive_url(options
, status
.release_version
, os
.path
.basename(archive_file
)),
240 archive_file
= archive_file
,
241 archive_extract
= archive_name
)
243 def get_previous_release(this_version
):
244 """Return the highest numbered verison in the master feed before this_version.
245 @return: version, or None if there wasn't one"""
246 parsed_release_version
= model
.parse_version(this_version
)
248 if os
.path
.exists(options
.master_feed_file
):
249 master
= support
.load_feed(options
.master_feed_file
)
250 versions
= [impl
.version
for impl
in master
.implementations
.values() if impl
.version
< parsed_release_version
]
252 return model
.format_version(max(versions
))
255 def export_changelog(previous_release
):
256 changelog
= file('changelog-%s' % status
.release_version
, 'w')
259 scm
.export_changelog(previous_release
, status
.head_before_release
, changelog
)
260 except SafeException
, ex
:
261 print "WARNING: Failed to generate changelog: " + str(ex
)
263 print "Wrote changelog from %s to here as %s" % (previous_release
or 'start', changelog
.name
)
267 def fail_candidate():
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
, 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.")
282 print "Already tagged in SCM. Not re-tagging."
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"
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'
298 if status
.updated_master_feed
:
299 print "Already added to master feed. Not changing."
302 if os
.path
.exists(options
.master_feed_file
):
303 # Check we haven't already released this version
304 master
= support
.load_feed(os
.path
.realpath(options
.master_feed_file
))
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 previous_release
= get_previous_release(status
.release_version
)
310 previous_testing_releases
= [impl
for impl
in master
.implementations
.values() if impl
.get_version() == previous_release
311 and impl
.upstream_stability
== model
.stability_levels
["testing"]]
312 if previous_testing_releases
:
313 print "The previous release, version %s, is still marked as 'testing'. Set to stable?" % previous_release
314 if support
.get_choice(['Yes', 'No']) == 'Yes':
315 publish_opts
['select_version'] = previous_release
316 publish_opts
['set_stability'] = "stable"
318 # Merge the source and binary feeds together first, so
319 # that we update the master feed atomically and only
320 # have to sign it once.
321 shutil
.copyfile(src_feed_name
, 'merged.xml')
322 for b
in compiler
.get_binary_feeds():
323 support
.publish('merged.xml', local
= b
)
325 support
.publish(options
.master_feed_file
, local
= 'merged.xml', xmlsign
= True, key
= options
.key
, **publish_opts
)
326 os
.unlink('merged.xml')
328 status
.updated_master_feed
= 'true'
332 uploads
= [os
.path
.basename(archive_file
)]
333 for b
in compiler
.get_binary_feeds():
334 binary_feed
= support
.load_feed(b
)
335 impl
, = binary_feed
.implementations
.values()
336 uploads
.append(os
.path
.basename(impl
.download_sources
[0].url
))
338 upload_archives(options
, status
, uploads
)
340 assert len(local_feed
.feed_for
) == 1
341 feed_base
= os
.path
.dirname(list(local_feed
.feed_for
)[0])
342 feed_files
= [options
.master_feed_file
]
343 print "Upload %s into %s" % (', '.join(feed_files
), feed_base
)
344 cmd
= options
.master_feed_upload_command
.strip()
346 support
.show_and_run(cmd
, feed_files
)
348 print "NOTE: No feed upload command set => you'll have to upload them yourself!"
350 print "Push changes to public SCM repository..."
351 public_repos
= options
.public_scm_repository
353 scm
.push_head_and_release(status
.release_version
)
355 print "NOTE: No public repository set => you'll have to push the tag and trunk yourself."
357 os
.unlink(support
.release_status_file
)
359 if status
.head_before_release
:
360 head
= scm
.get_head_revision()
361 if status
.release_version
:
362 print "RESUMING release of %s %s" % (local_feed
.get_name(), status
.release_version
)
363 if options
.release_version
and options
.release_version
!= status
.release_version
:
364 raise SafeException("Can't start release of version %s; we are currently releasing %s.\nDelete the release-status file to abort the previous release." % (options
.release_version
, status
.release_version
))
365 elif head
== status
.head_before_release
:
366 print "Restarting release of %s (HEAD revision has not changed)" % local_feed
.get_name()
368 raise SafeException("Something went wrong with the last run:\n" +
369 "HEAD revision for last run was " + status
.head_before_release
+ "\n" +
370 "HEAD revision now is " + head
+ "\n" +
371 "You should revert your working copy to the previous head and try again.\n" +
372 "If you're sure you want to release from the current head, delete '" + support
.release_status_file
+ "'")
374 print "Releasing", local_feed
.get_name()
376 ensure_ready_to_release()
378 if status
.release_version
:
379 if not os
.path
.isdir(status
.release_version
):
380 raise SafeException("Can't resume; directory %s missing. Try deleting '%s'." % (status
.release_version
, support
.release_status_file
))
381 os
.chdir(status
.release_version
)
382 need_set_snapshot
= False
384 print "Already tagged. Resuming the publishing process..."
385 elif status
.new_snapshot_version
:
386 head
= scm
.get_head_revision()
387 if head
!= status
.head_before_release
:
388 raise SafeException("There are more commits since we started!\n"
389 "HEAD was " + status
.head_before_release
+ "\n"
390 "HEAD now " + head
+ "\n"
391 "To include them, delete '" + support
.release_status_file
+ "' and try again.\n"
392 "To leave them out, put them on a new branch and reset HEAD to the release version.")
394 raise SafeException("Something went wrong previously when setting the new snapshot version.\n" +
395 "Suggest you reset to the original HEAD of\n%s and delete '%s'." % (status
.head_before_release
, support
.release_status_file
))
397 set_to_release() # Changes directory
398 assert status
.release_version
399 need_set_snapshot
= True
401 # May be needed by the upload command
402 os
.environ
['RELEASE_VERSION'] = status
.release_version
404 archive_name
= support
.make_archive_name(local_feed
.get_name(), status
.release_version
)
405 archive_file
= archive_name
+ '.tar.bz2'
407 export_prefix
= archive_name
408 if add_toplevel_dir
is not None:
409 export_prefix
+= '/' + add_toplevel_dir
411 if status
.created_archive
and os
.path
.isfile(archive_file
):
412 print "Archive already created"
414 support
.backup_if_exists(archive_file
)
415 scm
.export(export_prefix
, archive_file
, status
.head_at_release
)
417 has_submodules
= scm
.has_submodules()
419 if phase_actions
['generate-archive'] or has_submodules
:
421 support
.unpack_tarball(archive_file
)
423 scm
.export_submodules(archive_name
)
424 run_hooks('generate-archive', cwd
= archive_name
, env
= {'RELEASE_VERSION': status
.release_version
})
425 info("Regenerating archive (may have been modified by generate-archive hooks...")
426 support
.check_call(['tar', 'cjf', archive_file
, archive_name
])
427 except SafeException
:
428 scm
.reset_hard(scm
.get_current_branch())
432 status
.created_archive
= 'true'
435 if need_set_snapshot
:
436 set_to_snapshot(status
.release_version
+ '-post')
437 # Revert back to the original revision, so that any fixes the user makes
438 # will get applied before the tag
439 scm
.reset_hard(scm
.get_current_branch())
441 #backup_if_exists(archive_name)
442 support
.unpack_tarball(archive_file
)
444 extracted_feed_path
= os
.path
.abspath(os
.path
.join(export_prefix
, local_iface_rel_root_path
))
445 assert os
.path
.isfile(extracted_feed_path
), "Local feed not in archive! Is it under version control?"
446 extracted_feed
= support
.load_feed(extracted_feed_path
)
447 extracted_impl
= support
.get_singleton_impl(extracted_feed
)
449 if extracted_impl
.main
:
450 # Find main executable, relative to the archive root
451 abs_main
= os
.path
.join(os
.path
.dirname(extracted_feed_path
), extracted_impl
.id, extracted_impl
.main
)
452 main
= support
.relative_path(archive_name
+ '/', abs_main
)
453 if main
!= extracted_impl
.main
:
454 print "(adjusting main: '%s' for the feed inside the archive, '%s' externally)" % (extracted_impl
.main
, main
)
455 # XXX: this is going to fail if the feed uses the new <command> syntax
456 if not os
.path
.exists(abs_main
):
457 raise SafeException("Main executable '%s' not found after unpacking archive!" % abs_main
)
458 if main
== extracted_impl
.main
:
459 main
= None # Don't change the main attribute
464 if status
.src_tests_passed
:
465 print "Unit-tests already passed - not running again"
467 # Make directories read-only (checks tests don't write)
468 support
.make_readonly_recursive(archive_name
)
470 run_unit_tests(extracted_feed_path
)
471 status
.src_tests_passed
= True
473 except SafeException
:
474 print "(leaving extracted directory for examination)"
477 # Unpack it again in case the unit-tests changed anything
478 ro_rmtree(archive_name
)
479 support
.unpack_tarball(archive_file
)
481 # Generate feed for source
482 src_feed_name
= '%s.xml' % archive_name
483 create_feed(src_feed_name
, extracted_feed_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
), release_version
= status
.release_version
)
488 compiler
.build_binaries()
490 previous_release
= get_previous_release(status
.release_version
)
491 export_changelog(previous_release
)
494 raw_input('Already tagged. Press Return to resume publishing process...')
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 (delete release-status file)"
504 print "D) Diff against release archive for %s" % previous_release
505 maybe_diff
= ['Diff']
508 print "(you can also hit CTRL-C and resume this script when done)"
511 choice
= support
.get_choice(['Publish', 'Fail'] + maybe_diff
)
513 previous_archive_name
= support
.make_archive_name(local_feed
.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
)
525 support
.show_diff(previous_archive_name
, archive_name
)
527 shutil
.rmtree(previous_archive_name
)
530 print "Sorry, archive file %s not found! Can't show diff." % previous_archive_file
534 info("Deleting extracted archive %s", archive_name
)
535 shutil
.rmtree(archive_name
)
537 if choice
== 'Publish':
538 accept_and_publish(archive_file
, src_feed_name
)
540 assert choice
== 'Fail'