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)
21 print "SKIPPING unit tests for %s (no 'self-test' attribute set)" % impl
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
)
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
+= '/'
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'):
50 print "Testing URL %s..." % url
52 actual_size
= int(support
.get_size(url
))
54 print "Can't get size of '%s': %s" % (url
, ex
)
57 if actual_size
== size
:
59 print "WARNING: %s exists, but size is %d, not %d!" % (url
, actual_size
, size
)
62 # status.verified_uploads is an array of status flags:
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
)
75 print "\nUpload status:"
76 for i
, stat
in enumerate(status
.verified_uploads
):
77 print "- %s : %s" % (uploads
[i
], description
[stat
])
81 if status
.verified_uploads
== 'V' * len(uploads
):
84 # Find all New archives
86 for i
, stat
in enumerate(status
.verified_uploads
):
89 to_upload
.append(uploads
[i
])
90 print "Upload %s/%s as %s" % (status
.release_version
, uploads
[i
], url(uploads
[i
]))
93 # Mark all New items as Attempted
94 status
.verified_uploads
= status
.verified_uploads
.replace('N', 'A')
98 cmd
= options
.archive_upload_command
.strip()
100 support
.show_and_run(cmd
, to_upload
)
102 if len(to_upload
) == 1:
103 print "No upload command is set => please upload the archive manually now"
104 raw_input('Press Return once the archive is uploaded.')
106 print "No upload command is set => please upload the archives manually now"
107 raw_input('Press Return once the %d archives are uploaded.' % len(to_upload
))
109 # Verify all Attempted uploads
111 for i
, stat
in enumerate(status
.verified_uploads
):
112 assert stat
in 'AV', status
.verified_uploads
114 if not is_uploaded(url(uploads
[i
]), os
.path
.getsize(uploads
[i
])):
115 print "** Archive '%s' still not uploaded! Try again..." % uploads
[i
]
121 status
.verified_uploads
= new_stat
124 def do_release(local_iface
, options
):
125 assert options
.master_feed_file
126 options
.master_feed_file
= os
.path
.abspath(options
.master_feed_file
)
128 status
= support
.Status()
129 local_impl
= support
.get_singleton_impl(local_iface
)
131 local_impl_dir
= local_impl
.id
132 assert local_impl_dir
.startswith('/')
133 local_impl_dir
= os
.path
.realpath(local_impl_dir
)
134 assert os
.path
.isdir(local_impl_dir
)
135 assert local_iface
.uri
.startswith(local_impl_dir
+ '/')
137 # From the impl directory to the feed
138 # NOT relative to the archive root (in general)
139 local_iface_rel_path
= local_iface
.uri
[len(local_impl_dir
) + 1:]
140 assert not local_iface_rel_path
.startswith('/')
141 assert os
.path
.isfile(os
.path
.join(local_impl_dir
, local_iface_rel_path
))
144 for phase
in valid_phases
:
145 phase_actions
[phase
] = [] # List of <release:action> elements
147 add_toplevel_dir
= None
148 release_management
= local_iface
.get_metadata(XMLNS_RELEASE
, 'management')
149 if len(release_management
) == 1:
150 info("Found <release:management> element.")
151 release_management
= release_management
[0]
152 for x
in release_management
.childNodes
:
153 if x
.uri
== XMLNS_RELEASE
and x
.name
== 'action':
154 phase
= x
.getAttribute('phase')
155 if phase
not in valid_phases
:
156 raise SafeException("Invalid action phase '%s' in local feed %s. Valid actions are:\n%s" % (phase
, local_iface
.uri
, '\n'.join(valid_phases
)))
157 phase_actions
[phase
].append(x
.content
)
158 elif x
.uri
== XMLNS_RELEASE
and x
.name
== 'add-toplevel-directory':
159 add_toplevel_dir
= local_iface
.get_name()
161 warn("Unknown <release:management> element: %s", x
)
162 elif len(release_management
) > 1:
163 raise SafeException("Multiple <release:management> sections in %s!" % local_iface
)
165 info("No <release:management> element found in local feed.")
167 scm
= get_scm(local_iface
, options
)
169 # Path relative to the archive / SCM root
170 local_iface_rel_root_path
= local_iface
.uri
[len(scm
.root_dir
) + 1:]
172 def run_hooks(phase
, cwd
, env
):
173 info("Running hooks for phase '%s'" % phase
)
174 full_env
= os
.environ
.copy()
176 for x
in phase_actions
[phase
]:
177 print "[%s]: %s" % (phase
, x
)
178 support
.check_call(x
, shell
= True, cwd
= cwd
, env
= full_env
)
180 def set_to_release():
181 print "Snapshot version is " + local_impl
.get_version()
182 suggested
= support
.suggest_release_version(local_impl
.get_version())
183 release_version
= raw_input("Version number for new release [%s]: " % suggested
)
184 if not release_version
:
185 release_version
= suggested
187 scm
.ensure_no_tag(release_version
)
189 status
.head_before_release
= scm
.get_head_revision()
192 working_copy
= local_impl
.id
193 run_hooks('commit-release', cwd
= working_copy
, env
= {'RELEASE_VERSION': release_version
})
195 print "Releasing version", release_version
196 support
.publish(local_iface
.uri
, set_released
= 'today', set_version
= release_version
)
198 support
.backup_if_exists(release_version
)
199 os
.mkdir(release_version
)
200 os
.chdir(release_version
)
202 status
.old_snapshot_version
= local_impl
.get_version()
203 status
.release_version
= release_version
204 status
.head_at_release
= scm
.commit('Release %s' % release_version
, branch
= TMP_BRANCH_NAME
, parent
= 'HEAD')
207 def set_to_snapshot(snapshot_version
):
208 assert snapshot_version
.endswith('-post')
209 support
.publish(local_iface
.uri
, set_released
= '', set_version
= snapshot_version
)
210 scm
.commit('Start development series %s' % snapshot_version
, branch
= TMP_BRANCH_NAME
, parent
= TMP_BRANCH_NAME
)
211 status
.new_snapshot_version
= scm
.get_head_revision()
214 def ensure_ready_to_release():
215 if not options
.master_feed_file
:
216 raise SafeException("Master feed file not set! Check your configuration")
218 scm
.ensure_committed()
219 scm
.ensure_versioned(os
.path
.abspath(local_iface
.uri
))
220 info("No uncommitted changes. Good.")
221 # Not needed for GIT. For SCMs where tagging is expensive (e.g. svn) this might be useful.
222 #run_unit_tests(local_impl)
224 scm
.grep('\(^\\|[^=]\)\<\\(TODO\\|XXX\\|FIXME\\)\>')
226 def create_feed(target_feed
, local_iface_path
, archive_file
, archive_name
, main
):
227 shutil
.copyfile(local_iface_path
, target_feed
)
229 support
.publish(target_feed
,
231 archive_url
= options
.archive_dir_public_url
+ '/' + os
.path
.basename(archive_file
),
232 archive_file
= archive_file
,
233 archive_extract
= archive_name
)
235 def get_previous_release(this_version
):
236 """Return the highest numbered verison in the master feed before this_version.
237 @return: version, or None if there wasn't one"""
238 parsed_release_version
= model
.parse_version(this_version
)
240 if os
.path
.exists(options
.master_feed_file
):
241 master
= model
.Interface(os
.path
.realpath(options
.master_feed_file
))
242 reader
.update(master
, master
.uri
, local
= True)
243 versions
= [impl
.version
for impl
in master
.implementations
.values() if impl
.version
< parsed_release_version
]
245 return model
.format_version(max(versions
))
248 def export_changelog(previous_release
):
249 changelog
= file('changelog-%s' % status
.release_version
, 'w')
252 scm
.export_changelog(previous_release
, status
.head_before_release
, changelog
)
253 except SafeException
, ex
:
254 print "WARNING: Failed to generate changelog: " + str(ex
)
256 print "Wrote changelog from %s to here as %s" % (previous_release
or 'start', changelog
.name
)
260 def fail_candidate(archive_file
):
262 assert cwd
.endswith(status
.release_version
)
263 support
.backup_if_exists(cwd
)
264 scm
.delete_branch(TMP_BRANCH_NAME
)
265 os
.unlink(support
.release_status_file
)
266 print "Restored to state before starting release. Make your fixes and try again..."
268 def accept_and_publish(archive_file
, archive_name
, src_feed_name
):
269 assert options
.master_feed_file
271 if not options
.archive_dir_public_url
:
272 raise SafeException("Archive directory public URL is not set! Edit configuration and try again.")
275 print "Already tagged in SCM. Not re-tagging."
277 scm
.ensure_committed()
278 head
= scm
.get_head_revision()
279 if head
!= status
.head_before_release
:
280 raise SafeException("Changes committed since we started!\n" +
281 "HEAD was " + status
.head_before_release
+ "\n"
284 scm
.tag(status
.release_version
, status
.head_at_release
)
285 scm
.reset_hard(TMP_BRANCH_NAME
)
286 scm
.delete_branch(TMP_BRANCH_NAME
)
288 status
.tagged
= 'true'
291 if status
.updated_master_feed
:
292 print "Already added to master feed. Not changing."
294 if os
.path
.exists(options
.master_feed_file
):
295 # Check we haven't already released this version
296 master
= model
.Interface(os
.path
.realpath(options
.master_feed_file
))
297 reader
.update(master
, master
.uri
, local
= True)
298 existing_releases
= [impl
for impl
in master
.implementations
.values() if impl
.get_version() == status
.release_version
]
299 if len(existing_releases
):
300 raise SafeException("Master feed %s already contains an implementation with version number %s!" % (options
.master_feed_file
, status
.release_version
))
302 # Merge the source and binary feeds together first, so
303 # that we update the master feed atomically and only
304 # have to sign it once.
305 shutil
.copyfile(src_feed_name
, 'merged.xml')
306 for b
in compiler
.get_binary_feeds():
307 support
.publish('merged.xml', local
= b
)
309 support
.publish(options
.master_feed_file
, local
= 'merged.xml', xmlsign
= True, key
= options
.key
)
310 os
.unlink('merged.xml')
312 status
.updated_master_feed
= 'true'
316 uploads
= [os
.path
.basename(archive_file
)]
317 for b
in compiler
.get_binary_feeds():
319 binary_feed
= model
.ZeroInstallFeed(qdom
.parse(stream
), local_path
= b
)
321 impl
, = binary_feed
.implementations
.values()
322 uploads
.append(os
.path
.basename(impl
.download_sources
[0].url
))
324 upload_archives(options
, status
, uploads
)
326 assert len(local_iface
.feed_for
) == 1
327 feed_base
= os
.path
.dirname(local_iface
.feed_for
.keys()[0])
328 feed_files
= [options
.master_feed_file
]
329 print "Upload %s into %s" % (', '.join(feed_files
), feed_base
)
330 cmd
= options
.master_feed_upload_command
.strip()
332 support
.show_and_run(cmd
, feed_files
)
334 print "NOTE: No feed upload command set => you'll have to upload them yourself!"
336 print "Push changes to public SCM repository..."
337 public_repos
= options
.public_scm_repository
339 scm
.push_head_and_release(status
.release_version
)
341 print "NOTE: No public repository set => you'll have to push the tag and trunk yourself."
343 os
.unlink(support
.release_status_file
)
345 if status
.head_before_release
:
346 head
= scm
.get_head_revision()
347 if status
.release_version
:
348 print "RESUMING release of %s %s" % (local_iface
.get_name(), status
.release_version
)
349 elif head
== status
.head_before_release
:
350 print "Restarting release of %s (HEAD revision has not changed)" % local_iface
.get_name()
352 raise SafeException("Something went wrong with the last run:\n" +
353 "HEAD revision for last run was " + status
.head_before_release
+ "\n" +
354 "HEAD revision now is " + head
+ "\n" +
355 "You should revert your working copy to the previous head and try again.\n" +
356 "If you're sure you want to release from the current head, delete '" + support
.release_status_file
+ "'")
358 print "Releasing", local_iface
.get_name()
360 ensure_ready_to_release()
362 if status
.release_version
:
363 if not os
.path
.isdir(status
.release_version
):
364 raise SafeException("Can't resume; directory %s missing. Try deleting '%s'." % (status
.release_version
, support
.release_status_file
))
365 os
.chdir(status
.release_version
)
366 need_set_snapshot
= False
368 print "Already tagged. Resuming the publishing process..."
369 elif status
.new_snapshot_version
:
370 head
= scm
.get_head_revision()
371 if head
!= status
.head_before_release
:
372 raise SafeException("There are more commits since we started!\n"
373 "HEAD was " + status
.head_before_release
+ "\n"
374 "HEAD now " + head
+ "\n"
375 "To include them, delete '" + support
.release_status_file
+ "' and try again.\n"
376 "To leave them out, put them on a new branch and reset HEAD to the release version.")
378 raise SafeException("Something went wrong previously when setting the new snapshot version.\n" +
379 "Suggest you reset to the original HEAD of\n%s and delete '%s'." % (status
.head_before_release
, support
.release_status_file
))
381 set_to_release() # Changes directory
382 assert status
.release_version
383 need_set_snapshot
= True
385 archive_name
= support
.make_archive_name(local_iface
.get_name(), status
.release_version
)
386 archive_file
= archive_name
+ '.tar.bz2'
388 export_prefix
= archive_name
389 if add_toplevel_dir
is not None:
390 export_prefix
+= '/' + add_toplevel_dir
392 if status
.created_archive
and os
.path
.isfile(archive_file
):
393 print "Archive already created"
395 support
.backup_if_exists(archive_file
)
396 scm
.export(export_prefix
, archive_file
, status
.head_at_release
)
398 has_submodules
= scm
.has_submodules()
400 if phase_actions
['generate-archive'] or has_submodules
:
402 support
.unpack_tarball(archive_file
)
404 scm
.export_submodules(archive_name
)
405 run_hooks('generate-archive', cwd
= archive_name
, env
= {'RELEASE_VERSION': status
.release_version
})
406 info("Regenerating archive (may have been modified by generate-archive hooks...")
407 support
.check_call(['tar', 'cjf', archive_file
, archive_name
])
408 except SafeException
:
409 scm
.reset_hard(scm
.get_current_branch())
410 fail_candidate(archive_file
)
413 status
.created_archive
= 'true'
416 if need_set_snapshot
:
417 set_to_snapshot(status
.release_version
+ '-post')
418 # Revert back to the original revision, so that any fixes the user makes
419 # will get applied before the tag
420 scm
.reset_hard(scm
.get_current_branch())
422 #backup_if_exists(archive_name)
423 support
.unpack_tarball(archive_file
)
425 extracted_iface_path
= os
.path
.abspath(os
.path
.join(export_prefix
, local_iface_rel_root_path
))
426 assert os
.path
.isfile(extracted_iface_path
), "Local feed not in archive! Is it under version control?"
427 extracted_iface
= model
.Interface(extracted_iface_path
)
428 reader
.update(extracted_iface
, extracted_iface_path
, local
= True)
429 extracted_impl
= support
.get_singleton_impl(extracted_iface
)
431 if extracted_impl
.main
:
432 # Find main executable, relative to the archive root
433 abs_main
= os
.path
.join(os
.path
.dirname(extracted_iface_path
), extracted_impl
.main
)
434 main
= support
.relative_path(archive_name
+ '/', abs_main
)
435 if main
!= extracted_impl
.main
:
436 print "(adjusting main: '%s' for the feed inside the archive, '%s' externally)" % (extracted_impl
.main
, main
)
437 if not os
.path
.exists(abs_main
):
438 raise SafeException("Main executable '%s' not found after unpacking archive!" % abs_main
)
443 run_unit_tests(extracted_iface_path
, extracted_impl
)
444 except SafeException
:
445 print "(leaving extracted directory for examination)"
446 fail_candidate(archive_file
)
448 # Unpack it again in case the unit-tests changed anything
449 shutil
.rmtree(archive_name
)
450 support
.unpack_tarball(archive_file
)
452 # Generate feed for source
453 stream
= open(extracted_iface_path
)
454 src_feed_name
= '%s.xml' % archive_name
455 create_feed(src_feed_name
, extracted_iface_path
, archive_file
, archive_name
, main
)
456 print "Wrote source feed as %s" % src_feed_name
458 # If it's a source package, compile the binaries now...
459 compiler
= compile.Compiler(options
, os
.path
.abspath(src_feed_name
))
460 compiler
.build_binaries()
462 previous_release
= get_previous_release(status
.release_version
)
463 export_changelog(previous_release
)
465 print "\nCandidate release archive:", archive_file
466 print "(extracted to %s for inspection)" % os
.path
.abspath(archive_name
)
468 print "\nPlease check candidate and select an action:"
469 print "P) Publish candidate (accept)"
470 print "F) Fail candidate (untag)"
472 print "D) Diff against release archive for %s" % previous_release
473 maybe_diff
= ['Diff']
476 print "(you can also hit CTRL-C and resume this script when done)"
479 choice
= support
.get_choice(['Publish', 'Fail'] + maybe_diff
)
481 previous_archive_name
= support
.make_archive_name(local_iface
.get_name(), previous_release
)
482 previous_archive_file
= '../%s/%s.tar.bz2' % (previous_release
, previous_archive_name
)
484 # For archives created by older versions of 0release
485 if not os
.path
.isfile(previous_archive_file
):
486 old_previous_archive_file
= '../%s.tar.bz2' % previous_archive_name
487 if os
.path
.isfile(old_previous_archive_file
):
488 previous_archive_file
= old_previous_archive_file
490 if os
.path
.isfile(previous_archive_file
):
491 support
.unpack_tarball(previous_archive_file
)
493 support
.show_diff(previous_archive_name
, archive_name
)
495 shutil
.rmtree(previous_archive_name
)
498 print "Sorry, archive file %s not found! Can't show diff." % previous_archive_file
502 info("Deleting extracted archive %s", archive_name
)
503 shutil
.rmtree(archive_name
)
505 if choice
== 'Publish':
506 accept_and_publish(archive_file
, archive_name
, src_feed_name
)
508 assert choice
== 'Fail'
509 fail_candidate(archive_file
)