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
12 if hasattr(os
.path
, 'relpath'):
13 relpath
= os
.path
.relpath
15 # Copied from Python 2.6 (GPL compatible license)
16 # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights Reserved
18 # Return the longest prefix of all list elements.
20 "Given a list of pathnames, returns the longest common leading component"
24 for i
, c
in enumerate(s1
):
29 def relpath(path
, start
):
30 """Return a relative version of a 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
:]
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'
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
)):
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
)):
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
))
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
,
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()
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:])
101 do_env_binding(binding
, path
)
103 def fixup_generated_pkgconfig_file(pc_file
):
104 stream
= open(pc_file
)
105 lines
= stream
.readlines()
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
)
117 # After doing a build, check that we didn't generate pkgconfig files with absolute paths
119 def fixup_generated_pkgconfig_files():
120 for root
, dirs
, files
in os
.walk(os
.environ
['DISTDIR']):
121 if os
.path
.basename(root
) == 'pkgconfig':
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 remove_la_file(path
):
128 # Read the contents...
133 # Check it really is a libtool archive...
134 if 'Please DO NOT delete this file' not in data
:
135 warn("Ignoring %s; doesn't look like a libtool archive", path
)
139 print "Removed %s (.la files contain absolute paths)" % path
141 # libtool archives contain hard-coded paths. Lucky, modern systems don't need them, so remove
143 def remove_la_files():
144 for root
, dirs
, files
in os
.walk(os
.environ
['DISTDIR']):
145 if os
.path
.basename(root
) == 'lib':
147 if f
.endswith('.la'):
148 remove_la_file(os
.path
.join(root
, f
))
150 warn("Found static archive '%s'; maybe build with --disable-static?", f
)
152 def do_build_internal(options
, args
):
154 # If a sandbox is being used, we're in it now.
155 import getpass
, socket
, time
157 buildenv
= BuildEnv()
158 sels
= buildenv
.get_selections()
160 builddir
= os
.path
.realpath('build')
161 ensure_dir(buildenv
.metadir
)
163 build_env_xml
= join(buildenv
.metadir
, 'build-environment.xml')
165 buildenv_doc
= buildenv
.get_selections().toDOM()
167 # Create build-environment.xml file
168 root
= buildenv_doc
.documentElement
169 info
= buildenv_doc
.createElementNS(XMLNS_0COMPILE
, 'build-info')
170 root
.appendChild(info
)
171 info
.setAttributeNS(None, 'time', time
.strftime('%Y-%m-%d %H:%M').strip())
172 info
.setAttributeNS(None, 'host', socket
.getfqdn())
173 info
.setAttributeNS(None, 'user', getpass
.getuser())
175 info
.setAttributeNS(None, 'arch', '%s-%s' % (uname
[0], uname
[4]))
176 stream
= file(build_env_xml
, 'w')
177 buildenv_doc
.writexml(stream
, addindent
=" ", newl
="\n")
180 # Create local binary interface file
181 src_iface
= iface_cache
.get_interface(buildenv
.interface
)
182 src_impl
= buildenv
.chosen_impl(buildenv
.interface
)
183 write_sample_interface(buildenv
, src_iface
, src_impl
)
185 # Check 0compile is new enough
186 min_version
= parse_version(src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' min-version', None))
187 if min_version
and min_version
> parse_version(__main__
.version
):
188 raise SafeException("%s-%s requires 0compile >= %s, but we are only version %s" %
189 (src_iface
.get_name(), src_impl
.version
, format_version(min_version
), __main__
.version
))
192 patch_file
= join(buildenv
.metadir
, 'from-%s.patch' % src_impl
.version
)
193 if buildenv
.user_srcdir
:
194 # (ignore errors; will already be shown on stderr)
195 os
.system("diff -urN '%s' src > %s" %
196 (buildenv
.orig_srcdir
.replace('\\', '\\\\').replace("'", "\\'"),
198 if os
.path
.getsize(patch_file
) == 0:
199 os
.unlink(patch_file
)
200 elif os
.path
.exists(patch_file
):
201 os
.unlink(patch_file
)
203 env('BUILDDIR', builddir
)
204 env('DISTDIR', buildenv
.distdir
)
205 env('SRCDIR', buildenv
.user_srcdir
or buildenv
.orig_srcdir
)
209 for needed_iface
in sels
.selections
:
210 impl
= buildenv
.chosen_impl(needed_iface
)
212 for dep
in impl
.dependencies
:
213 dep_iface
= sels
.selections
[dep
.interface
]
214 for b
in dep
.bindings
:
215 if isinstance(b
, EnvironmentBinding
):
216 dep_impl
= buildenv
.chosen_impl(dep
.interface
)
217 if not is_package_impl(dep_impl
):
218 if b
.name
== 'PKG_CONFIG_PATH':
219 do_pkg_config_binding(b
, dep_impl
)
221 do_env_binding(b
, lookup(dep_impl
.id))
223 # These mappings are needed when mixing Zero Install -dev packages with
224 # native package binaries.
226 for impl
in sels
.selections
.values():
227 # Add mappings that have been set explicitly...
228 new_mappings
= impl
.attrs
.get(XMLNS_0COMPILE
+ ' lib-mappings', '')
230 new_mappings
= new_mappings
.split(' ')
231 for mapping
in new_mappings
:
232 assert ':' in mapping
, "lib-mappings missing ':' in '%s' from '%s'" % (mapping
, impl
.feed
)
233 name
, major_version
= mapping
.split(':', 1)
234 assert '/' not in mapping
, "lib-mappings '%s' contains a / in the version number (from '%s')!" % (mapping
, impl
.feed
)
235 mappings
[name
] = 'lib%s.so.%s' % (name
, major_version
)
236 # Auto-detect required mappings where possible...
237 # (if the -dev package is native, the symlinks will be OK)
238 if not is_package_impl(impl
):
239 impl_path
= lookup(impl
.id)
240 for libdirname
in ['lib', 'usr/lib', 'lib64', 'usr/lib64']:
241 libdir
= os
.path
.join(impl_path
, libdirname
)
242 if os
.path
.isdir(libdir
):
243 find_broken_version_symlinks(libdir
, mappings
)
246 set_up_mappings(mappings
)
248 overrides_dir
= os
.path
.join(os
.environ
['TMPDIR'], PKG_CONFIG_OVERRIDES
)
249 if os
.path
.isdir(overrides_dir
):
250 add_overrides
= model
.EnvironmentBinding('PKG_CONFIG_PATH', PKG_CONFIG_OVERRIDES
)
251 do_env_binding(add_overrides
, os
.environ
['TMPDIR'])
253 # Some programs want to put temporary build files in the source directory.
254 # Make a copy of the source if needed.
255 dup_src_type
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' dup-src', None)
256 if dup_src_type
== 'true':
257 dup_src(shutil
.copy2
)
258 env('SRCDIR', builddir
)
260 raise Exception("Unknown dup-src value '%s'" % dup_src_type
)
263 spawn_and_check(find_in_path('sh'), [])
265 command
= src_impl
.attrs
[XMLNS_0COMPILE
+ ' command']
267 # Remove any existing log files
268 for log
in ['build.log', 'build-success.log', 'build-failure.log']:
269 if os
.path
.exists(log
):
272 # Run the command, copying output to a new log
273 log
= file('build.log', 'w')
275 print >>log
, "Build log for %s-%s" % (src_iface
.get_name(),
277 print >>log
, "\nBuilt using 0compile-%s" % __main__
.version
278 print >>log
, "\nBuild system: " + ', '.join(uname
)
279 print >>log
, "\n%s:\n" % ENV_FILE
280 shutil
.copyfileobj(file("../" + ENV_FILE
), log
)
284 if os
.path
.exists(patch_file
):
285 print >>log
, "\nPatched with:\n"
286 shutil
.copyfileobj(file(patch_file
), log
)
289 print "Executing: " + command
290 print >>log
, "Executing: " + command
292 # Tee the output to the console and to the log
293 child
= subprocess
.Popen(command
, shell
= True, stdout
= subprocess
.PIPE
, stderr
= subprocess
.STDOUT
)
295 data
= os
.read(child
.stdout
.fileno(), 100)
297 sys
.stdout
.write(data
)
299 status
= child
.wait()
302 print >>log
, "Build successful"
303 fixup_generated_pkgconfig_files()
306 failure
= "Build failed with exit code %d" % status
308 failure
= "Build failure: exited due to signal %d" % (-status
)
311 os
.rename('build.log', 'build-failure.log')
312 raise SafeException("Command '%s': %s" % (command
, failure
))
314 os
.rename('build.log', 'build-success.log')
319 """build [ --no-sandbox ] [ --shell | --force | --clean ]"""
320 buildenv
= BuildEnv()
321 sels
= buildenv
.get_selections()
323 parser
= OptionParser(usage
="usage: %prog build [options]")
325 parser
.add_option('', "--no-sandbox", help="disable use of sandboxing", action
='store_true')
326 parser
.add_option("-s", "--shell", help="run a shell instead of building", action
='store_true')
327 parser
.add_option("-c", "--clean", help="remove the build directories", action
='store_true')
328 parser
.add_option("-f", "--force", help="build even if dependencies have changed", action
='store_true')
330 parser
.disable_interspersed_args()
332 (options
, args2
) = parser
.parse_args(args
)
334 builddir
= os
.path
.realpath('build')
336 changes
= buildenv
.get_build_changes()
338 if not (options
.force
or options
.clean
):
339 raise SafeException("Build dependencies have changed:\n" +
340 '\n'.join(changes
) + "\n\n" +
341 "To build anyway, use: 0compile build --force\n" +
342 "To do a clean build: 0compile build --clean")
343 if not options
.no_sandbox
:
344 print "Build dependencies have changed:\n" + '\n'.join(changes
)
346 ensure_dir(builddir
, options
.clean
)
347 ensure_dir(buildenv
.distdir
, options
.clean
)
349 if options
.no_sandbox
:
350 return do_build_internal(options
, args2
)
352 tmpdir
= tempfile
.mkdtemp(prefix
= '0compile-')
354 my_dir
= os
.path
.dirname(__file__
)
355 readable
= ['.', my_dir
]
356 writable
= ['build', buildenv
.distdir
, tmpdir
]
357 env('TMPDIR', tmpdir
)
359 for selection
in sels
.selections
.values():
360 if not is_package_impl(selection
):
361 readable
.append(lookup(selection
.id))
364 if __main__
.options
.verbose
:
365 options
.append('--verbose')
367 readable
.append('/etc') # /etc/ld.*
369 spawn_maybe_sandboxed(readable
, writable
, tmpdir
, sys
.executable
, ['-u', sys
.argv
[0]] + options
+ ['build', '--no-sandbox'] + args
)
371 info("Deleting temporary directory '%s'" % tmpdir
)
372 shutil
.rmtree(tmpdir
)
374 def write_sample_interface(buildenv
, iface
, src_impl
):
375 path
= buildenv
.local_iface_file
376 target_arch
= buildenv
.target_arch
378 impl
= minidom
.getDOMImplementation()
380 XMLNS_IFACE
= namespaces
.XMLNS_IFACE
382 doc
= impl
.createDocument(XMLNS_IFACE
, "interface", None)
384 root
= doc
.documentElement
385 root
.setAttributeNS(XMLNS_NAMESPACE
, 'xmlns', XMLNS_IFACE
)
387 def addSimple(parent
, name
, text
= None):
388 elem
= doc
.createElementNS(XMLNS_IFACE
, name
)
390 parent
.appendChild(doc
.createTextNode('\n' + ' ' * (1 + depth(parent
))))
391 parent
.appendChild(elem
)
393 elem
.appendChild(doc
.createTextNode(text
))
397 element
.appendChild(doc
.createTextNode('\n' + ' ' * depth(element
)))
399 addSimple(root
, 'name', iface
.name
)
400 addSimple(root
, 'summary', iface
.summary
)
401 addSimple(root
, 'description', iface
.description
)
402 feed_for
= addSimple(root
, 'feed-for')
405 if uri
.startswith('/'):
406 print "Note: source %s is a local feed" % iface
.uri
407 for feed_uri
in iface
.feed_for
or []:
409 print "Will use <feed-for interface='%s'> instead..." % uri
412 master_feed
= minidom
.parse(uri
).documentElement
413 if master_feed
.hasAttribute('uri'):
414 uri
= master_feed
.getAttribute('uri')
415 print "Will use <feed-for interface='%s'> instead..." % uri
417 feed_for
.setAttributeNS(None, 'interface', uri
)
419 group
= addSimple(root
, 'group')
420 main
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' binary-main', None)
422 group
.setAttributeNS(None, 'main', main
)
424 lib_mappings
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' binary-lib-mappings', None)
426 root
.setAttributeNS(XMLNS_NAMESPACE
, 'xmlns:compile', XMLNS_0COMPILE
)
427 group
.setAttributeNS(XMLNS_0COMPILE
, 'compile:lib-mappings', lib_mappings
)
429 for d
in src_impl
.dependencies
:
430 # 0launch < 0.32 messed up the namespace...
431 if parse_bool(d
.metadata
.get('include-binary', 'false')) or \
432 parse_bool(d
.metadata
.get(XMLNS_0COMPILE
+ ' include-binary', 'false')):
433 requires
= addSimple(group
, 'requires')
434 requires
.setAttributeNS(None, 'interface', d
.interface
)
436 if isinstance(b
, model
.EnvironmentBinding
):
437 env_elem
= addSimple(requires
, 'environment')
438 env_elem
.setAttributeNS(None, 'name', b
.name
)
439 env_elem
.setAttributeNS(None, 'insert', b
.insert
)
441 env_elem
.setAttributeNS(None, 'default', b
.default
)
443 raise Exception('Unknown binding type ' + b
)
446 group
.setAttributeNS(None, 'arch', target_arch
)
447 impl_elem
= addSimple(group
, 'implementation')
448 impl_elem
.setAttributeNS(None, 'version', src_impl
.version
)
450 version_modifier
= buildenv
.version_modifier
452 impl_elem
.setAttributeNS(None, 'version-modifier', version_modifier
)
454 impl_elem
.setAttributeNS(None, 'id', '..')
455 impl_elem
.setAttributeNS(None, 'released', time
.strftime('%Y-%m-%d'))
459 stream
= codecs
.open(path
, 'w', encoding
= 'utf-8')
465 def find_broken_version_symlinks(libdir
, mappings
):
466 """libdir may be a legacy -devel package containing lib* symlinks whose
467 targets would be provided by the corresponding runtime package. If so,
468 create fixed symlinks under $TMPDIR with the real location."""
469 for x
in os
.listdir(libdir
):
470 if x
.startswith('lib') and x
.endswith('.so'):
471 path
= os
.path
.join(libdir
, x
)
472 if os
.path
.islink(path
):
473 target
= os
.readlink(path
)
474 if '/' not in target
and not os
.path
.exists(os
.path
.join(libdir
, target
)):
475 print "Broken link %s -> %s; will relocate..." % (x
, target
)
476 mappings
[x
[3:-3]] = target
478 def set_up_mappings(mappings
):
479 """Create a temporary directory with symlinks for each of the library mappings."""
481 for d
in os
.environ
.get('LD_LIBRARY_PATH', '').split(':'):
482 if d
: libdirs
.append(d
)
483 libdirs
+= ['/lib', '/usr/lib']
485 def add_ldconf(config_file
):
486 if not os
.path
.isfile(config_file
):
488 for line
in file(config_file
):
490 if d
.startswith('include '):
491 glob_pattern
= d
.split(' ', 1)[1]
492 for conf
in glob
.glob(glob_pattern
):
494 elif d
and not d
.startswith('#'):
496 add_ldconf('/etc/ld.so.conf')
498 def find_library(name
, wanted
):
499 # Takes a short-name and target name of a library and returns
500 # the full path of the library.
502 path
= os
.path
.join(d
, wanted
)
503 if os
.path
.exists(path
):
505 print "WARNING: library '%s' not found (searched '%s')!" % (wanted
, libdirs
)
508 mappings_dir
= os
.path
.join(os
.environ
['TMPDIR'], 'lib-mappings')
509 os
.mkdir(mappings_dir
)
511 old_path
= os
.environ
.get('LIBRARY_PATH', '')
512 if old_path
: old_path
= ':' + old_path
513 os
.environ
['LIBRARY_PATH'] = mappings_dir
+ old_path
515 for name
, wanted
in mappings
.items():
516 target
= find_library(name
, wanted
)
518 print "Adding mapping lib%s.so -> %s" % (name
, target
)
519 os
.symlink(target
, os
.path
.join(mappings_dir
, 'lib' + name
+ '.so'))
522 srcdir
= os
.environ
['SRCDIR'] + '/'
523 for root
, dirs
, files
in os
.walk(srcdir
):
524 assert root
.startswith(srcdir
)
525 reldir
= root
[len(srcdir
):]
527 target
= os
.path
.join(reldir
, f
)
528 #print "Copy %s -> %s" % (os.path.join(root, f), target)
529 if os
.path
.exists(target
):
531 fn(os
.path
.join(root
, f
), target
)
533 target
= os
.path
.join(reldir
, d
)
534 if not os
.path
.isdir(target
):
537 __main__
.commands
.append(do_build
)