If the window is destroyed, write any further messages to stdout instead
[0compile.git] / build.py
blob590957d6137d6b7f4610f5cea66b16daf52ec0c7
1 # Copyright (C) 2006, Thomas Leonard
2 # See http://0install.net/0compile.html
4 import sys, os, __main__, time, shutil, glob, codecs, subprocess
5 from os.path import join
6 from logging import info
7 from xml.dom import minidom, XMLNS_NAMESPACE
8 from optparse import OptionParser
10 from support import *
12 if hasattr(os.path, 'relpath'):
13 relpath = os.path.relpath
14 else:
15 # Copied from Python 2.6 (GPL compatible license)
16 # Copyright Python Software Foundation
18 # Return the longest prefix of all list elements.
19 def commonprefix(m):
20 "Given a list of pathnames, returns the longest common leading component"
21 if not m: return ''
22 s1 = min(m)
23 s2 = max(m)
24 for i, c in enumerate(s1):
25 if c != s2[i]:
26 return s1[:i]
27 return s1
29 def relpath(path, start):
30 """Return a relative version of a path"""
32 if not path:
33 raise ValueError("no path specified")
35 start_list = os.path.abspath(start).split('/')
36 path_list = os.path.abspath(path).split('/')
38 # Work out how much of the filepath is shared by start and path.
39 i = len(commonprefix([start_list, path_list]))
41 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
42 if not rel_list:
43 return '.'
44 return join(*rel_list)
46 # If we have to modify any pkg-config files, we put the new versions in $TMPDIR/PKG_CONFIG_OVERRIDES
47 PKG_CONFIG_OVERRIDES = 'pkg-config-overrides'
49 def env(name, value):
50 os.environ[name] = value
51 print "%s=%s" % (name, value)
53 def do_env_binding(binding, path):
54 env(binding.name, binding.get_value(path, os.environ.get(binding.name, None)))
56 def correct_for_64bit(base, rel_path):
57 """If rel_path starts lib or usr/lib and doesn't exist, try with lib64 instead."""
58 if os.path.exists(os.path.join(base, rel_path)):
59 return rel_path
61 if rel_path.startswith('lib/') or rel_path.startswith('usr/lib/'):
62 new_rel_path = rel_path.replace('lib/', 'lib64/', 1)
63 if os.path.exists(os.path.join(base, new_rel_path)):
64 return new_rel_path
66 return rel_path
68 def write_pc(name, lines):
69 overrides_dir = os.path.join(os.environ['TMPDIR'], PKG_CONFIG_OVERRIDES)
70 if not os.path.isdir(overrides_dir):
71 os.mkdir(overrides_dir)
72 stream = open(os.path.join(overrides_dir, name), 'w')
73 stream.write(''.join(lines))
74 stream.close()
76 def do_pkg_config_binding(binding, impl):
77 feed_name = impl.feed.split('/')[-1]
78 path = lookup(impl.id)
79 new_insert = correct_for_64bit(path, binding.insert)
80 if new_insert != binding.insert:
81 print "PKG_CONFIG_PATH dir <%s>/%s not found; using %s instead" % (feed_name, binding.insert, new_insert)
82 binding = model.EnvironmentBinding(binding.name,
83 new_insert,
84 binding.default,
85 binding.mode)
87 orig_path = os.path.join(path, binding.insert)
88 if os.path.isdir(orig_path):
89 for pc in os.listdir(orig_path):
90 stream = open(os.path.join(orig_path, pc))
91 lines = stream.readlines()
92 stream.close()
93 for i, line in enumerate(lines):
94 if '=' not in line: continue
95 name, value = [x.strip() for x in line.split('=', 1)]
96 if name == 'prefix' and value.startswith('/'):
97 print "Absolute prefix=%s in %s; overriding..." % (value, feed_name)
98 lines[i] = 'prefix=%s/%s\n' % (path, value[1:])
99 write_pc(pc, lines)
100 break
101 do_env_binding(binding, path)
103 def fixup_generated_pkgconfig_file(pc_file):
104 stream = open(pc_file)
105 lines = stream.readlines()
106 stream.close()
107 for i, line in enumerate(lines):
108 if '=' not in line: continue
109 name, value = [x.strip() for x in line.split('=', 1)]
110 if name == 'prefix' and value.startswith('/'):
111 print "Absolute prefix=%s in %s; fixing..." % (value, pc_file)
112 rel_path = relpath(value, os.path.dirname(pc_file)) # Requires Python 2.6
113 lines[i] = 'prefix=${pcfiledir}/%s\n' % rel_path
114 write_pc(pc_file, lines)
115 break
117 # After doing a build, check that we didn't generate pkgconfig files with absolute paths
118 # Rewrite if so
119 def fixup_generated_pkgconfig_files():
120 for root, dirs, files in os.walk(os.environ['DISTDIR']):
121 if os.path.basename(root) == 'pkgconfig':
122 for f in files:
123 if f.endswith('.pc'):
124 info("Checking generated pkgconfig file '%s'", f)
125 fixup_generated_pkgconfig_file(os.path.join(root, f))
127 def do_build_internal(options, args):
128 """build-internal"""
129 # If a sandbox is being used, we're in it now.
130 import getpass, socket, time
132 buildenv = BuildEnv()
133 sels = buildenv.get_selections()
135 builddir = os.path.realpath('build')
136 ensure_dir(buildenv.metadir)
138 build_env_xml = join(buildenv.metadir, 'build-environment.xml')
140 buildenv_doc = buildenv.get_selections().toDOM()
142 # Create build-environment.xml file
143 root = buildenv_doc.documentElement
144 info = buildenv_doc.createElementNS(XMLNS_0COMPILE, 'build-info')
145 root.appendChild(info)
146 info.setAttributeNS(None, 'time', time.strftime('%Y-%m-%d %H:%M').strip())
147 info.setAttributeNS(None, 'host', socket.getfqdn())
148 info.setAttributeNS(None, 'user', getpass.getuser())
149 uname = os.uname()
150 info.setAttributeNS(None, 'arch', '%s-%s' % (uname[0], uname[4]))
151 stream = file(build_env_xml, 'w')
152 buildenv_doc.writexml(stream, addindent=" ", newl="\n")
153 stream.close()
155 # Create local binary interface file
156 src_iface = iface_cache.get_interface(buildenv.interface)
157 src_impl = buildenv.chosen_impl(buildenv.interface)
158 write_sample_interface(buildenv, src_iface, src_impl)
160 # Check 0compile is new enough
161 min_version = parse_version(src_impl.attrs.get(XMLNS_0COMPILE + ' min-version', None))
162 if min_version and min_version > parse_version(__main__.version):
163 raise SafeException("%s-%s requires 0compile >= %s, but we are only version %s" %
164 (src_iface.get_name(), src_impl.version, format_version(min_version), __main__.version))
166 # Create the patch
167 patch_file = join(buildenv.metadir, 'from-%s.patch' % src_impl.version)
168 if buildenv.user_srcdir:
169 # (ignore errors; will already be shown on stderr)
170 os.system("diff -urN '%s' src > %s" %
171 (buildenv.orig_srcdir.replace('\\', '\\\\').replace("'", "\\'"),
172 patch_file))
173 if os.path.getsize(patch_file) == 0:
174 os.unlink(patch_file)
175 elif os.path.exists(patch_file):
176 os.unlink(patch_file)
178 env('BUILDDIR', builddir)
179 env('DISTDIR', buildenv.distdir)
180 env('SRCDIR', buildenv.user_srcdir or buildenv.orig_srcdir)
181 os.chdir(builddir)
182 print "cd", builddir
184 for needed_iface in sels.selections:
185 impl = buildenv.chosen_impl(needed_iface)
186 assert impl
187 for dep in impl.dependencies:
188 dep_iface = sels.selections[dep.interface]
189 for b in dep.bindings:
190 if isinstance(b, EnvironmentBinding):
191 dep_impl = buildenv.chosen_impl(dep.interface)
192 if b.name == 'PKG_CONFIG_PATH':
193 do_pkg_config_binding(b, dep_impl)
194 else:
195 do_env_binding(b, lookup(dep_impl.id))
197 mappings = {}
198 for impl in sels.selections.values():
199 new_mappings = impl.attrs.get(XMLNS_0COMPILE + ' lib-mappings', '')
200 if new_mappings:
201 new_mappings = new_mappings.split(' ')
202 for mapping in new_mappings:
203 assert ':' in mapping, "lib-mappings missing ':' in '%s' from '%s'" % (mapping, impl.feed)
204 name, major_version = mapping.split(':', 1)
205 assert '/' not in mapping, "lib-mappings '%s' contains a / in the version number (from '%s')!" % (mapping, impl.feed)
206 mappings[name] = 'lib%s.so.%s' % (name, major_version)
207 impl_path = lookup(impl.id)
208 for libdirname in ['lib', 'usr/lib', 'lib64', 'usr/lib64']:
209 libdir = os.path.join(impl_path, libdirname)
210 if os.path.isdir(libdir):
211 find_broken_version_symlinks(libdir, mappings)
213 if mappings:
214 set_up_mappings(mappings)
216 overrides_dir = os.path.join(os.environ['TMPDIR'], PKG_CONFIG_OVERRIDES)
217 if os.path.isdir(overrides_dir):
218 add_overrides = model.EnvironmentBinding('PKG_CONFIG_PATH', PKG_CONFIG_OVERRIDES)
219 do_env_binding(add_overrides, os.environ['TMPDIR'])
221 # Some programs want to put temporary build files in the source directory.
222 # Make a copy of the source if needed.
223 dup_src_type = src_impl.attrs.get(XMLNS_0COMPILE + ' dup-src', None)
224 if dup_src_type == 'true':
225 dup_src(shutil.copy2)
226 env('SRCDIR', builddir)
227 elif dup_src_type:
228 raise Exception("Unknown dup-src value '%s'" % dup_src_type)
230 if options.shell:
231 spawn_and_check(find_in_path('sh'), [])
232 else:
233 command = src_impl.attrs[XMLNS_0COMPILE + ' command']
235 # Remove any existing log files
236 for log in ['build.log', 'build-success.log', 'build-failure.log']:
237 if os.path.exists(log):
238 os.unlink(log)
240 # Run the command, copying output to a new log
241 log = file('build.log', 'w')
242 try:
243 print >>log, "Build log for %s-%s" % (src_iface.get_name(),
244 src_impl.version)
245 print >>log, "\nBuilt using 0compile-%s" % __main__.version
246 print >>log, "\nBuild system: " + ', '.join(uname)
247 print >>log, "\n%s:\n" % ENV_FILE
248 shutil.copyfileobj(file("../" + ENV_FILE), log)
250 log.write('\n')
252 if os.path.exists(patch_file):
253 print >>log, "\nPatched with:\n"
254 shutil.copyfileobj(file(patch_file), log)
255 log.write('\n')
257 print "Executing: " + command
258 print >>log, "Executing: " + command
260 # Tee the output to the console and to the log
261 child = subprocess.Popen(command, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
262 while True:
263 data = os.read(child.stdout.fileno(), 100)
264 if not data: break
265 sys.stdout.write(data)
266 log.write(data)
267 status = child.wait()
268 failure = None
269 if status == 0:
270 print >>log, "Build successful"
271 fixup_generated_pkgconfig_files()
272 elif status > 0:
273 failure = "Build failed with exit code %d" % status
274 else:
275 failure = "Build failure: exited due to signal %d" % (-status)
276 if failure:
277 print >>log, failure
278 os.rename('build.log', 'build-failure.log')
279 raise SafeException("Command '%s': %s" % (command, failure))
280 else:
281 os.rename('build.log', 'build-success.log')
282 finally:
283 log.close()
285 def do_build(args):
286 """build [ --no-sandbox ] [ --shell | --force | --clean ]"""
287 buildenv = BuildEnv()
288 sels = buildenv.get_selections()
290 parser = OptionParser(usage="usage: %prog build [options]")
292 parser.add_option('', "--no-sandbox", help="disable use of sandboxing", action='store_true')
293 parser.add_option("-s", "--shell", help="run a shell instead of building", action='store_true')
294 parser.add_option("-c", "--clean", help="remove the build directories", action='store_true')
295 parser.add_option("-f", "--force", help="build even if dependencies have changed", action='store_true')
297 parser.disable_interspersed_args()
299 (options, args2) = parser.parse_args(args)
301 builddir = os.path.realpath('build')
303 changes = buildenv.get_build_changes()
304 if changes:
305 if not (options.force or options.clean):
306 raise SafeException("Build dependencies have changed:\n" +
307 '\n'.join(changes) + "\n\n" +
308 "To build anyway, use: 0compile build --force\n" +
309 "To do a clean build: 0compile build --clean")
310 if not options.no_sandbox:
311 print "Build dependencies have changed:\n" + '\n'.join(changes)
313 ensure_dir(builddir, options.clean)
314 ensure_dir(buildenv.distdir, options.clean)
316 if options.no_sandbox:
317 return do_build_internal(options, args2)
319 tmpdir = tempfile.mkdtemp(prefix = '0compile-')
320 try:
321 my_dir = os.path.dirname(__file__)
322 readable = ['.', my_dir]
323 writable = ['build', buildenv.distdir, tmpdir]
324 env('TMPDIR', tmpdir)
326 for selection in sels.selections.values():
327 readable.append(lookup(selection.id))
329 options = []
330 if __main__.options.verbose:
331 options.append('--verbose')
333 readable.append('/etc') # /etc/ld.*
335 spawn_maybe_sandboxed(readable, writable, tmpdir, sys.executable, [sys.argv[0]] + options + ['build', '--no-sandbox'] + args)
336 finally:
337 info("Deleting temporary directory '%s'" % tmpdir)
338 shutil.rmtree(tmpdir)
340 def write_sample_interface(buildenv, iface, src_impl):
341 path = buildenv.local_iface_file
342 target_arch = buildenv.target_arch
344 impl = minidom.getDOMImplementation()
346 XMLNS_IFACE = namespaces.XMLNS_IFACE
348 doc = impl.createDocument(XMLNS_IFACE, "interface", None)
350 root = doc.documentElement
351 root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', XMLNS_IFACE)
353 def addSimple(parent, name, text = None):
354 elem = doc.createElementNS(XMLNS_IFACE, name)
356 parent.appendChild(doc.createTextNode('\n' + ' ' * (1 + depth(parent))))
357 parent.appendChild(elem)
358 if text:
359 elem.appendChild(doc.createTextNode(text))
360 return elem
362 def close(element):
363 element.appendChild(doc.createTextNode('\n' + ' ' * depth(element)))
365 addSimple(root, 'name', iface.name)
366 addSimple(root, 'summary', iface.summary)
367 addSimple(root, 'description', iface.description)
368 feed_for = addSimple(root, 'feed-for')
370 uri = iface.uri
371 if uri.startswith('/'):
372 print "Note: source %s is a local feed" % iface.uri
373 for feed_uri in iface.feed_for or []:
374 uri = feed_uri
375 print "Will use <feed-for interface='%s'> instead..." % uri
376 break
377 else:
378 master_feed = minidom.parse(uri).documentElement
379 if master_feed.hasAttribute('uri'):
380 uri = master_feed.getAttribute('uri')
381 print "Will use <feed-for interface='%s'> instead..." % uri
383 feed_for.setAttributeNS(None, 'interface', uri)
385 group = addSimple(root, 'group')
386 main = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-main', None)
387 if main:
388 group.setAttributeNS(None, 'main', main)
390 lib_mappings = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-lib-mappings', None)
391 if lib_mappings:
392 root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:compile', XMLNS_0COMPILE)
393 group.setAttributeNS(XMLNS_0COMPILE, 'compile:lib-mappings', lib_mappings)
395 for d in src_impl.dependencies:
396 # 0launch < 0.32 messed up the namespace...
397 if parse_bool(d.metadata.get('include-binary', 'false')) or \
398 parse_bool(d.metadata.get(XMLNS_0COMPILE + ' include-binary', 'false')):
399 requires = addSimple(group, 'requires')
400 requires.setAttributeNS(None, 'interface', d.interface)
401 for b in d.bindings:
402 if isinstance(b, model.EnvironmentBinding):
403 env_elem = addSimple(requires, 'environment')
404 env_elem.setAttributeNS(None, 'name', b.name)
405 env_elem.setAttributeNS(None, 'insert', b.insert)
406 if b.default:
407 env_elem.setAttributeNS(None, 'default', b.default)
408 else:
409 raise Exception('Unknown binding type ' + b)
410 close(requires)
412 group.setAttributeNS(None, 'arch', target_arch)
413 impl_elem = addSimple(group, 'implementation')
414 impl_elem.setAttributeNS(None, 'version', src_impl.version)
416 version_modifier = buildenv.version_modifier
417 if version_modifier:
418 impl_elem.setAttributeNS(None, 'version-modifier', version_modifier)
420 impl_elem.setAttributeNS(None, 'id', '..')
421 impl_elem.setAttributeNS(None, 'released', time.strftime('%Y-%m-%d'))
422 close(group)
423 close(root)
425 stream = codecs.open(path, 'w', encoding = 'utf-8')
426 try:
427 doc.writexml(stream)
428 finally:
429 stream.close()
431 def find_broken_version_symlinks(libdir, mappings):
432 """libdir may be a legacy -devel package containing lib* symlinks whose
433 targets would be provided by the corresponding runtime package. If so,
434 create fixed symlinks under $TMPDIR with the real location."""
435 for x in os.listdir(libdir):
436 if x.startswith('lib') and x.endswith('.so'):
437 path = os.path.join(libdir, x)
438 if os.path.islink(path):
439 target = os.readlink(path)
440 if '/' not in target and not os.path.exists(os.path.join(libdir, target)):
441 print "Broken link %s -> %s; will relocate..." % (x, target)
442 mappings[x[3:-3]] = target
444 def set_up_mappings(mappings):
445 """Create a temporary directory with symlinks for each of the library mappings."""
446 libdirs = []
447 for d in os.environ.get('LD_LIBRARY_PATH', '').split(':'):
448 if d: libdirs.append(d)
449 libdirs += ['/lib', '/usr/lib']
451 def add_ldconf(config_file):
452 if not os.path.isfile(config_file):
453 return
454 for line in file(config_file):
455 d = line.strip()
456 if d.startswith('include '):
457 glob_pattern = d.split(' ', 1)[1]
458 for conf in glob.glob(glob_pattern):
459 add_ldconf(conf)
460 elif d and not d.startswith('#'):
461 libdirs.append(d)
462 add_ldconf('/etc/ld.so.conf')
464 def find_library(name, wanted):
465 # Takes a short-name and target name of a library and returns
466 # the full path of the library.
467 for d in libdirs:
468 path = os.path.join(d, wanted)
469 if os.path.exists(path):
470 return path
471 print "WARNING: library '%s' not found (searched '%s')!" % (wanted, libdirs)
472 return None
474 mappings_dir = os.path.join(os.environ['TMPDIR'], 'lib-mappings')
475 os.mkdir(mappings_dir)
477 old_path = os.environ.get('LIBRARY_PATH', '')
478 if old_path: old_path = ':' + old_path
479 os.environ['LIBRARY_PATH'] = mappings_dir + old_path
481 for name, wanted in mappings.items():
482 target = find_library(name, wanted)
483 if target:
484 print "Adding mapping lib%s.so -> %s" % (name, target)
485 os.symlink(target, os.path.join(mappings_dir, 'lib' + name + '.so'))
487 def dup_src(fn):
488 srcdir = os.environ['SRCDIR'] + '/'
489 for root, dirs, files in os.walk(srcdir):
490 assert root.startswith(srcdir)
491 reldir = root[len(srcdir):]
492 for f in files:
493 target = os.path.join(reldir, f)
494 #print "Copy %s -> %s" % (os.path.join(root, f), target)
495 if os.path.exists(target):
496 os.unlink(target)
497 fn(os.path.join(root, f), target)
498 for d in dirs:
499 target = os.path.join(reldir, d)
500 if not os.path.isdir(target):
501 os.mkdir(target)
503 __main__.commands.append(do_build)