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
12 # If we have to modify any pkg-config files, we put the new versions in $TMPDIR/PKG_CONFIG_OVERRIDES
13 PKG_CONFIG_OVERRIDES
= 'pkg-config-overrides'
16 os
.environ
[name
] = value
17 print "%s=%s" % (name
, value
)
19 def do_env_binding(binding
, path
):
20 env(binding
.name
, binding
.get_value(path
, os
.environ
.get(binding
.name
, None)))
22 def correct_for_64bit(base
, rel_path
):
23 """If rel_path starts lib or usr/lib and doesn't exist, try with lib64 instead."""
24 if os
.path
.exists(os
.path
.join(base
, rel_path
)):
27 if rel_path
.startswith('lib/') or rel_path
.startswith('usr/lib/'):
28 new_rel_path
= rel_path
.replace('lib/', 'lib64/', 1)
29 if os
.path
.exists(os
.path
.join(base
, new_rel_path
)):
34 def write_pc(name
, lines
):
35 overrides_dir
= os
.path
.join(os
.environ
['TMPDIR'], PKG_CONFIG_OVERRIDES
)
36 if not os
.path
.isdir(overrides_dir
):
37 os
.mkdir(overrides_dir
)
38 stream
= open(os
.path
.join(overrides_dir
, name
), 'w')
39 stream
.write(''.join(lines
))
42 def do_pkg_config_binding(binding
, impl
):
43 feed_name
= impl
.feed
.split('/')[-1]
44 path
= lookup(impl
.id)
45 new_insert
= correct_for_64bit(path
, binding
.insert
)
46 if new_insert
!= binding
.insert
:
47 print "PKG_CONFIG_PATH dir <%s>/%s not found; using %s instead" % (feed_name
, binding
.insert
, new_insert
)
48 binding
= model
.EnvironmentBinding(binding
.name
,
53 orig_path
= os
.path
.join(path
, binding
.insert
)
54 if os
.path
.isdir(orig_path
):
55 for pc
in os
.listdir(orig_path
):
56 stream
= open(os
.path
.join(orig_path
, pc
))
57 lines
= stream
.readlines()
59 for i
, line
in enumerate(lines
):
60 if '=' not in line
: continue
61 name
, value
= [x
.strip() for x
in line
.split('=', 1)]
62 if name
== 'prefix' and value
.startswith('/'):
63 print "Absolute prefix=%s in %s; overriding..." % (value
, feed_name
)
64 lines
[i
] = 'prefix=%s/%s\n' % (path
, value
[1:])
67 do_env_binding(binding
, path
)
69 def fixup_generated_pkgconfig_file(pc_file
):
70 stream
= open(pc_file
)
71 lines
= stream
.readlines()
73 for i
, line
in enumerate(lines
):
74 if '=' not in line
: continue
75 name
, value
= [x
.strip() for x
in line
.split('=', 1)]
76 if name
== 'prefix' and value
.startswith('/'):
77 print "Absolute prefix=%s in %s; fixing..." % (value
, pc_file
)
78 rel_path
= os
.path
.relpath(value
, os
.path
.dirname(pc_file
)) # Requires Python 2.6
79 lines
[i
] = 'prefix=${pcfiledir}/%s\n' % rel_path
80 write_pc(pc_file
, lines
)
83 # After doing a build, check that we didn't generate pkgconfig files with absolute paths
85 def fixup_generated_pkgconfig_files():
86 for root
, dirs
, files
in os
.walk(os
.environ
['DISTDIR']):
87 if os
.path
.basename(root
) == 'pkgconfig':
90 info("Checking generated pkgconfig file '%s'", f
)
91 fixup_generated_pkgconfig_file(os
.path
.join(root
, f
))
93 def do_build_internal(options
, args
):
95 # If a sandbox is being used, we're in it now.
96 import getpass
, socket
, time
99 sels
= buildenv
.get_selections()
101 builddir
= os
.path
.realpath('build')
102 ensure_dir(buildenv
.metadir
)
104 build_env_xml
= join(buildenv
.metadir
, 'build-environment.xml')
106 buildenv_doc
= buildenv
.get_selections().toDOM()
108 # Create build-environment.xml file
109 root
= buildenv_doc
.documentElement
110 info
= buildenv_doc
.createElementNS(XMLNS_0COMPILE
, 'build-info')
111 root
.appendChild(info
)
112 info
.setAttributeNS(None, 'time', time
.strftime('%Y-%m-%d %H:%M').strip())
113 info
.setAttributeNS(None, 'host', socket
.getfqdn())
114 info
.setAttributeNS(None, 'user', getpass
.getuser())
116 info
.setAttributeNS(None, 'arch', '%s-%s' % (uname
[0], uname
[4]))
117 stream
= file(build_env_xml
, 'w')
118 buildenv_doc
.writexml(stream
, addindent
=" ", newl
="\n")
121 # Create local binary interface file
122 src_iface
= iface_cache
.get_interface(buildenv
.interface
)
123 src_impl
= buildenv
.chosen_impl(buildenv
.interface
)
124 write_sample_interface(buildenv
, src_iface
, src_impl
)
126 # Check 0compile is new enough
127 min_version
= parse_version(src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' min-version', None))
128 if min_version
and min_version
> parse_version(__main__
.version
):
129 raise SafeException("%s-%s requires 0compile >= %s, but we are only version %s" %
130 (src_iface
.get_name(), src_impl
.version
, format_version(min_version
), __main__
.version
))
133 patch_file
= join(buildenv
.metadir
, 'from-%s.patch' % src_impl
.version
)
134 if buildenv
.user_srcdir
:
135 # (ignore errors; will already be shown on stderr)
136 os
.system("diff -urN '%s' src > %s" %
137 (buildenv
.orig_srcdir
.replace('\\', '\\\\').replace("'", "\\'"),
139 if os
.path
.getsize(patch_file
) == 0:
140 os
.unlink(patch_file
)
141 elif os
.path
.exists(patch_file
):
142 os
.unlink(patch_file
)
144 env('BUILDDIR', builddir
)
145 env('DISTDIR', buildenv
.distdir
)
146 env('SRCDIR', buildenv
.user_srcdir
or buildenv
.orig_srcdir
)
150 for needed_iface
in sels
.selections
:
151 impl
= buildenv
.chosen_impl(needed_iface
)
153 for dep
in impl
.dependencies
:
154 dep_iface
= sels
.selections
[dep
.interface
]
155 for b
in dep
.bindings
:
156 if isinstance(b
, EnvironmentBinding
):
157 dep_impl
= buildenv
.chosen_impl(dep
.interface
)
158 if b
.name
== 'PKG_CONFIG_PATH':
159 do_pkg_config_binding(b
, dep_impl
)
161 do_env_binding(b
, lookup(dep_impl
.id))
164 for impl
in sels
.selections
.values():
165 new_mappings
= impl
.attrs
.get(XMLNS_0COMPILE
+ ' lib-mappings', '')
167 new_mappings
= new_mappings
.split(' ')
168 for mapping
in new_mappings
:
169 assert ':' in mapping
, "lib-mappings missing ':' in '%s' from '%s'" % (mapping
, impl
.feed
)
170 name
, major_version
= mapping
.split(':', 1)
171 assert '/' not in mapping
, "lib-mappings '%s' contains a / in the version number (from '%s')!" % (mapping
, impl
.feed
)
172 mappings
[name
] = 'lib%s.so.%s' % (name
, major_version
)
173 impl_path
= lookup(impl
.id)
174 for libdirname
in ['lib', 'usr/lib', 'lib64', 'usr/lib64']:
175 libdir
= os
.path
.join(impl_path
, libdirname
)
176 if os
.path
.isdir(libdir
):
177 find_broken_version_symlinks(libdir
, mappings
)
180 set_up_mappings(mappings
)
182 overrides_dir
= os
.path
.join(os
.environ
['TMPDIR'], PKG_CONFIG_OVERRIDES
)
183 if os
.path
.isdir(overrides_dir
):
184 add_overrides
= model
.EnvironmentBinding('PKG_CONFIG_PATH', PKG_CONFIG_OVERRIDES
)
185 do_env_binding(add_overrides
, os
.environ
['TMPDIR'])
187 # Some programs want to put temporary build files in the source directory.
188 # Make a copy of the source if needed.
189 dup_src_type
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' dup-src', None)
190 if dup_src_type
== 'true':
191 dup_src(shutil
.copy2
)
192 env('SRCDIR', builddir
)
194 raise Exception("Unknown dup-src value '%s'" % dup_src_type
)
197 spawn_and_check(find_in_path('sh'), [])
199 command
= src_impl
.attrs
[XMLNS_0COMPILE
+ ' command']
201 # Remove any existing log files
202 for log
in ['build.log', 'build-success.log', 'build-failure.log']:
203 if os
.path
.exists(log
):
206 # Run the command, copying output to a new log
207 log
= file('build.log', 'w')
209 print >>log
, "Build log for %s-%s" % (src_iface
.get_name(),
211 print >>log
, "\nBuilt using 0compile-%s" % __main__
.version
212 print >>log
, "\nBuild system: " + ', '.join(uname
)
213 print >>log
, "\n%s:\n" % ENV_FILE
214 shutil
.copyfileobj(file("../" + ENV_FILE
), log
)
218 if os
.path
.exists(patch_file
):
219 print >>log
, "\nPatched with:\n"
220 shutil
.copyfileobj(file(patch_file
), log
)
223 print "Executing: " + command
224 print >>log
, "Executing: " + command
226 # Tee the output to the console and to the log
227 child
= subprocess
.Popen(command
, shell
= True, stdout
= subprocess
.PIPE
, stderr
= subprocess
.STDOUT
)
229 data
= os
.read(child
.stdout
.fileno(), 100)
231 sys
.stdout
.write(data
)
233 status
= child
.wait()
236 print >>log
, "Build successful"
237 fixup_generated_pkgconfig_files()
239 failure
= "Build failed with exit code %d" % status
241 failure
= "Build failure: exited due to signal %d" % (-status
)
244 os
.rename('build.log', 'build-failure.log')
245 raise SafeException("Command '%s': %s" % (command
, failure
))
247 os
.rename('build.log', 'build-success.log')
252 """build [ --no-sandbox ] [ --shell | --force | --clean ]"""
253 buildenv
= BuildEnv()
254 sels
= buildenv
.get_selections()
256 parser
= OptionParser(usage
="usage: %prog build [options]")
258 parser
.add_option('', "--no-sandbox", help="disable use of sandboxing", action
='store_true')
259 parser
.add_option("-s", "--shell", help="run a shell instead of building", action
='store_true')
260 parser
.add_option("-c", "--clean", help="remove the build directories", action
='store_true')
261 parser
.add_option("-f", "--force", help="build even if dependencies have changed", action
='store_true')
263 parser
.disable_interspersed_args()
265 (options
, args2
) = parser
.parse_args(args
)
267 builddir
= os
.path
.realpath('build')
269 changes
= buildenv
.get_build_changes()
271 if not (options
.force
or options
.clean
):
272 raise SafeException("Build dependencies have changed:\n" +
273 '\n'.join(changes
) + "\n\n" +
274 "To build anyway, use: 0compile build --force\n" +
275 "To do a clean build: 0compile build --clean")
276 if not options
.no_sandbox
:
277 print "Build dependencies have changed:\n" + '\n'.join(changes
)
279 ensure_dir(builddir
, options
.clean
)
280 ensure_dir(buildenv
.distdir
, options
.clean
)
282 if options
.no_sandbox
:
283 return do_build_internal(options
, args2
)
285 tmpdir
= tempfile
.mkdtemp(prefix
= '0compile-')
287 my_dir
= os
.path
.dirname(__file__
)
288 readable
= ['.', my_dir
]
289 writable
= ['build', buildenv
.distdir
, tmpdir
]
290 env('TMPDIR', tmpdir
)
292 for selection
in sels
.selections
.values():
293 readable
.append(lookup(selection
.id))
296 if __main__
.options
.verbose
:
297 options
.append('--verbose')
299 readable
.append('/etc') # /etc/ld.*
301 spawn_maybe_sandboxed(readable
, writable
, tmpdir
, sys
.executable
, [sys
.argv
[0]] + options
+ ['build', '--no-sandbox'] + args
)
303 info("Deleting temporary directory '%s'" % tmpdir
)
304 shutil
.rmtree(tmpdir
)
306 def write_sample_interface(buildenv
, iface
, src_impl
):
307 path
= buildenv
.local_iface_file
308 target_arch
= buildenv
.target_arch
310 impl
= minidom
.getDOMImplementation()
312 XMLNS_IFACE
= namespaces
.XMLNS_IFACE
314 doc
= impl
.createDocument(XMLNS_IFACE
, "interface", None)
316 root
= doc
.documentElement
317 root
.setAttributeNS(XMLNS_NAMESPACE
, 'xmlns', XMLNS_IFACE
)
319 def addSimple(parent
, name
, text
= None):
320 elem
= doc
.createElementNS(XMLNS_IFACE
, name
)
322 parent
.appendChild(doc
.createTextNode('\n' + ' ' * (1 + depth(parent
))))
323 parent
.appendChild(elem
)
325 elem
.appendChild(doc
.createTextNode(text
))
329 element
.appendChild(doc
.createTextNode('\n' + ' ' * depth(element
)))
331 addSimple(root
, 'name', iface
.name
)
332 addSimple(root
, 'summary', iface
.summary
)
333 addSimple(root
, 'description', iface
.description
)
334 feed_for
= addSimple(root
, 'feed-for')
337 if uri
.startswith('/'):
338 print "Note: source %s is a local feed" % iface
.uri
339 for feed_uri
in iface
.feed_for
or []:
341 print "Will use <feed-for interface='%s'> instead..." % uri
344 master_feed
= minidom
.parse(uri
).documentElement
345 if master_feed
.hasAttribute('uri'):
346 uri
= master_feed
.getAttribute('uri')
347 print "Will use <feed-for interface='%s'> instead..." % uri
349 feed_for
.setAttributeNS(None, 'interface', uri
)
351 group
= addSimple(root
, 'group')
352 main
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' binary-main', None)
354 group
.setAttributeNS(None, 'main', main
)
356 lib_mappings
= src_impl
.attrs
.get(XMLNS_0COMPILE
+ ' binary-lib-mappings', None)
358 root
.setAttributeNS(XMLNS_NAMESPACE
, 'xmlns:compile', XMLNS_0COMPILE
)
359 group
.setAttributeNS(XMLNS_0COMPILE
, 'compile:lib-mappings', lib_mappings
)
361 for d
in src_impl
.dependencies
:
362 # 0launch < 0.32 messed up the namespace...
363 if parse_bool(d
.metadata
.get('include-binary', 'false')) or \
364 parse_bool(d
.metadata
.get(XMLNS_0COMPILE
+ ' include-binary', 'false')):
365 requires
= addSimple(group
, 'requires')
366 requires
.setAttributeNS(None, 'interface', d
.interface
)
368 if isinstance(b
, model
.EnvironmentBinding
):
369 env_elem
= addSimple(requires
, 'environment')
370 env_elem
.setAttributeNS(None, 'name', b
.name
)
371 env_elem
.setAttributeNS(None, 'insert', b
.insert
)
373 env_elem
.setAttributeNS(None, 'default', b
.default
)
375 raise Exception('Unknown binding type ' + b
)
378 group
.setAttributeNS(None, 'arch', target_arch
)
379 impl_elem
= addSimple(group
, 'implementation')
380 impl_elem
.setAttributeNS(None, 'version', src_impl
.version
)
382 version_modifier
= buildenv
.version_modifier
384 impl_elem
.setAttributeNS(None, 'version-modifier', version_modifier
)
386 impl_elem
.setAttributeNS(None, 'id', '..')
387 impl_elem
.setAttributeNS(None, 'released', time
.strftime('%Y-%m-%d'))
391 stream
= codecs
.open(path
, 'w', encoding
= 'utf-8')
397 def find_broken_version_symlinks(libdir
, mappings
):
398 """libdir may be a legacy -devel package containing lib* symlinks whose
399 targets would be provided by the corresponding runtime package. If so,
400 create fixed symlinks under $TMPDIR with the real location."""
401 for x
in os
.listdir(libdir
):
402 if x
.startswith('lib') and x
.endswith('.so'):
403 path
= os
.path
.join(libdir
, x
)
404 if os
.path
.islink(path
):
405 target
= os
.readlink(path
)
406 if '/' not in target
and not os
.path
.exists(os
.path
.join(libdir
, target
)):
407 print "Broken link %s -> %s; will relocate..." % (x
, target
)
408 mappings
[x
[3:-3]] = target
410 def set_up_mappings(mappings
):
411 """Create a temporary directory with symlinks for each of the library mappings."""
413 for d
in os
.environ
.get('LD_LIBRARY_PATH', '').split(':'):
414 if d
: libdirs
.append(d
)
415 libdirs
+= ['/lib', '/usr/lib']
417 def add_ldconf(config_file
):
418 if not os
.path
.isfile(config_file
):
420 for line
in file(config_file
):
422 if d
.startswith('include '):
423 glob_pattern
= d
.split(' ', 1)[1]
424 for conf
in glob
.glob(glob_pattern
):
426 elif d
and not d
.startswith('#'):
428 add_ldconf('/etc/ld.so.conf')
430 def find_library(name
, wanted
):
431 # Takes a short-name and target name of a library and returns
432 # the full path of the library.
434 path
= os
.path
.join(d
, wanted
)
435 if os
.path
.exists(path
):
437 print "WARNING: library '%s' not found (searched '%s')!" % (wanted
, libdirs
)
440 mappings_dir
= os
.path
.join(os
.environ
['TMPDIR'], 'lib-mappings')
441 os
.mkdir(mappings_dir
)
443 old_path
= os
.environ
.get('LIBRARY_PATH', '')
444 if old_path
: old_path
= ':' + old_path
445 os
.environ
['LIBRARY_PATH'] = mappings_dir
+ old_path
447 for name
, wanted
in mappings
.items():
448 target
= find_library(name
, wanted
)
450 print "Adding mapping lib%s.so -> %s" % (name
, target
)
451 os
.symlink(target
, os
.path
.join(mappings_dir
, 'lib' + name
+ '.so'))
454 srcdir
= os
.environ
['SRCDIR'] + '/'
455 for root
, dirs
, files
in os
.walk(srcdir
):
456 assert root
.startswith(srcdir
)
457 reldir
= root
[len(srcdir
):]
459 target
= os
.path
.join(reldir
, f
)
460 #print "Copy %s -> %s" % (os.path.join(root, f), target)
461 if os
.path
.exists(target
):
463 fn(os
.path
.join(root
, f
), target
)
465 target
= os
.path
.join(reldir
, d
)
466 if not os
.path
.isdir(target
):
469 __main__
.commands
.append(do_build
)