Updated argument name for new API
[0compile.git] / build.py
blob70f5415afa9f098c03d6abd082bc4c14c5b2be8d
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, warn
7 from xml.dom import minidom, XMLNS_NAMESPACE
8 from optparse import OptionParser
9 import tempfile
11 from zeroinstall import SafeException
12 from zeroinstall.injector import model, namespaces, run
13 from zeroinstall.injector.iface_cache import iface_cache
15 from support import BuildEnv, ensure_dir, XMLNS_0COMPILE, is_package_impl, parse_bool, depth
16 from support import spawn_and_check, find_in_path, ENV_FILE, lookup, spawn_maybe_sandboxed, Prefixes
18 if hasattr(os.path, 'relpath'):
19 relpath = os.path.relpath
20 else:
21 # Copied from Python 2.6 (GPL compatible license)
22 # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights Reserved
24 # Return the longest prefix of all list elements.
25 def commonprefix(m):
26 "Given a list of pathnames, returns the longest common leading component"
27 if not m: return ''
28 s1 = min(m)
29 s2 = max(m)
30 for i, c in enumerate(s1):
31 if c != s2[i]:
32 return s1[:i]
33 return s1
35 def relpath(path, start):
36 """Return a relative version of a path"""
38 if not path:
39 raise ValueError("no path specified")
41 start_list = os.path.abspath(start).split('/')
42 path_list = os.path.abspath(path).split('/')
44 # Work out how much of the filepath is shared by start and path.
45 i = len(commonprefix([start_list, path_list]))
47 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
48 if not rel_list:
49 return '.'
50 return join(*rel_list)
52 # If we have to modify any pkg-config files, we put the new versions in $TMPDIR/PKG_CONFIG_OVERRIDES
53 PKG_CONFIG_OVERRIDES = 'pkg-config-overrides'
55 def env(name, value):
56 os.environ[name] = value
57 print "%s=%s" % (name, value)
59 def do_env_binding(binding, path):
60 env(binding.name, binding.get_value(path, os.environ.get(binding.name, None)))
62 def correct_for_64bit(base, rel_path):
63 """If rel_path starts lib or usr/lib and doesn't exist, try with lib64 instead."""
64 if os.path.exists(os.path.join(base, rel_path)):
65 return rel_path
67 if rel_path.startswith('lib/') or rel_path.startswith('usr/lib/'):
68 new_rel_path = rel_path.replace('lib/', 'lib64/', 1)
69 if os.path.exists(os.path.join(base, new_rel_path)):
70 return new_rel_path
72 return rel_path
74 def write_pc(name, lines):
75 overrides_dir = os.path.join(os.environ['TMPDIR'], PKG_CONFIG_OVERRIDES)
76 if not os.path.isdir(overrides_dir):
77 os.mkdir(overrides_dir)
78 stream = open(os.path.join(overrides_dir, name), 'w')
79 stream.write(''.join(lines))
80 stream.close()
82 def do_pkg_config_binding(binding, impl):
83 feed_name = impl.feed.split('/')[-1]
84 path = lookup(impl)
85 new_insert = correct_for_64bit(path, binding.insert)
86 if new_insert != binding.insert:
87 print "PKG_CONFIG_PATH dir <%s>/%s not found; using %s instead" % (feed_name, binding.insert, new_insert)
88 binding = model.EnvironmentBinding(binding.name,
89 new_insert,
90 binding.default,
91 binding.mode)
93 orig_path = os.path.join(path, binding.insert)
94 if os.path.isdir(orig_path):
95 for pc in os.listdir(orig_path):
96 stream = open(os.path.join(orig_path, pc))
97 lines = stream.readlines()
98 stream.close()
99 for i, line in enumerate(lines):
100 if '=' not in line: continue
101 name, value = [x.strip() for x in line.split('=', 1)]
102 if name == 'prefix' and value.startswith('/'):
103 print "Absolute prefix=%s in %s; overriding..." % (value, feed_name)
104 lines[i] = 'prefix=%s/%s\n' % (path, value[1:])
105 write_pc(pc, lines)
106 break
107 do_env_binding(binding, path)
109 def fixup_generated_pkgconfig_file(pc_file):
110 stream = open(pc_file)
111 lines = stream.readlines()
112 stream.close()
113 for i, line in enumerate(lines):
114 if '=' not in line: continue
115 name, value = [x.strip() for x in line.split('=', 1)]
116 if name == 'prefix' and value.startswith('/'):
117 print "Absolute prefix=%s in %s; fixing..." % (value, pc_file)
118 rel_path = relpath(value, os.path.dirname(pc_file)) # Requires Python 2.6
119 lines[i] = 'prefix=${pcfiledir}/%s\n' % rel_path
120 write_pc(pc_file, lines)
121 break
123 # After doing a build, check that we didn't generate pkgconfig files with absolute paths
124 # Rewrite if so
125 def fixup_generated_pkgconfig_files():
126 for root, dirs, files in os.walk(os.environ['DISTDIR']):
127 if os.path.basename(root) == 'pkgconfig':
128 for f in files:
129 if f.endswith('.pc'):
130 info("Checking generated pkgconfig file '%s'", f)
131 fixup_generated_pkgconfig_file(os.path.join(root, f))
133 def remove_la_file(path):
134 # Read the contents...
135 stream = open(path)
136 data = stream.read()
137 stream.close()
139 # Check it really is a libtool archive...
140 if 'Please DO NOT delete this file' not in data:
141 warn("Ignoring %s; doesn't look like a libtool archive", path)
142 return
144 os.unlink(path)
145 print "Removed %s (.la files contain absolute paths)" % path
147 # libtool archives contain hard-coded paths. Lucky, modern systems don't need them, so remove
148 # them.
149 def remove_la_files():
150 for root, dirs, files in os.walk(os.environ['DISTDIR']):
151 if os.path.basename(root) == 'lib':
152 for f in files:
153 if f.endswith('.la'):
154 remove_la_file(os.path.join(root, f))
155 if f.endswith('.a'):
156 warn("Found static archive '%s'; maybe build with --disable-static?", f)
158 class CompileSetup(run.Setup):
159 def do_binding(self, impl, b, iface):
160 if isinstance(b, model.EnvironmentBinding):
161 if b.name == 'PKG_CONFIG_PATH':
162 do_pkg_config_binding(b, impl)
163 else:
164 do_env_binding(b, lookup(impl))
165 else:
166 run.Setup.do_binding(self, impl, b, iface)
168 def do_build_internal(options, args):
169 """build-internal"""
170 # If a sandbox is being used, we're in it now.
171 import getpass, socket
173 buildenv = BuildEnv()
174 sels = buildenv.get_selections()
176 builddir = os.path.realpath('build')
177 ensure_dir(buildenv.metadir)
179 build_env_xml = join(buildenv.metadir, 'build-environment.xml')
181 buildenv_doc = sels.toDOM()
183 # Create build-environment.xml file
184 root = buildenv_doc.documentElement
185 info = buildenv_doc.createElementNS(XMLNS_0COMPILE, 'build-info')
186 root.appendChild(info)
187 info.setAttributeNS(None, 'time', time.strftime('%Y-%m-%d %H:%M').strip())
188 info.setAttributeNS(None, 'host', socket.getfqdn())
189 info.setAttributeNS(None, 'user', getpass.getuser())
190 uname = os.uname()
191 info.setAttributeNS(None, 'arch', '%s-%s' % (uname[0], uname[4]))
192 stream = file(build_env_xml, 'w')
193 buildenv_doc.writexml(stream, addindent=" ", newl="\n")
194 stream.close()
196 # Create local binary interface file
197 src_iface = iface_cache.get_interface(buildenv.interface)
198 src_impl = buildenv.chosen_impl(buildenv.interface)
199 write_sample_interface(buildenv, src_iface, src_impl)
201 # Check 0compile is new enough
202 min_version = model.parse_version(src_impl.attrs.get(XMLNS_0COMPILE + ' min-version', None))
203 if min_version and min_version > model.parse_version(__main__.version):
204 raise SafeException("%s-%s requires 0compile >= %s, but we are only version %s" %
205 (src_iface.get_name(), src_impl.version, model.format_version(min_version), __main__.version))
207 # Create the patch
208 patch_file = join(buildenv.metadir, 'from-%s.patch' % src_impl.version)
209 if buildenv.user_srcdir:
210 # (ignore errors; will already be shown on stderr)
211 os.system("diff -urN '%s' src > %s" %
212 (buildenv.orig_srcdir.replace('\\', '\\\\').replace("'", "\\'"),
213 patch_file))
214 if os.path.getsize(patch_file) == 0:
215 os.unlink(patch_file)
216 elif os.path.exists(patch_file):
217 os.unlink(patch_file)
219 env('BUILDDIR', builddir)
220 env('DISTDIR', buildenv.distdir)
221 env('SRCDIR', buildenv.user_srcdir or buildenv.orig_srcdir)
222 env('BINARYFEED', buildenv.local_iface_file)
223 os.chdir(builddir)
224 print "cd", builddir
226 setup = CompileSetup(iface_cache.stores, sels)
227 setup.prepare_env()
229 # These mappings are needed when mixing Zero Install -dev packages with
230 # native package binaries.
231 mappings = {}
232 for impl in sels.selections.values():
233 # Add mappings that have been set explicitly...
234 new_mappings = impl.attrs.get(XMLNS_0COMPILE + ' lib-mappings', '')
235 if new_mappings:
236 new_mappings = new_mappings.split(' ')
237 for mapping in new_mappings:
238 assert ':' in mapping, "lib-mappings missing ':' in '%s' from '%s'" % (mapping, impl.feed)
239 name, major_version = mapping.split(':', 1)
240 assert '/' not in mapping, "lib-mappings '%s' contains a / in the version number (from '%s')!" % (mapping, impl.feed)
241 if sys.platform == 'darwin':
242 mappings[name] = 'lib%s.%s.dylib' % (name, major_version)
243 else:
244 mappings[name] = 'lib%s.so.%s' % (name, major_version)
245 # Auto-detect required mappings where possible...
246 # (if the -dev package is native, the symlinks will be OK)
247 if not is_package_impl(impl):
248 impl_path = lookup(impl)
249 for libdirname in ['lib', 'usr/lib', 'lib64', 'usr/lib64']:
250 libdir = os.path.join(impl_path, libdirname)
251 if os.path.isdir(libdir):
252 find_broken_version_symlinks(libdir, mappings)
254 if mappings:
255 set_up_mappings(mappings)
257 overrides_dir = os.path.join(os.environ['TMPDIR'], PKG_CONFIG_OVERRIDES)
258 if os.path.isdir(overrides_dir):
259 add_overrides = model.EnvironmentBinding('PKG_CONFIG_PATH', PKG_CONFIG_OVERRIDES)
260 do_env_binding(add_overrides, os.environ['TMPDIR'])
262 # Some programs want to put temporary build files in the source directory.
263 # Make a copy of the source if needed.
264 dup_src_type = src_impl.attrs.get(XMLNS_0COMPILE + ' dup-src', None)
265 if dup_src_type == 'true':
266 dup_src(shutil.copy2)
267 env('SRCDIR', builddir)
268 elif dup_src_type:
269 raise Exception("Unknown dup-src value '%s'" % dup_src_type)
271 if options.shell:
272 spawn_and_check(find_in_path('sh'), [])
273 else:
274 command = sels.commands[0].qdom.attrs.get('shell-command', None)
275 if command is None:
276 # New style <command>
277 prog_args = setup.build_command(sels.interface, sels.command) + args
278 else:
279 # Old style shell-command='...'
280 prog_args = ['/bin/sh', '-c', command + ' "$@"', '-'] + args
281 assert len(sels.commands) == 1
283 # Remove any existing log files
284 for log in ['build.log', 'build-success.log', 'build-failure.log']:
285 if os.path.exists(log):
286 os.unlink(log)
288 # Run the command, copying output to a new log
289 log = file('build.log', 'w')
290 try:
291 print >>log, "Build log for %s-%s" % (src_iface.get_name(),
292 src_impl.version)
293 print >>log, "\nBuilt using 0compile-%s" % __main__.version
294 print >>log, "\nBuild system: " + ', '.join(uname)
295 print >>log, "\n%s:\n" % ENV_FILE
296 shutil.copyfileobj(file("../" + ENV_FILE), log)
298 log.write('\n')
300 if os.path.exists(patch_file):
301 print >>log, "\nPatched with:\n"
302 shutil.copyfileobj(file(patch_file), log)
303 log.write('\n')
305 if command:
306 print "Executing: " + command, args
307 print >>log, "Executing: " + command, args
308 else:
309 print "Executing: " + str(prog_args)
310 print >>log, "Executing: " + str(prog_args)
312 # Tee the output to the console and to the log
313 child = subprocess.Popen(prog_args, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
314 while True:
315 data = os.read(child.stdout.fileno(), 100)
316 if not data: break
317 sys.stdout.write(data)
318 log.write(data)
319 status = child.wait()
320 failure = None
321 if status == 0:
322 print >>log, "Build successful"
323 fixup_generated_pkgconfig_files()
324 remove_la_files()
325 elif status > 0:
326 failure = "Build failed with exit code %d" % status
327 else:
328 failure = "Build failure: exited due to signal %d" % (-status)
329 if failure:
330 print >>log, failure
331 os.rename('build.log', 'build-failure.log')
332 raise SafeException("Command '%s': %s" % (prog_args, failure))
333 else:
334 os.rename('build.log', 'build-success.log')
335 finally:
336 log.close()
338 def do_build(args):
339 """build [ --no-sandbox ] [ --shell | --force | --clean ]"""
340 buildenv = BuildEnv()
341 sels = buildenv.get_selections()
343 parser = OptionParser(usage="usage: %prog build [options]")
345 parser.add_option('', "--no-sandbox", help="disable use of sandboxing", action='store_true')
346 parser.add_option("-s", "--shell", help="run a shell instead of building", action='store_true')
347 parser.add_option("-c", "--clean", help="remove the build directories", action='store_true')
348 parser.add_option("-f", "--force", help="build even if dependencies have changed", action='store_true')
350 parser.disable_interspersed_args()
352 (options, args2) = parser.parse_args(args)
354 builddir = os.path.realpath('build')
356 changes = buildenv.get_build_changes()
357 if changes:
358 if not (options.force or options.clean):
359 raise SafeException("Build dependencies have changed:\n" +
360 '\n'.join(changes) + "\n\n" +
361 "To build anyway, use: 0compile build --force\n" +
362 "To do a clean build: 0compile build --clean")
363 if not options.no_sandbox:
364 print "Build dependencies have changed:\n" + '\n'.join(changes)
366 ensure_dir(builddir, options.clean)
367 ensure_dir(buildenv.distdir, options.clean)
369 if options.no_sandbox:
370 return do_build_internal(options, args2)
372 tmpdir = tempfile.mkdtemp(prefix = '0compile-')
373 try:
374 my_dir = os.path.dirname(__file__)
375 readable = ['.', my_dir]
376 writable = ['build', buildenv.distdir, tmpdir]
377 env('TMPDIR', tmpdir)
379 for selection in sels.selections.values():
380 if not is_package_impl(selection):
381 readable.append(lookup(selection))
383 options = []
384 if __main__.options.verbose:
385 options.append('--verbose')
387 readable.append('/etc') # /etc/ld.*
389 spawn_maybe_sandboxed(readable, writable, tmpdir, sys.executable, ['-u', sys.argv[0]] + options + ['build', '--no-sandbox'] + args)
390 finally:
391 info("Deleting temporary directory '%s'" % tmpdir)
392 shutil.rmtree(tmpdir)
394 def write_sample_interface(buildenv, iface, src_impl):
395 path = buildenv.local_iface_file
397 impl = minidom.getDOMImplementation()
399 XMLNS_IFACE = namespaces.XMLNS_IFACE
401 doc = impl.createDocument(XMLNS_IFACE, "interface", None)
403 root = doc.documentElement
404 root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', XMLNS_IFACE)
405 prefixes = Prefixes(XMLNS_IFACE)
407 def addSimple(parent, name, text = None):
408 elem = doc.createElementNS(XMLNS_IFACE, name)
410 parent.appendChild(doc.createTextNode('\n' + ' ' * (1 + depth(parent))))
411 parent.appendChild(elem)
412 if text:
413 elem.appendChild(doc.createTextNode(text))
414 return elem
416 def close(element):
417 element.appendChild(doc.createTextNode('\n' + ' ' * depth(element)))
419 addSimple(root, 'name', iface.name)
420 addSimple(root, 'summary', iface.summary)
421 addSimple(root, 'description', iface.description)
422 feed_for = addSimple(root, 'feed-for')
424 uri = iface.uri
425 if uri.startswith('/'):
426 print "Note: source %s is a local feed" % iface.uri
427 for feed_uri in iface.feed_for or []:
428 uri = feed_uri
429 print "Will use <feed-for interface='%s'> instead..." % uri
430 break
431 else:
432 master_feed = minidom.parse(uri).documentElement
433 if master_feed.hasAttribute('uri'):
434 uri = master_feed.getAttribute('uri')
435 print "Will use <feed-for interface='%s'> instead..." % uri
437 feed_for.setAttributeNS(None, 'interface', uri)
439 group = addSimple(root, 'group')
440 main = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-main', None)
441 if main:
442 group.setAttributeNS(None, 'main', main)
444 lib_mappings = src_impl.attrs.get(XMLNS_0COMPILE + ' binary-lib-mappings', None)
445 if lib_mappings:
446 prefixes.setAttributeNS(group, XMLNS_0COMPILE, 'lib-mappings', lib_mappings)
448 for d in src_impl.dependencies:
449 # 0launch < 0.32 messed up the namespace...
450 if parse_bool(d.metadata.get('include-binary', 'false')) or \
451 parse_bool(d.metadata.get(XMLNS_0COMPILE + ' include-binary', 'false')):
452 requires = addSimple(group, 'requires')
453 requires.setAttributeNS(None, 'interface', d.interface)
454 for b in d.bindings:
455 if isinstance(b, model.EnvironmentBinding):
456 env_elem = addSimple(requires, 'environment')
457 env_elem.setAttributeNS(None, 'name', b.name)
458 env_elem.setAttributeNS(None, 'insert', b.insert)
459 if b.default:
460 env_elem.setAttributeNS(None, 'default', b.default)
461 else:
462 raise Exception('Unknown binding type ' + b)
463 close(requires)
465 set_arch = True
467 impl_elem = addSimple(group, 'implementation')
468 impl_template = buildenv.get_binary_template()
469 if impl_template:
470 # Copy attributes from template
471 for fullname, value in impl_template.attrs.iteritems():
472 if fullname == 'arch':
473 set_arch = False
474 if value == '*-*':
475 continue
476 if ' ' in fullname:
477 ns, localName = fullname.split(' ', 1)
478 else:
479 ns, localName = None, fullname
480 prefixes.setAttributeNS(impl_elem, ns, localName, value)
481 # Copy child nodes
482 for child in impl_template.childNodes:
483 impl_elem.appendChild(child.toDOM(doc, prefixes))
484 if impl_template.content:
485 impl_elem.appendChild(doc.createTextNode(impl_template.content))
487 if set_arch:
488 group.setAttributeNS(None, 'arch', buildenv.target_arch)
490 impl_elem.setAttributeNS(None, 'version', src_impl.version)
492 version_modifier = buildenv.version_modifier
493 if version_modifier:
494 impl_elem.setAttributeNS(None, 'version-modifier', version_modifier)
496 impl_elem.setAttributeNS(None, 'id', '..')
497 impl_elem.setAttributeNS(None, 'released', time.strftime('%Y-%m-%d'))
498 close(group)
499 close(root)
501 for ns, prefix in prefixes.prefixes.items():
502 root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:' + prefix, ns)
504 stream = codecs.open(path, 'w', encoding = 'utf-8')
505 try:
506 doc.writexml(stream)
507 finally:
508 stream.close()
510 def find_broken_version_symlinks(libdir, mappings):
511 """libdir may be a legacy -devel package containing lib* symlinks whose
512 targets would be provided by the corresponding runtime package. If so,
513 create fixed symlinks under $TMPDIR with the real location."""
514 prefix = 'lib'
515 if sys.platform == 'darwin':
516 extension = '.dylib'
517 else:
518 extension = '.so'
520 for x in os.listdir(libdir):
521 if x.startswith(prefix) and x.endswith(extension):
522 path = os.path.join(libdir, x)
523 if os.path.islink(path):
524 target = os.readlink(path)
525 if '/' not in target and not os.path.exists(os.path.join(libdir, target)):
526 print "Broken link %s -> %s; will relocate..." % (x, target)
527 mappings[x[len(prefix):-len(extension)]] = target
529 def set_up_mappings(mappings):
530 """Create a temporary directory with symlinks for each of the library mappings."""
531 libdirs = []
532 if sys.platform == 'darwin':
533 LD_LIBRARY_PATH='DYLD_LIBRARY_PATH'
534 else:
535 LD_LIBRARY_PATH='LD_LIBRARY_PATH'
536 for d in os.environ.get(LD_LIBRARY_PATH, '').split(':'):
537 if d: libdirs.append(d)
538 libdirs += ['/lib', '/usr/lib']
540 def add_ldconf(config_file):
541 if not os.path.isfile(config_file):
542 return
543 for line in file(config_file):
544 d = line.strip()
545 if d.startswith('include '):
546 glob_pattern = d.split(' ', 1)[1]
547 for conf in glob.glob(glob_pattern):
548 add_ldconf(conf)
549 elif d and not d.startswith('#'):
550 libdirs.append(d)
551 add_ldconf('/etc/ld.so.conf')
553 def find_library(name, wanted):
554 # Takes a short-name and target name of a library and returns
555 # the full path of the library.
556 for d in libdirs:
557 path = os.path.join(d, wanted)
558 if os.path.exists(path):
559 return path
560 print "WARNING: library '%s' not found (searched '%s')!" % (wanted, libdirs)
561 return None
563 mappings_dir = os.path.join(os.environ['TMPDIR'], 'lib-mappings')
564 os.mkdir(mappings_dir)
566 old_path = os.environ.get('LIBRARY_PATH', '')
567 if old_path: old_path = ':' + old_path
568 os.environ['LIBRARY_PATH'] = mappings_dir + old_path
570 if sys.platform == 'darwin':
571 soext='.dylib'
572 else:
573 soext='.so'
574 for name, wanted in mappings.items():
575 target = find_library(name, wanted)
576 if target:
577 print "Adding mapping lib%s%s -> %s" % (name, soext, target)
578 os.symlink(target, os.path.join(mappings_dir, 'lib' + name + soext))
580 def dup_src(fn):
581 srcdir = os.environ['SRCDIR'] + '/'
582 for root, dirs, files in os.walk(srcdir):
583 assert root.startswith(srcdir)
584 reldir = root[len(srcdir):]
585 for f in files:
586 target = os.path.join(reldir, f)
587 #print "Copy %s -> %s" % (os.path.join(root, f), target)
588 if os.path.exists(target):
589 os.unlink(target)
590 fn(os.path.join(root, f), target)
591 for d in dirs:
592 target = os.path.join(reldir, d)
593 if not os.path.isdir(target):
594 os.mkdir(target)
596 __main__.commands.append(do_build)