OSDN Git Service

BuildSystem:
[handbrake-jp/handbrake-jp-git.git] / make / configure.py
1 import fnmatch
2 import optparse
3 import os
4 import platform
5 import re
6 import subprocess
7 import sys
8 import time
9
10 from optparse import OptionGroup
11 from optparse import OptionGroup
12 from optparse import OptionParser
13 from sys import stderr
14 from sys import stdout
15
16 ###############################################################################
17
18 def errf( format, *args ):
19     stderr.write( ('ERROR: ' + format + '\n') % args )
20     sys.exit( 1 )
21
22 def outf( format, *args ):
23     stdout.write( (format + '\n') % args )
24
25 ###############################################################################
26
27 ## Expand values of iterable object into a decent string representation.
28 ##
29 def expandValues( obj ):
30     buf = ''
31     for v in obj:
32         buf += ', ' + v
33     return '{ ' + buf[2:] + ' }'
34
35 ###############################################################################
36
37 ## Find executable by searching path.
38 ## On success, returns full pathname of executable.
39 ## On fail, returns None.
40 ##
41 def findExecutable( name ):
42     if len( os.path.split(name)[0] ):
43         return name if os.access( name, os.X_OK ) else None
44
45     if not os.environ.has_key( 'PATH' ) or os.environ[ 'PATH' ] == '':
46         path = os.defpath
47     else:
48         path = os.environ['PATH']
49
50     for dir in path.split( os.pathsep ):
51         f = os.path.join( dir, name )
52         if os.access( f, os.X_OK ):
53             return f
54     return None
55
56 ###############################################################################
57
58 def computeNumCPU():
59     ## good for darwin9.6.0 and linux
60     try:
61         n = os.sysconf( 'SC_NPROCESSORS_ONLN' )
62         if n < 1:
63             n = 1
64         return n
65     except:
66         pass
67     ## windows
68     try:
69         n = int( os.environ['NUMBER_OF_PROCESSORS'] )
70         if n < 1:
71             n = 1
72         return n
73     except:
74         pass
75     return 1
76
77 ###############################################################################
78
79 ## taken from python2.6 -- we need it
80 def relpath(path, start=os.path.curdir):
81     """Return a relative version of a path"""
82
83     if not path:
84         raise ValueError("no path specified")
85
86     start_list = os.path.abspath(start).split(os.sep)
87     path_list = os.path.abspath(path).split(os.sep)
88
89     # Work out how much of the filepath is shared by start and path.
90     i = len(os.path.commonprefix([start_list, path_list]))
91
92     rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:]
93     if not rel_list:
94         return os.path.curdir
95     return os.path.join(*rel_list)
96
97 ###############################################################################
98
99 # compute project dir which should be 2 dirs below this script
100 build_dir = os.curdir
101 project_dir = os.path.normpath( sys.argv[0] )
102 for i in range( 2 ):
103     project_dir = os.path.dirname( project_dir )
104 if len( project_dir ) == 0:
105     project_dir = os.curdir
106 initial_project_dir = project_dir
107
108 ###############################################################################
109
110 ## model gnu-autotools platform guess
111 ##
112 ## native format:
113 ##   (PROC)-(VENDOR)-(SYSTEM)(RELEASE)-(EXTRA)
114 ##
115 ## examples:
116 ##   i386-apple-darwin9.6.0    (Mac OS X 10.5.6 Intel)
117 ##   powerpc-apple-darwin9.6.0 (Mac OS X 10.5.6 PPC)
118 ##   i686-pc-cygwin            (Cygwin, Microsoft Vista)
119 ##   x86_64-unknown-linux-gnu  (Linux, Fedora 10 x86_64)
120 ##
121 class Guess:
122     def __init__( self ):
123         self.machine = 'unknown'
124         self.vendor  = 'unknown'
125         self.system  = 'unknown'
126         self.systemc = 'Unknown'
127         self.release = '0.0.0'
128         self.extra   = ''
129
130         p_system    = platform.system().lower()
131         p_systemc   = platform.system()
132         p_release   = platform.release().lower()
133         p_processor = platform.processor().lower()
134         p_machine   = platform.machine().lower()
135
136         if re.match( 'cygwin', p_system ):
137             self.machine = p_machine
138             self.vendor  = 'pc'
139             self.system  = 'cygwin'
140             self.systemc = 'Cygwin'
141             self.release = ''
142             self.extra   = ''
143         elif re.match( 'darwin', p_system ):
144             self.machine = p_machine
145             self.vendor  = 'apple'
146             self.system  = p_system
147             self.systemc = p_systemc
148             self.release = p_release
149             self.extra   = ''
150         elif re.match( 'linux', p_system ):
151             self.machine = p_machine
152             self.vendor  = 'unknown'
153             self.system  = p_system
154             self.systemc = p_systemc
155             self.release = ''
156             self.extra   = 'gnu'
157             self.title   = 'Linux %s' % (p_machine)
158         else:
159             errf( 'unrecognized host system: %s', p_system )
160
161     def __str__( self ):
162         if len(self.extra):
163             return '%s-%s-%s%s-%s' % (self.machine,self.vendor,self.system,self.release,self.extra)
164         else:
165             return '%s-%s-%s%s' % (self.machine,self.vendor,self.system,self.release)
166
167     def match( self, spec ):
168         return fnmatch.fnmatch( str(self), spec )
169
170 ###############################################################################
171
172 # a tool represents a command-line tool which may be searched for in PATH
173 class Tool:
174     def __init__( self, parent, optional, var, *pool ):
175         self.name     = pool[0]
176         self.optional = optional
177         self.var      = var
178         self.pool     = pool
179         self.found    = None
180         if parent:
181             parent.register( self )
182
183     def addToConfig( self, config ):
184         config.add( self.var, self.found )
185
186     def addToGroup( self, group ):
187         group.add_option( '', '--' + self.name, help='specify %s location' % (self.name), default=None, metavar='EXE' )
188
189     def locate( self, options ):
190         spec = options.__dict__[self.name]
191         pool = self.pool if not spec else [spec]
192         for p in pool:
193             self.found = findExecutable( p )
194             if self.found:
195                 outf( 'located %s: %s', self.name, self.found )
196                 return
197         if self.optional:
198             outf( 'missing: %s (optional)', self.name )
199         else:
200             errf( 'unable to locate tool: %s', self.name )
201
202 ## a select tool picks first found from a list of tools
203 class SelectTool( Tool ):
204     def __init__( self, parent, var, name, *pool ):
205         self.var     = var
206         self.name    = name
207         self.pool    = pool
208         self.found   = None
209
210         self.poolMap = {}
211         for p in self.pool:
212             self.poolMap[p.name] = p
213         if parent:
214             parent.register( self )
215
216     def addToConfig( self, config ):
217         config.add( self.var, self.found )
218
219     def addToGroup( self, group ):
220         group.add_option( '', '--' + self.name, help='select %s mode: %s' % (self.name,expandValues(self.poolMap)),
221             default=self.name, metavar='MODE' )
222
223     def locate( self, options ):
224         spec = options.__dict__[self.name]
225         if spec in self.poolMap:
226             self.found = spec
227             return
228         for p in self.pool:
229             if p.found:
230                 self.found = p.name
231                 outf( 'selected %s: %s', self.name, self.found )
232                 return
233         errf( 'require at least one location of: %s', expandValues( self.poolMap ))
234
235 ###############################################################################
236
237 class ToolSet:
238     def __init__( self ):
239         self.items = []
240         Tool( self, False, 'AR.exe',    'ar' )
241         Tool( self, False, 'CP.exe',    'cp' )
242         Tool( self, True,  'CURL.exe',  'curl' )
243         Tool( self, False, 'GCC.gcc',   'gcc', 'gcc-4' )
244         Tool( self, False, 'M4.exe',    'm4' )
245         Tool( self, False, 'MKDIR.exe', 'mkdir' )
246         Tool( self, False, 'PATCH.exe', 'patch' )
247         Tool( self, False, 'RM.exe',    'rm' )
248         Tool( self, False, 'TAR.exe',   'tar' )
249         Tool( self, True,  'WGET.exe',  'wget' )
250
251         SelectTool( self, 'FETCH.select', 'fetch', self.wget, self.curl )
252
253     def register( self, item ):
254         self.__dict__[item.name] = item
255         self.items.append( item )
256
257 ###############################################################################
258
259 class OptionMode( list ):
260     def __init__( self, default, *items ):
261         super( OptionMode, self ).__init__( items )
262         self.default = items[default]
263         self.mode = self.default
264
265     def __str__( self ):
266         return ' '.join( self ).replace( self.mode, '*'+self.mode )
267
268     def addToGroup( self, group, option, name ):
269         group.add_option( '', option, help='select %s mode: %s' % (name,self), default=self.mode, metavar='MODE' )
270
271     def setFromOption( self, name, mode ):
272         if mode not in self:
273             errf( 'invalid %s mode: %s', name, mode )
274         self.mode = mode
275
276 ###############################################################################
277
278 ## create singletons
279 guessHost  = Guess()
280 guessBuild = Guess()
281
282 makeTool = Tool( None, False, 'CONF.make', 'gmake', 'make' )
283 tools = ToolSet()
284
285 debugMode    = OptionMode( 0, 'none', 'min', 'std', 'max' )
286 optimizeMode = OptionMode( 1, 'none', 'speed', 'size' )
287
288 ## populate platform-specific architecture modes
289 if guessHost.match( 'i386-*-darwin8.*' ):
290     archMode = OptionMode( 0, 'i386', 'ppc' )
291 elif guessHost.match( 'powerpc-*-darwin8.*' ):
292     archMode = OptionMode( 1, 'i386', 'ppc' )
293 elif guessHost.match( 'i386-*-darwin9.*' ):
294     archMode = OptionMode( 0, 'i386', 'x86_64', 'ppc', 'ppc64' )
295 elif guessHost.match( 'powerpc-*-darwin9.*' ):
296     archMode = OptionMode( 2, 'i386', 'x86_64', 'ppc', 'ppc64' )
297 else:
298     archMode = OptionMode( 0, guessHost.machine )
299
300 if guessHost.match( '*-*-darwin*' ):
301     d_prefix = '/Applications'
302 else: 
303     d_prefix = '/usr/local'
304
305 ## create parser
306 parser = OptionParser( 'Usage: %prog' )
307
308 ## add hidden options
309 parser.add_option( '', '--conf-method', default='terminal', action='store', help=optparse.SUPPRESS_HELP )
310
311 ## add install options
312 group = OptionGroup( parser, 'Installation Options' )
313 group.add_option( '', '--prefix', default=d_prefix, action='store',
314     help='specify destination for final products (%s)' % (d_prefix) )
315 parser.add_option_group( group )
316
317 group = OptionGroup( parser, 'Feature Options' )
318 group.add_option( '', '--disable-xcode', default=False, action='store_true',
319     help='disable Xcode (Darwin only)' )
320 group.add_option( '', '--disable-gtk', default=False, action='store_true',
321     help='disable GTK GUI (Linux only)' )
322 parser.add_option_group( group )
323
324 ## add launch options
325 group = OptionGroup( parser, 'Launch Options' )
326 group.add_option( '', '--launch', default=False, action='store_true',
327     help='launch build, capture log and wait for completion' )
328 group.add_option( '', '--launch-jobs', default=1, action='store', metavar='N',
329     help='allow N jobs at once; 0 to match CPU count (1)' )
330 group.add_option( '', '--launch-args', default=None, action='store', metavar='ARGS',
331     help='specify additional ARGS for launch command' )
332 group.add_option( '', '--launch-dir', default='build', action='store', metavar='DIR',
333     help='specify scratch DIR to use for build (build)' )
334 group.add_option( '', '--launch-force', default=False, action='store_true',
335     help='force use of scratch directory even if exists' )
336 group.add_option( '', '--launch-log', default='log.txt', action='store', metavar='FILE',
337     help='specify log FILE (log.txt)' )
338 group.add_option( '', '--launch-quiet', default=False, action='store_true',
339     help='do not echo build output' )
340 parser.add_option_group( group )
341
342 ## add compile options
343 group = OptionGroup( parser, 'Compiler Options' )
344 debugMode.addToGroup( group, '--debug', 'debug' )
345 optimizeMode.addToGroup( group, '--optimize', 'optimize' )
346 archMode.addToGroup( group, '--arch', 'architecutre' )
347 parser.add_option_group( group )
348
349 ## add tool options
350 group = OptionGroup( parser, 'Tool Options' )
351 makeTool.addToGroup( group )
352 for tool in tools.items:
353     tool.addToGroup( group )
354 parser.add_option_group( group )
355
356 (options,args) = parser.parse_args()
357
358 exports = []
359 for arg in args:
360     m = re.match( '([^=]+)=(.*)', arg )
361     if m:
362         exports.append( m.groups() )
363
364 ## recompute values when launch mode
365 if options.launch:
366     options.launch_jobs = int(options.launch_jobs)
367     build_dir = options.launch_dir
368     if os.path.isabs( build_dir ):
369         project_dir = os.getcwd() 
370     else:
371         project_dir = os.path.normpath( relpath( project_dir, build_dir ))
372     if options.launch_jobs == 0:
373         options.launch_jobs = computeNumCPU()
374     if options.launch_jobs < 1:
375         options.launch_jobs = 1
376     elif options.launch_jobs > 8:
377         options.launch_jobs = 8
378
379 ## make sure configure does not run in source root
380 if os.path.abspath( project_dir ) == os.path.abspath( build_dir ):
381     errf( 'scratch (build) directory must not be the same as source root' )
382
383 ## validate modes
384 debugMode.setFromOption( 'debug', options.debug )
385 optimizeMode.setFromOption( 'optimize', options.optimize )
386 archMode.setFromOption( 'architecture', options.arch )
387
388 ## update guessBuild as per architecture mode
389 if guessHost.match( '*-*-darwin*' ):
390     if archMode.mode == 'i386':
391         guessBuild.machine = 'i386'
392     elif archMode.mode == 'x86_64':
393         guessBuild.machine = 'x86_64'
394     elif archMode.mode == 'ppc':
395         guessBuild.machine = 'powerpc'
396     elif archMode.mode == 'ppc64':
397         guessBuild.machine = 'powerpc64'
398 else:
399     guessBuild.machine = archMode.mode
400 guessBuild.cross = 0 if archMode.default == archMode.mode else 1
401
402 # locate tools
403 makeTool.locate( options )
404 for tool in tools.items:
405     tool.locate( options )
406
407 ###############################################################################
408
409 ## Repository object.
410 ## Holds information gleaned from subversion working dir.
411 ##
412 ## Builds are classed into one of the following types:
413 ##
414 ##  release
415 ##      must be built from official svn with '/tags/' in the url
416 ##  developer
417 ##      must be built from official svn but is not a release
418 ##  unofficial
419 ##      all other builds
420 ##
421 class Repository:
422     def __init__( self ):
423         self.url       = 'svn://nowhere.com/project/unknown'
424         self.root      = 'svn://nowhere.com/project'
425         self.branch    = 'unknown'
426         self.uuid      = '00000000-0000-0000-0000-000000000000';
427         self.rev       = 0
428         self.date      = '0000-00-00 00:00:00 -0000'
429         self.wcversion = 'exported'
430         self.official  = 0
431         self.type      = 'unofficial'
432
433         # parse output: svnversion PROJECT_DIR
434         cmd = 'svnversion ' + initial_project_dir
435         print 'running: %s' % (cmd)
436         try:
437             p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
438             p.wait();
439             if p.returncode == 0:
440                 self.wcversion = p.stdout.readline().rstrip()
441         except:
442             pass
443
444         # parse output: svn info PROJECT_DIR
445         cmd = 'svn info ' + initial_project_dir
446         print 'running: %s' % (cmd)
447         try:
448             p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
449             p.wait();
450             if p.returncode == 0:
451                 for line in p.stdout:
452                     (name,value) = re.match( '([^:]+):\\s+(.+)', line.rstrip() ).groups()
453                     if name == 'URL':
454                         self.url = value
455                     elif name == 'Repository Root':
456                         self.root = value
457                     elif name == 'Repository UUID':
458                         self.uuid = value
459                     elif name == 'Revision':
460                         self.rev = int( value )
461                     elif name == 'Last Changed Date':
462                         # strip chars in parens
463                         if value.find( ' (' ):
464                             self.date = value[0:value.find(' (')]
465                         else:
466                             self.date = value
467         except:
468             pass
469
470         i = self.url.rfind( '/' )
471         if i != -1 and i < len(self.url)-1:
472             self.branch = self.url[i+1:]
473
474         # official UUID behavior
475         if self.uuid == 'b64f7644-9d1e-0410-96f1-a4d463321fa5':
476             self.official = 1
477             m = re.match( '([^:]+)://([^/]+)/(.+)', self.url )
478             if m and re.match( 'tags/', m.group( 3 )):
479                 self.type = 'release'
480             else:
481                 self.type = 'developer'
482
483 ###############################################################################
484
485 ## Project object.
486 ## Contains manually updated version numbers consistent with HB releases
487 ## and other project metadata.
488 ##
489 class Project:
490     def __init__( self ):
491         if repo.type == 'unofficial':
492             self.name          = 'NoNameBrand'
493             self.acro_lower    = 'nnb'
494             self.acro_upper    = 'NNB'
495             self.url_website   = 'http://nonamebrand.com'
496             self.url_community = 'http://forum.nonamebrand.com'
497             self.url_irc       = 'irc://irc.freenode.net/nonamebrand'
498         else:
499             self.name          = 'HandBrake'
500             self.acro_lower    = 'hb'
501             self.acro_upper    = 'HB'
502             self.url_website   = 'http://handbrake.fr'
503             self.url_community = 'http://forum.handbrake.fr'
504             self.url_irc       = 'irc://irc.freenode.net/handbrake'
505
506         self.name_lower = self.name.lower()
507         self.name_upper = self.name.upper()
508
509         self.vmajor = 0
510         self.vminor = 9
511         self.vpoint = 4
512
513         appcastfmt = 'http://handbrake.fr/appcast%s.xml'
514
515         if repo.type == 'release':
516             self.version = '%d.%d.%d' % (self.vmajor,self.vminor,self.vpoint)
517             self.url_appcast = appcastfmt % ('')
518             self.build = time.strftime('%Y%m%d') + '00'
519             self.title = '%s %s (%s)' % (self.name,self.version,self.build)
520         elif repo.type == 'developer':
521             self.version = 'svn%d' % (repo.rev)
522             self.url_appcast = appcastfmt % ('_unstable')
523             self.build = time.strftime('%Y%m%d') + '01'
524             self.title = '%s svn%d (%s)' % (self.name,repo.rev,self.build)
525         else:
526             self.version = 'svn%d' % (repo.rev)
527             self.version = '%d.%d.%d' % (self.vmajor,self.vminor,self.vpoint)
528             self.url_appcast = appcastfmt % ('_unofficial')
529             self.build = time.strftime('%Y%m%d') + '99'
530             self.title = 'Unofficial svn%d (%s)' % (repo.rev,self.build)
531
532 ###############################################################################
533
534 ## Config object used to output gnu-make or gnu-m4 output.
535 ##
536 ## Use add() to add NAME/VALUE pairs suitable for both make/m4.
537 ## Use addBlank() to add a linefeed for both make/m4.
538 ## Use addMake() to add a make-specific line.
539 ## Use addM4() to add a m4-specific line.
540 ##
541 class Config:
542     def __init__( self ):
543         self._items = []
544
545     def add( self, name, value ):
546         self._items.append( (name,value) )
547
548     def addBlank( self ):
549         self._items.append( None )
550
551     def addComment( self, format, *args ):
552         self.addMake( '## ' + format % args )
553         self.addM4( 'dnl ' + format % args )
554
555     def addMake( self, line ):
556         self._items.append( ('?make',line) )
557
558     def addM4( self, line ):
559         self._items.append( ('?m4',line) )
560
561     def output( self, file, type ):
562         namelen = 0
563         for item in self._items:
564             if item == None or item[0].find( '?' ) == 0:
565                 continue
566             if len(item[0]) > namelen:
567                 namelen = len(item[0])
568         for item in self._items:
569             if item == None:
570                 if type == 'm4':
571                     file.write( 'dnl\n' )
572                 else:
573                     file.write( '\n' )
574                 continue
575             if item[0].find( '?' ) == 0:
576                 if item[0].find( type, 1 ) == 1:
577                     file.write( '%s\n' % (item[1]) )
578                 continue
579
580             if type == 'm4':
581                 self._outputM4( file, namelen, item[0], item[1] )
582             else:
583                 self._outputMake( file, namelen, item[0], item[1] )
584
585     def _outputMake( self, file, namelen, name, value ):
586         file.write( '%-*s = %s\n' % (namelen, name, value ))
587
588     def _outputM4( self, file, namelen, name, value ):
589         namelen += 7
590         name = '<<__%s>>,' % name.replace( '.', '_' )
591         file.write( 'define(%-*s  <<%s>>)dnl\n' % (namelen, name, value ))
592
593 ###############################################################################
594
595 ## create configure line, stripping arg --launch, quoting others
596 configure = []
597 for arg in sys.argv[1:]:
598     if arg == '--launch':
599         continue
600     configure.append( "'%s'" % (arg.replace("'", '%c%c%c%c%c' % (0x27,0x22,0x27,0x22,0x27))) )
601
602 ## create singletones
603 repo = Repository()
604 project = Project()
605 config  = Config()
606
607 config.addComment( 'generated by configure on %s', time.strftime( '%c' ))
608
609 config.addBlank()
610 config.add( 'CONF.args', ' '.join( configure ))
611
612 config.addBlank()
613 config.add( 'HB.title',         project.title )
614 config.add( 'HB.name',          project.name )
615 config.add( 'HB.name.lower',    project.name_lower )
616 config.add( 'HB.name.upper',    project.name_upper )
617 config.add( 'HB.acro.lower',    project.acro_lower )
618 config.add( 'HB.acro.upper',    project.acro_upper )
619
620 config.add( 'HB.url.website',   project.url_website )
621 config.add( 'HB.url.community', project.url_community )
622 config.add( 'HB.url.irc',       project.url_irc )
623 config.add( 'HB.url.appcast',   project.url_appcast )
624
625 config.add( 'HB.version.major',  project.vmajor )
626 config.add( 'HB.version.minor',  project.vminor )
627 config.add( 'HB.version.point',  project.vpoint )
628 config.add( 'HB.version',        project.version )
629 config.add( 'HB.version.hex',    '%04x%02x%02x%02x%06x' % (project.vmajor,project.vminor,project.vpoint,0,repo.rev) )
630
631 config.add( 'HB.build', project.build )
632
633 config.add( 'HB.repo.url',       repo.url )
634 config.add( 'HB.repo.root',      repo.root )
635 config.add( 'HB.repo.branch',    repo.branch )
636 config.add( 'HB.repo.uuid',      repo.uuid )
637 config.add( 'HB.repo.rev',       repo.rev )
638 config.add( 'HB.repo.date',      repo.date )
639 config.add( 'HB.repo.wcversion', repo.wcversion )
640 config.add( 'HB.repo.official',  repo.official )
641 config.add( 'HB.repo.type',      repo.type )
642
643 config.addBlank()
644 config.add( 'HOST.spec',    guessHost )
645 config.add( 'HOST.machine', guessHost.machine )
646 config.add( 'HOST.vendor',  guessHost.vendor )
647 config.add( 'HOST.system',  guessHost.system )
648 config.add( 'HOST.systemc', guessHost.systemc )
649 config.add( 'HOST.release', guessHost.release )
650 config.add( 'HOST.title',   '%s %s' % (guessHost.systemc,archMode.default) )
651 config.add( 'HOST.extra',   guessHost.extra )
652 config.add( 'HOST.ncpu',    computeNumCPU() )
653
654 config.addBlank()
655 config.add( 'BUILD.spec',    guessBuild )
656 config.add( 'BUILD.machine', guessBuild.machine )
657 config.add( 'BUILD.vendor',  guessBuild.vendor )
658 config.add( 'BUILD.system',  guessBuild.system )
659 config.add( 'BUILD.systemc', guessBuild.systemc )
660 config.add( 'BUILD.release', guessBuild.release )
661 config.add( 'BUILD.title',   '%s %s' % (guessBuild.systemc,archMode.mode) )
662 config.add( 'BUILD.extra',   guessBuild.extra )
663 config.add( 'BUILD.method',  'terminal' )
664 config.add( 'BUILD.cross',   guessBuild.cross )
665 config.add( 'BUILD.date',    time.strftime('%c') )
666 config.add( 'BUILD.arch',    archMode.mode )
667 config.add( 'BUILD.jobs',    computeNumCPU() )
668
669 config.addBlank()
670 config.add( 'CONF.method', options.conf_method )
671
672 config.addBlank()
673 config.add( 'BUILD/',   os.curdir + os.sep )
674 config.add( 'PROJECT/', project_dir + os.sep )
675
676 config.addBlank()
677 config.add( 'INSTALL.prefix', options.prefix )
678 config.add( 'INSTALL.prefix/', '$(INSTALL.prefix)/' )
679
680 config.addBlank()
681 config.add( 'FEATURE.xcode', 0 if options.disable_xcode else 1 )
682 config.add( 'FEATURE.gtk',   0 if options.disable_gtk   else 1 )
683
684 config.addMake( '' )
685 config.addMake( '## include main definitions' )
686 config.addMake( 'include $(PROJECT/)make/include/main.defs' )
687
688 config.addBlank()
689 for tool in tools.items:
690     tool.addToConfig( config )
691
692 config.addBlank()
693 config.add( 'GCC.archs', archMode.mode if guessBuild.cross else '' )
694 config.add( 'GCC.g', options.debug )
695 config.add( 'GCC.O', options.optimize )
696
697 if len(exports):
698     config.addBlank()
699     for nv in exports:
700         config.add( nv[0], nv[1] )
701
702 config.addMake( '' )
703 config.addMake( '## include (optional) customization file' )
704 config.addMake( '-include $(BUID/)GNUmakefile.custom' )
705
706 config.addMake( '' )
707 config.addMake( '## include main rules' )
708 config.addMake( 'include $(PROJECT/)make/include/main.rules' )
709
710 ###############################################################################
711
712 # generate make or m4 file
713 def generate( type ):
714     if type == 'make':
715         fname = 'GNUmakefile'
716     elif type == 'm4':
717         fname = os.path.join( 'project', project.name_lower + '.m4' )
718     else:
719         raise ValueError, 'unknown file type: ' + type
720
721     ftmp  = fname + '.tmp'
722
723     pdir = os.path.dirname( fname )
724     if pdir:
725         if not os.path.exists( pdir ):
726             os.makedirs( pdir )
727
728     try:
729         try:
730             outf( 'generating %s', fname )
731             file = open( ftmp, 'w' )
732             config.output( file, type )
733         finally:
734             try:
735                 file.close()
736             except:
737                 pass
738     except Exception, x:
739         try:
740             os.remove( ftmp )
741         except Exception, x:
742             pass
743         errf( 'failed writing to %s\n%s', ftmp, x )
744
745     try:
746         os.rename( ftmp, fname )
747     except Exception, x:
748         errf( 'failed writing to %s\n%s', fname, x )
749
750 ###############################################################################
751
752 if not options.launch:
753     generate( 'make' )
754     generate( 'm4' )
755     sys.exit( 0 )
756
757 ###############################################################################
758
759 if os.path.exists( options.launch_dir ):
760     if not options.launch_force:
761         errf( 'scratch directory already exists: %s', options.launch_dir )
762 else:
763     outf( 'creating %s', options.launch_dir )
764     os.makedirs( options.launch_dir )    
765
766 outf( 'chdir %s', options.launch_dir )
767 os.chdir( options.launch_dir )
768 generate( 'make' )
769 generate( 'm4' )
770
771 outf( 'opening %s', options.launch_log )
772 try:
773     log = open( options.launch_log, 'w' )
774 except Exception, x:
775     errf( 'open failure: %s', x )
776
777 cmd = '%s -j%d' % (makeTool.found,options.launch_jobs)
778 if options.launch_args:
779     cmd += ' ' + options.launch_args
780
781 ## record begin
782 timeBegin = time.time()
783 s = '###\n### TIME: %s\n### launch: %s\n###\n' % (time.asctime(),cmd)
784 stdout.write( s ); stdout.flush()
785 log.write( s ); log.flush()
786
787 ## launch/pipe
788 try:
789     pipe = subprocess.Popen( cmd, shell=True, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
790 except Exception, x:
791     errf( 'launch failure: %s', x )
792 for line in pipe.stdout:
793     if not options.launch_quiet:
794         stdout.write( line ); stdout.flush()
795     log.write( line ); log.flush()
796 pipe.wait()
797
798 ## record end
799 timeEnd = time.time()
800 elapsed = timeEnd - timeBegin
801 result = '%s (exit code %d)' % ('success' if pipe.returncode == 0 else 'failed',pipe.returncode)
802 s = '###\n### TIME: %s\n### finished: %.2f seconds\n### %s\n###\n' % (time.asctime(),elapsed,result)
803 stdout.write( s ); stdout.flush()
804 log.write( s ); log.flush()
805
806 log.close()
807 sys.exit( 0 )