1 # Copyright (C) 2009, Thomas Leonard
2 # See http://0install.net/0compile.html
4 import sys
, os
, __main__
, tempfile
, shutil
, subprocess
, signal
5 from xml
.dom
import minidom
6 from optparse
import OptionParser
8 from zeroinstall
import SafeException
9 from zeroinstall
.injector
import arch
, handler
, policy
, model
, iface_cache
, selections
, namespaces
, writer
, reader
10 from zeroinstall
.zerostore
import manifest
11 from zeroinstall
.support
import tasks
, basedir
13 from support
import BuildEnv
15 # This is a bit hacky...
17 # We invent a new CPU type which is compatible with the host but worse than
18 # every existing type, and we use * for the OS type so that we don't beat 'Any'
19 # binaries either. This means that we always prefer an existing binary of the
20 # desired version to compiling a new one, but we'll compile a new version from source
21 # rather than use an older binary.
22 arch
.machine_groups
['newbuild'] = arch
.machine_groups
.get(arch
._uname
[-1], 0)
23 arch
.machine_ranks
['newbuild'] = max(arch
.machine_ranks
.values()) + 1
24 host_arch
= '*-newbuild'
26 class AutocompileCache(iface_cache
.IfaceCache
):
28 iface_cache
.IfaceCache
.__init
__(self
)
31 def get_interface(self
, uri
):
32 iface
= iface_cache
.IfaceCache
.get_interface(self
, uri
)
33 if not iface
: return None
34 feed
= iface
._main
_feed
36 # Note: when a feed is updated, a new ZeroInstallFeed object is created,
37 # so record whether we've seen the feed, not the interface.
39 if feed
not in self
.done
:
42 # For each source impl, add a corresponding binary
43 # (the binary has no dependencies as we can't predict them here,
44 # but they're not the same as the source's dependencies)
46 srcs
= [x
for x
in feed
.implementations
.itervalues() if x
.arch
and x
.arch
.endswith('-src')]
48 new_id
= '0compile=' + x
.id
49 if not new_id
in feed
.implementations
:
50 new
= feed
._get
_impl
(new_id
)
51 new
.set_arch(host_arch
)
52 new
.version
= x
.version
56 policy
.iface_cache
= AutocompileCache()
58 class MyHandler(handler
.Handler
):
59 def downloads_changed(self
):
60 self
.compiler
.downloads_changed()
62 def confirm_import_feed(self
, pending
, valid_sigs
):
63 if hasattr(self
.compiler
, 'confirm_import_feed'):
64 return self
.compiler
.confirm_import_feed(pending
, valid_sigs
)
66 return handler
.Handler
.confirm_import_feed(self
, pending
, valid_sigs
)
69 def __init__(self
, iface_uri
, options
):
70 self
.iface_uri
= iface_uri
71 self
.options
= options
72 self
.handler
= MyHandler()
73 self
.handler
.compiler
= self
75 def downloads_changed(self
):
76 if self
.handler
.monitored_downloads
:
77 self
.note('Downloads in progress:')
78 for x
in self
.handler
.monitored_downloads
:
81 self
.note('No downloads remaining.')
83 def pretty_print_plan(self
, solver
, root
, indent
= '- '):
84 """Display a tree showing the selected implementations."""
85 iface
= solver
.iface_cache
.get_interface(root
)
86 impl
= solver
.selections
[iface
]
88 msg
= 'Failed to select any suitable version (source or binary)'
89 elif impl
.id.startswith('0compile='):
90 real_impl_id
= impl
.id.split('=', 1)[1]
91 real_impl
= impl
.feed
.implementations
[real_impl_id
]
92 msg
= 'Compile %s (%s)' % (real_impl
.get_version(), real_impl
.id)
93 elif impl
.arch
and impl
.arch
.endswith('-src'):
94 msg
= 'Compile %s (%s)' % (impl
.get_version(), impl
.id)
97 msg
= 'Use existing binary %s (%s)' % (impl
.get_version(), impl
.arch
)
99 msg
= 'Use existing architecture-independent package %s' % impl
.get_version()
100 self
.note("%s%s: %s" % (indent
, iface
.get_name(), msg
))
103 indent
= ' ' + indent
104 for x
in impl
.requires
:
105 self
.pretty_print_plan(solver
, x
.interface
, indent
)
107 def print_details(self
, solver
):
108 """Dump debugging details."""
109 self
.note("\nDetails of all components and versions considered:")
110 for iface
in solver
.details
:
111 self
.note('\n%s\n' % iface
.get_name())
112 for impl
, note
in solver
.details
[iface
]:
113 self
.note('%s (%s) : %s' % (impl
.get_version(), impl
.arch
or '*-*', note
or 'OK'))
114 self
.note("\nEnd details")
117 def compile_and_register(self
, policy
):
118 local_feed_dir
= basedir
.save_config_path('0install.net', '0compile', 'builds', model
._pretty
_escape
(policy
.root
))
119 s
= selections
.Selections(policy
)
121 buildenv
= BuildEnv(need_config
= False)
122 buildenv
.config
.set('compile', 'interface', policy
.root
)
123 buildenv
.config
.set('compile', 'selections', 'selections.xml')
125 version
= s
.selections
[policy
.root
].version
126 local_feed
= os
.path
.join(local_feed_dir
, '%s-%s-%s.xml' % (buildenv
.iface_name
, version
, arch
._uname
[-1]))
127 if os
.path
.exists(local_feed
):
128 raise SafeException("Build metadata file '%s' already exists!" % local_feed
)
130 tmpdir
= tempfile
.mkdtemp(prefix
= '0compile-')
134 # Write configuration for build...
138 sel_file
= open('selections.xml', 'w')
141 doc
.writexml(sel_file
)
148 build
= self
.spawn_build(buildenv
.iface_name
)
153 # Register the result...
155 alg
= manifest
.get_algorithm('sha1new')
156 digest
= alg
.new_digest()
158 for line
in alg
.generate_manifest(buildenv
.distdir
):
162 actual_digest
= alg
.getID(digest
)
164 local_feed_file
= file(local_feed
, 'w')
166 dom
= minidom
.parse(buildenv
.local_iface_file
)
167 impl
, = dom
.getElementsByTagNameNS(namespaces
.XMLNS_IFACE
, 'implementation')
168 impl
.setAttribute('id', actual_digest
)
169 dom
.writexml(local_feed_file
)
170 local_feed_file
.write('\n')
172 local_feed_file
.close()
174 self
.note("Implementation metadata written to %s" % local_feed
)
176 # No point adding it to the system store when only the user has the feed...
177 store
= policy
.solver
.iface_cache
.stores
.stores
[0]
178 self
.note("Storing build in user cache %s..." % store
.dir)
179 policy
.solver
.iface_cache
.stores
.add_dir_to_cache(actual_digest
, buildenv
.distdir
)
181 self
.note("Registering feed...")
182 iface
= policy
.solver
.iface_cache
.get_interface(policy
.root
)
183 feed
= iface
.get_feed(local_feed
)
185 self
.note("WARNING: feed %s already registered!" % local_feed
)
187 iface
.extra_feeds
.append(model
.Feed(local_feed
, impl
.getAttribute('arch'), user_override
= True))
188 writer
.save_interface(iface
)
190 # We might have cached an old version
191 new_feed
= policy
.solver
.iface_cache
.get_interface(local_feed
)
192 reader
.update_from_cache(new_feed
)
194 self
.note("\nBuild failed: leaving build directory %s for inspection...\n" % tmpdir
)
197 shutil
.rmtree(tmpdir
)
200 def recursive_build(self
, iface_uri
, version
= None):
201 p
= policy
.Policy(iface_uri
, handler
= self
.handler
, src
= True)
202 iface
= p
.solver
.iface_cache
.get_interface(iface_uri
)
203 p
.solver
.record_details
= True
205 p
.solver
.extra_restrictions
[iface
] = [model
.VersionRestriction(model
.parse_version(version
))]
208 #p.target_arch = arch.Architecture(os_ranks = {'FreeBSD': 0, None: 1}, machine_ranks = {'i386': 0, None: 1, 'newbuild': 2})
211 self
.heading(iface_uri
)
212 self
.note("\nSelecting versions for %s..." % iface
.get_name())
213 solved
= p
.solve_with_downloads()
218 if not p
.solver
.ready
:
219 self
.print_details(p
.solver
)
220 raise SafeException("Can't find all required implementations (source or binary):\n" +
221 '\n'.join(["- %s -> %s" % (iface
, p
.solver
.selections
[iface
])
222 for iface
in p
.solver
.selections
]))
223 self
.note("Selection done.")
225 self
.note("\nPlan:\n")
226 self
.pretty_print_plan(p
.solver
, p
.root
)
229 for dep_iface
, dep_impl
in p
.solver
.selections
.iteritems():
230 if dep_impl
.id.startswith('0compile='):
231 build
= self
.recursive_build(dep_iface
.uri
, dep_impl
.get_version())
234 break # Try again with that dependency built...
236 self
.note("No dependencies need compiling... compile %s itself..." % iface
.get_name())
237 build
= self
.compile_and_register(p
)
242 def spawn_build(self
, iface_name
):
243 subprocess
.check_call([sys
.executable
, sys
.argv
[0], 'build'])
246 self
.handler
.wait_for_blocker(self
.recursive_build(self
.iface_uri
))
248 def heading(self
, msg
):
249 self
.note((' %s ' % msg
).center(76, '='))
254 def note_error(self
, msg
):
255 self
.overall
.insert_at_cursor(msg
+ '\n')
257 class GTKAutoCompiler(AutoCompiler
):
258 def __init__(self
, iface_uri
, options
):
259 AutoCompiler
.__init
__(self
, iface_uri
, options
)
262 import pygtk
; pygtk
.require('2.0')
265 w
= gtk
.Dialog('Autocompile %s' % iface_uri
, None, 0,
266 (gtk
.STOCK_CANCEL
, gtk
.RESPONSE_CANCEL
,
267 gtk
.STOCK_OK
, gtk
.RESPONSE_OK
))
270 w
.set_default_size(int(gtk
.gdk
.screen_width() * 0.8),
271 int(gtk
.gdk
.screen_height() * 0.8))
273 vpaned
= gtk
.VPaned()
275 w
.set_response_sensitive(gtk
.RESPONSE_OK
, False)
280 tv
.set_property('left-margin', 8)
281 tv
.set_wrap_mode(gtk
.WRAP_WORD_CHAR
)
282 tv
.set_editable(False)
283 swin
= gtk
.ScrolledWindow()
285 swin
.set_policy(gtk
.POLICY_NEVER
, gtk
.POLICY_AUTOMATIC
)
286 buffer = tv
.get_buffer()
288 heading
= buffer.create_tag('heading')
289 heading
.set_property('scale', 1.5)
291 error
= buffer.create_tag('error')
292 error
.set_property('background', 'white')
293 error
.set_property('foreground', 'red')
299 def insert_at_end_and_scroll(self
, data
, *tags
):
300 vscroll
= self
.widget
.get_vadjustment()
302 # Widget has been destroyed
305 near_end
= vscroll
.upper
- vscroll
.page_size
* 1.5 < vscroll
.value
306 end
= self
.buffer.get_end_iter()
307 self
.buffer.insert_with_tags_by_name(end
, data
, *tags
)
309 cursor
= self
.buffer.get_insert()
310 self
.buffer.move_mark(cursor
, end
)
311 self
.tv
.scroll_to_mark(cursor
, 0, False, 0, 0)
313 self
.overall
= AutoScroller()
314 self
.details
= AutoScroller()
316 vpaned
.pack1(self
.overall
.widget
, True, False)
317 vpaned
.pack2(self
.details
.widget
, True, False)
319 self
.closed
= tasks
.Blocker('Window closed')
322 w
.connect('destroy', lambda wd
: self
.closed
.trigger())
324 def response(wd
, resp
):
325 if self
.child
is not None:
326 self
.note_error('Sending TERM signal to build process group %d...' % self
.child
.pid
)
327 os
.kill(-self
.child
.pid
, signal
.SIGTERM
)
329 self
.closed
.trigger()
330 w
.connect('response', response
)
332 def heading(self
, msg
):
333 self
.overall
.insert_at_end_and_scroll(msg
+ '\n', 'heading')
336 self
.overall
.insert_at_end_and_scroll(msg
+ '\n')
338 def note_error(self
, msg
):
339 self
.overall
.insert_at_end_and_scroll(msg
+ '\n', 'error')
344 self
.handler
.wait_for_blocker(self
.recursive_build(self
.iface_uri
))
345 except SafeException
, ex
:
346 self
.note_error(str(ex
))
348 self
.heading('All builds completed successfully!')
349 self
.dialog
.set_response_sensitive(gtk
.RESPONSE_CANCEL
, False)
350 self
.dialog
.set_response_sensitive(gtk
.RESPONSE_OK
, True)
352 self
.handler
.wait_for_blocker(self
.closed
)
355 def spawn_build(self
, iface_name
):
356 assert self
.child
is None
358 self
.details
.insert_at_end_and_scroll('Building %s\n' % iface_name
, 'heading')
360 # Group all the child processes so we can kill them easily
361 def become_group_leader():
363 self
.child
= subprocess
.Popen([sys
.executable
, '-u', sys
.argv
[0], 'build'],
364 stdout
= subprocess
.PIPE
, stderr
= subprocess
.STDOUT
,
365 preexec_fn
= become_group_leader
)
368 decoder
= codecs
.getincrementaldecoder('utf-8')(errors
= 'replace')
371 yield tasks
.InputBlocker(self
.child
.stdout
, 'output from child')
372 got
= os
.read(self
.child
.stdout
.fileno(), 100)
373 chars
= decoder
.decode(got
, final
= not got
)
374 self
.details
.insert_at_end_and_scroll(chars
)
378 code
= self
.child
.returncode
381 self
.details
.insert_at_end_and_scroll('Build process exited with error status %d\n' % code
, 'error')
382 raise SafeException('Build process exited with error status %d' % code
)
383 self
.details
.insert_at_end_and_scroll('Build completed successfully\n', 'heading')
386 def confirm_import_feed(self
, pending
, valid_sigs
):
387 from zeroinstall
.gtkui
import trust_box
388 box
= trust_box
.TrustBox(pending
, valid_sigs
, parent
= self
.dialog
)
392 def do_autocompile(args
):
393 """autocompile [--gui] URI"""
395 parser
= OptionParser(usage
="usage: %prog autocompile [options]")
397 parser
.add_option('', "--gui", help="graphical interface", action
='store_true')
398 (options
, args2
) = parser
.parse_args(args
)
400 raise __main__
.UsageError()
402 iface_uri
= model
.canonical_iface_uri(args2
[0])
404 compiler
= GTKAutoCompiler(iface_uri
, options
)
406 compiler
= AutoCompiler(iface_uri
, options
)
410 __main__
.commands
+= [do_autocompile
]