wafsamba: add optional keep_underscore=True to SAMBA_LIBRARY()
[obnox/samba/samba-obnox.git] / buildtools / wafsamba / wafsamba.py
1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
3
4 import Build, os, sys, Options, Task, Utils, cc, TaskGen, fnmatch, re, shutil, Logs, Constants
5 from Configure import conf
6 from Logs import debug
7 from samba_utils import SUBST_VARS_RECURSIVE
8 TaskGen.task_gen.apply_verif = Utils.nada
9
10 # bring in the other samba modules
11 from samba_optimisation import *
12 from samba_utils import *
13 from samba_version import *
14 from samba_autoconf import *
15 from samba_patterns import *
16 from samba_pidl import *
17 from samba_autoproto import *
18 from samba_python import *
19 from samba_perl import *
20 from samba_deps import *
21 from samba_bundled import *
22 from samba_third_party import *
23 import samba_install
24 import samba_conftests
25 import samba_abi
26 import samba_headers
27 import tru64cc
28 import irixcc
29 import hpuxcc
30 import generic_cc
31 import samba_dist
32 import samba_wildcard
33 import stale_files
34 import symbols
35 import pkgconfig
36 import configure_file
37
38 # some systems have broken threading in python
39 if os.environ.get('WAF_NOTHREADS') == '1':
40     import nothreads
41
42 LIB_PATH="shared"
43
44 os.environ['PYTHONUNBUFFERED'] = '1'
45
46
47 if Constants.HEXVERSION < 0x105019:
48     Logs.error('''
49 Please use the version of waf that comes with Samba, not
50 a system installed version. See http://wiki.samba.org/index.php/Waf
51 for details.
52
53 Alternatively, please run ./configure and make as usual. That will
54 call the right version of waf.''')
55     sys.exit(1)
56
57
58 @conf
59 def SAMBA_BUILD_ENV(conf):
60     '''create the samba build environment'''
61     conf.env.BUILD_DIRECTORY = conf.blddir
62     mkdir_p(os.path.join(conf.blddir, LIB_PATH))
63     mkdir_p(os.path.join(conf.blddir, LIB_PATH, "private"))
64     mkdir_p(os.path.join(conf.blddir, "modules"))
65     mkdir_p(os.path.join(conf.blddir, 'python/samba/dcerpc'))
66     # this allows all of the bin/shared and bin/python targets
67     # to be expressed in terms of build directory paths
68     mkdir_p(os.path.join(conf.blddir, 'default'))
69     for (source, target) in [('shared', 'shared'), ('modules', 'modules'), ('python', 'python_modules')]:
70         link_target = os.path.join(conf.blddir, 'default/' + target)
71         if not os.path.lexists(link_target):
72             os.symlink('../' + source, link_target)
73
74     # get perl to put the blib files in the build directory
75     blib_bld = os.path.join(conf.blddir, 'default/pidl/blib')
76     blib_src = os.path.join(conf.srcdir, 'pidl/blib')
77     mkdir_p(blib_bld + '/man1')
78     mkdir_p(blib_bld + '/man3')
79     if os.path.islink(blib_src):
80         os.unlink(blib_src)
81     elif os.path.exists(blib_src):
82         shutil.rmtree(blib_src)
83
84
85 def ADD_INIT_FUNCTION(bld, subsystem, target, init_function):
86     '''add an init_function to the list for a subsystem'''
87     if init_function is None:
88         return
89     bld.ASSERT(subsystem is not None, "You must specify a subsystem for init_function '%s'" % init_function)
90     cache = LOCAL_CACHE(bld, 'INIT_FUNCTIONS')
91     if not subsystem in cache:
92         cache[subsystem] = []
93     cache[subsystem].append( { 'TARGET':target, 'INIT_FUNCTION':init_function } )
94 Build.BuildContext.ADD_INIT_FUNCTION = ADD_INIT_FUNCTION
95
96
97
98 #################################################################
99 def SAMBA_LIBRARY(bld, libname, source,
100                   deps='',
101                   public_deps='',
102                   includes='',
103                   public_headers=None,
104                   public_headers_install=True,
105                   header_path=None,
106                   pc_files=None,
107                   vnum=None,
108                   soname=None,
109                   cflags='',
110                   ldflags='',
111                   external_library=False,
112                   realname=None,
113                   keep_underscore=False,
114                   autoproto=None,
115                   autoproto_extra_source='',
116                   group='main',
117                   depends_on='',
118                   local_include=True,
119                   global_include=True,
120                   vars=None,
121                   subdir=None,
122                   install_path=None,
123                   install=True,
124                   pyembed=False,
125                   pyext=False,
126                   target_type='LIBRARY',
127                   bundled_extension=True,
128                   link_name=None,
129                   abi_directory=None,
130                   abi_match=None,
131                   hide_symbols=False,
132                   manpages=None,
133                   private_library=False,
134                   grouping_library=False,
135                   allow_undefined_symbols=False,
136                   allow_warnings=False,
137                   enabled=True):
138     '''define a Samba library'''
139
140     if LIB_MUST_BE_PRIVATE(bld, libname):
141         private_library=True
142
143     if not enabled:
144         SET_TARGET_TYPE(bld, libname, 'DISABLED')
145         return
146
147     source = bld.EXPAND_VARIABLES(source, vars=vars)
148     if subdir:
149         source = bld.SUBDIR(subdir, source)
150
151     # remember empty libraries, so we can strip the dependencies
152     if ((source == '') or (source == [])) and deps == '' and public_deps == '':
153         SET_TARGET_TYPE(bld, libname, 'EMPTY')
154         return
155
156     if BUILTIN_LIBRARY(bld, libname):
157         obj_target = libname
158     else:
159         obj_target = libname + '.objlist'
160
161     if group == 'libraries':
162         subsystem_group = 'main'
163     else:
164         subsystem_group = group
165
166     # first create a target for building the object files for this library
167     # by separating in this way, we avoid recompiling the C files
168     # separately for the install library and the build library
169     bld.SAMBA_SUBSYSTEM(obj_target,
170                         source         = source,
171                         deps           = deps,
172                         public_deps    = public_deps,
173                         includes       = includes,
174                         public_headers = public_headers,
175                         public_headers_install = public_headers_install,
176                         header_path    = header_path,
177                         cflags         = cflags,
178                         group          = subsystem_group,
179                         autoproto      = autoproto,
180                         autoproto_extra_source=autoproto_extra_source,
181                         depends_on     = depends_on,
182                         hide_symbols   = hide_symbols,
183                         allow_warnings = allow_warnings,
184                         pyembed        = pyembed,
185                         pyext          = pyext,
186                         local_include  = local_include,
187                         global_include = global_include)
188
189     if BUILTIN_LIBRARY(bld, libname):
190         return
191
192     if not SET_TARGET_TYPE(bld, libname, target_type):
193         return
194
195     # the library itself will depend on that object target
196     deps += ' ' + public_deps
197     deps = TO_LIST(deps)
198     deps.append(obj_target)
199
200     realname = bld.map_shlib_extension(realname, python=(target_type=='PYTHON'))
201     link_name = bld.map_shlib_extension(link_name, python=(target_type=='PYTHON'))
202
203     # we don't want any public libraries without version numbers
204     if (not private_library and target_type != 'PYTHON' and not realname):
205         if vnum is None and soname is None:
206             raise Utils.WafError("public library '%s' must have a vnum" %
207                     libname)
208         if pc_files is None:
209             raise Utils.WafError("public library '%s' must have pkg-config file" %
210                        libname)
211         if public_headers is None:
212             raise Utils.WafError("public library '%s' must have header files" %
213                        libname)
214
215     if target_type == 'PYTHON' or realname or not private_library:
216         if keep_underscore:
217             bundled_name = libname
218         else:
219             bundled_name = libname.replace('_', '-')
220     else:
221         bundled_name = PRIVATE_NAME(bld, libname, bundled_extension,
222             private_library)
223
224     ldflags = TO_LIST(ldflags)
225
226     features = 'cc cshlib symlink_lib install_lib'
227     if pyext:
228         features += ' pyext'
229     if pyembed:
230         features += ' pyembed'
231
232     if abi_directory:
233         features += ' abi_check'
234
235     vscript = None
236     if bld.env.HAVE_LD_VERSION_SCRIPT:
237         if private_library:
238             version = "%s_%s" % (Utils.g_module.APPNAME, Utils.g_module.VERSION)
239         elif vnum:
240             version = "%s_%s" % (libname, vnum)
241         else:
242             version = None
243         if version:
244             vscript = "%s.vscript" % libname
245             bld.ABI_VSCRIPT(libname, abi_directory, version, vscript,
246                             abi_match)
247             fullname = apply_pattern(bundled_name, bld.env.shlib_PATTERN)
248             fullpath = bld.path.find_or_declare(fullname)
249             vscriptpath = bld.path.find_or_declare(vscript)
250             if not fullpath:
251                 raise Utils.WafError("unable to find fullpath for %s" % fullname)
252             if not vscriptpath:
253                 raise Utils.WafError("unable to find vscript path for %s" % vscript)
254             bld.add_manual_dependency(fullpath, vscriptpath)
255             if Options.is_install:
256                 # also make the .inst file depend on the vscript
257                 instname = apply_pattern(bundled_name + '.inst', bld.env.shlib_PATTERN)
258                 bld.add_manual_dependency(bld.path.find_or_declare(instname), bld.path.find_or_declare(vscript))
259             vscript = os.path.join(bld.path.abspath(bld.env), vscript)
260
261     bld.SET_BUILD_GROUP(group)
262     t = bld(
263         features        = features,
264         source          = [],
265         target          = bundled_name,
266         depends_on      = depends_on,
267         samba_ldflags   = ldflags,
268         samba_deps      = deps,
269         samba_includes  = includes,
270         version_script  = vscript,
271         local_include   = local_include,
272         global_include  = global_include,
273         vnum            = vnum,
274         soname          = soname,
275         install_path    = None,
276         samba_inst_path = install_path,
277         name            = libname,
278         samba_realname  = realname,
279         samba_install   = install,
280         abi_directory   = "%s/%s" % (bld.path.abspath(), abi_directory),
281         abi_match       = abi_match,
282         private_library = private_library,
283         grouping_library=grouping_library,
284         allow_undefined_symbols=allow_undefined_symbols
285         )
286
287     if realname and not link_name:
288         link_name = 'shared/%s' % realname
289
290     if link_name:
291         t.link_name = link_name
292
293     if pc_files is not None and not private_library:
294         bld.PKG_CONFIG_FILES(pc_files, vnum=vnum)
295
296     if (manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and
297         bld.env['XSLTPROC_MANPAGES']):
298         bld.MANPAGES(manpages, install)
299
300
301 Build.BuildContext.SAMBA_LIBRARY = SAMBA_LIBRARY
302
303
304 #################################################################
305 def SAMBA_BINARY(bld, binname, source,
306                  deps='',
307                  includes='',
308                  public_headers=None,
309                  header_path=None,
310                  modules=None,
311                  ldflags=None,
312                  cflags='',
313                  autoproto=None,
314                  use_hostcc=False,
315                  use_global_deps=True,
316                  compiler=None,
317                  group='main',
318                  manpages=None,
319                  local_include=True,
320                  global_include=True,
321                  subsystem_name=None,
322                  pyembed=False,
323                  vars=None,
324                  subdir=None,
325                  install=True,
326                  install_path=None,
327                  enabled=True):
328     '''define a Samba binary'''
329
330     if not enabled:
331         SET_TARGET_TYPE(bld, binname, 'DISABLED')
332         return
333
334     if not SET_TARGET_TYPE(bld, binname, 'BINARY'):
335         return
336
337     features = 'cc cprogram symlink_bin install_bin'
338     if pyembed:
339         features += ' pyembed'
340
341     obj_target = binname + '.objlist'
342
343     source = bld.EXPAND_VARIABLES(source, vars=vars)
344     if subdir:
345         source = bld.SUBDIR(subdir, source)
346     source = unique_list(TO_LIST(source))
347
348     if group == 'binaries':
349         subsystem_group = 'main'
350     else:
351         subsystem_group = group
352
353     # only specify PIE flags for binaries
354     pie_cflags = cflags
355     pie_ldflags = TO_LIST(ldflags)
356     if bld.env['ENABLE_PIE'] is True:
357         pie_cflags += ' -fPIE'
358         pie_ldflags.extend(TO_LIST('-pie'))
359     if bld.env['ENABLE_RELRO'] is True:
360         pie_ldflags.extend(TO_LIST('-Wl,-z,relro,-z,now'))
361
362     # first create a target for building the object files for this binary
363     # by separating in this way, we avoid recompiling the C files
364     # separately for the install binary and the build binary
365     bld.SAMBA_SUBSYSTEM(obj_target,
366                         source         = source,
367                         deps           = deps,
368                         includes       = includes,
369                         cflags         = pie_cflags,
370                         group          = subsystem_group,
371                         autoproto      = autoproto,
372                         subsystem_name = subsystem_name,
373                         local_include  = local_include,
374                         global_include = global_include,
375                         use_hostcc     = use_hostcc,
376                         pyext          = pyembed,
377                         use_global_deps= use_global_deps)
378
379     bld.SET_BUILD_GROUP(group)
380
381     # the binary itself will depend on that object target
382     deps = TO_LIST(deps)
383     deps.append(obj_target)
384
385     t = bld(
386         features       = features,
387         source         = [],
388         target         = binname,
389         samba_deps     = deps,
390         samba_includes = includes,
391         local_include  = local_include,
392         global_include = global_include,
393         samba_modules  = modules,
394         top            = True,
395         samba_subsystem= subsystem_name,
396         install_path   = None,
397         samba_inst_path= install_path,
398         samba_install  = install,
399         samba_ldflags  = pie_ldflags
400         )
401
402     if manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and bld.env['XSLTPROC_MANPAGES']:
403         bld.MANPAGES(manpages, install)
404
405 Build.BuildContext.SAMBA_BINARY = SAMBA_BINARY
406
407
408 #################################################################
409 def SAMBA_MODULE(bld, modname, source,
410                  deps='',
411                  includes='',
412                  subsystem=None,
413                  init_function=None,
414                  module_init_name='samba_init_module',
415                  autoproto=None,
416                  autoproto_extra_source='',
417                  cflags='',
418                  internal_module=True,
419                  local_include=True,
420                  global_include=True,
421                  vars=None,
422                  subdir=None,
423                  enabled=True,
424                  pyembed=False,
425                  manpages=None,
426                  allow_undefined_symbols=False,
427                  allow_warnings=False
428                  ):
429     '''define a Samba module.'''
430
431     source = bld.EXPAND_VARIABLES(source, vars=vars)
432     if subdir:
433         source = bld.SUBDIR(subdir, source)
434
435     if internal_module or BUILTIN_LIBRARY(bld, modname):
436         # Do not create modules for disabled subsystems
437         if subsystem and GET_TARGET_TYPE(bld, subsystem) == 'DISABLED':
438             return
439         bld.SAMBA_SUBSYSTEM(modname, source,
440                     deps=deps,
441                     includes=includes,
442                     autoproto=autoproto,
443                     autoproto_extra_source=autoproto_extra_source,
444                     cflags=cflags,
445                     local_include=local_include,
446                     global_include=global_include,
447                     allow_warnings=allow_warnings,
448                     enabled=enabled)
449
450         bld.ADD_INIT_FUNCTION(subsystem, modname, init_function)
451         return
452
453     if not enabled:
454         SET_TARGET_TYPE(bld, modname, 'DISABLED')
455         return
456
457     # Do not create modules for disabled subsystems
458     if subsystem and GET_TARGET_TYPE(bld, subsystem) == 'DISABLED':
459         return
460
461     obj_target = modname + '.objlist'
462
463     realname = modname
464     if subsystem is not None:
465         deps += ' ' + subsystem
466         while realname.startswith("lib"+subsystem+"_"):
467             realname = realname[len("lib"+subsystem+"_"):]
468         while realname.startswith(subsystem+"_"):
469             realname = realname[len(subsystem+"_"):]
470
471     realname = bld.make_libname(realname)
472     while realname.startswith("lib"):
473         realname = realname[len("lib"):]
474
475     build_link_name = "modules/%s/%s" % (subsystem, realname)
476
477     if init_function:
478         cflags += " -D%s=%s" % (init_function, module_init_name)
479
480     bld.SAMBA_LIBRARY(modname,
481                       source,
482                       deps=deps,
483                       includes=includes,
484                       cflags=cflags,
485                       realname = realname,
486                       autoproto = autoproto,
487                       local_include=local_include,
488                       global_include=global_include,
489                       vars=vars,
490                       link_name=build_link_name,
491                       install_path="${MODULESDIR}/%s" % subsystem,
492                       pyembed=pyembed,
493                       manpages=manpages,
494                       allow_undefined_symbols=allow_undefined_symbols,
495                       allow_warnings=allow_warnings
496                       )
497
498
499 Build.BuildContext.SAMBA_MODULE = SAMBA_MODULE
500
501
502 #################################################################
503 def SAMBA_SUBSYSTEM(bld, modname, source,
504                     deps='',
505                     public_deps='',
506                     includes='',
507                     public_headers=None,
508                     public_headers_install=True,
509                     header_path=None,
510                     cflags='',
511                     cflags_end=None,
512                     group='main',
513                     init_function_sentinel=None,
514                     autoproto=None,
515                     autoproto_extra_source='',
516                     depends_on='',
517                     local_include=True,
518                     local_include_first=True,
519                     global_include=True,
520                     subsystem_name=None,
521                     enabled=True,
522                     use_hostcc=False,
523                     use_global_deps=True,
524                     vars=None,
525                     subdir=None,
526                     hide_symbols=False,
527                     allow_warnings=False,
528                     pyext=False,
529                     pyembed=False):
530     '''define a Samba subsystem'''
531
532     if not enabled:
533         SET_TARGET_TYPE(bld, modname, 'DISABLED')
534         return
535
536     # remember empty subsystems, so we can strip the dependencies
537     if ((source == '') or (source == [])) and deps == '' and public_deps == '':
538         SET_TARGET_TYPE(bld, modname, 'EMPTY')
539         return
540
541     if not SET_TARGET_TYPE(bld, modname, 'SUBSYSTEM'):
542         return
543
544     source = bld.EXPAND_VARIABLES(source, vars=vars)
545     if subdir:
546         source = bld.SUBDIR(subdir, source)
547     source = unique_list(TO_LIST(source))
548
549     deps += ' ' + public_deps
550
551     bld.SET_BUILD_GROUP(group)
552
553     features = 'cc'
554     if pyext:
555         features += ' pyext'
556     if pyembed:
557         features += ' pyembed'
558
559     t = bld(
560         features       = features,
561         source         = source,
562         target         = modname,
563         samba_cflags   = CURRENT_CFLAGS(bld, modname, cflags,
564                                         allow_warnings=allow_warnings,
565                                         hide_symbols=hide_symbols),
566         depends_on     = depends_on,
567         samba_deps     = TO_LIST(deps),
568         samba_includes = includes,
569         local_include  = local_include,
570         local_include_first  = local_include_first,
571         global_include = global_include,
572         samba_subsystem= subsystem_name,
573         samba_use_hostcc = use_hostcc,
574         samba_use_global_deps = use_global_deps,
575         )
576
577     if cflags_end is not None:
578         t.samba_cflags.extend(TO_LIST(cflags_end))
579
580     if autoproto is not None:
581         bld.SAMBA_AUTOPROTO(autoproto, source + TO_LIST(autoproto_extra_source))
582     if public_headers is not None:
583         bld.PUBLIC_HEADERS(public_headers, header_path=header_path,
584                            public_headers_install=public_headers_install)
585     return t
586
587
588 Build.BuildContext.SAMBA_SUBSYSTEM = SAMBA_SUBSYSTEM
589
590
591 def SAMBA_GENERATOR(bld, name, rule, source='', target='',
592                     group='generators', enabled=True,
593                     public_headers=None,
594                     public_headers_install=True,
595                     header_path=None,
596                     vars=None,
597                     dep_vars=[],
598                     always=False):
599     '''A generic source generator target'''
600
601     if not SET_TARGET_TYPE(bld, name, 'GENERATOR'):
602         return
603
604     if not enabled:
605         return
606
607     dep_vars.append('ruledeps')
608     dep_vars.append('SAMBA_GENERATOR_VARS')
609
610     bld.SET_BUILD_GROUP(group)
611     t = bld(
612         rule=rule,
613         source=bld.EXPAND_VARIABLES(source, vars=vars),
614         target=target,
615         shell=isinstance(rule, str),
616         on_results=True,
617         before='cc',
618         ext_out='.c',
619         samba_type='GENERATOR',
620         dep_vars = dep_vars,
621         name=name)
622
623     if vars is None:
624         vars = {}
625     t.env.SAMBA_GENERATOR_VARS = vars
626
627     if always:
628         t.always = True
629
630     if public_headers is not None:
631         bld.PUBLIC_HEADERS(public_headers, header_path=header_path,
632                            public_headers_install=public_headers_install)
633     return t
634 Build.BuildContext.SAMBA_GENERATOR = SAMBA_GENERATOR
635
636
637
638 @runonce
639 def SETUP_BUILD_GROUPS(bld):
640     '''setup build groups used to ensure that the different build
641     phases happen consecutively'''
642     bld.p_ln = bld.srcnode # we do want to see all targets!
643     bld.env['USING_BUILD_GROUPS'] = True
644     bld.add_group('setup')
645     bld.add_group('build_compiler_source')
646     bld.add_group('vscripts')
647     bld.add_group('base_libraries')
648     bld.add_group('generators')
649     bld.add_group('compiler_prototypes')
650     bld.add_group('compiler_libraries')
651     bld.add_group('build_compilers')
652     bld.add_group('build_source')
653     bld.add_group('prototypes')
654     bld.add_group('headers')
655     bld.add_group('main')
656     bld.add_group('symbolcheck')
657     bld.add_group('syslibcheck')
658     bld.add_group('final')
659 Build.BuildContext.SETUP_BUILD_GROUPS = SETUP_BUILD_GROUPS
660
661
662 def SET_BUILD_GROUP(bld, group):
663     '''set the current build group'''
664     if not 'USING_BUILD_GROUPS' in bld.env:
665         return
666     bld.set_group(group)
667 Build.BuildContext.SET_BUILD_GROUP = SET_BUILD_GROUP
668
669
670
671 @conf
672 def ENABLE_TIMESTAMP_DEPENDENCIES(conf):
673     """use timestamps instead of file contents for deps
674     this currently doesn't work"""
675     def h_file(filename):
676         import stat
677         st = os.stat(filename)
678         if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
679         m = Utils.md5()
680         m.update(str(st.st_mtime))
681         m.update(str(st.st_size))
682         m.update(filename)
683         return m.digest()
684     Utils.h_file = h_file
685
686
687 def SAMBA_SCRIPT(bld, name, pattern, installdir, installname=None):
688     '''used to copy scripts from the source tree into the build directory
689        for use by selftest'''
690
691     source = bld.path.ant_glob(pattern)
692
693     bld.SET_BUILD_GROUP('build_source')
694     for s in TO_LIST(source):
695         iname = s
696         if installname is not None:
697             iname = installname
698         target = os.path.join(installdir, iname)
699         tgtdir = os.path.dirname(os.path.join(bld.srcnode.abspath(bld.env), '..', target))
700         mkdir_p(tgtdir)
701         link_src = os.path.normpath(os.path.join(bld.curdir, s))
702         link_dst = os.path.join(tgtdir, os.path.basename(iname))
703         if os.path.islink(link_dst) and os.readlink(link_dst) == link_src:
704             continue
705         if os.path.exists(link_dst):
706             os.unlink(link_dst)
707         Logs.info("symlink: %s -> %s/%s" % (s, installdir, iname))
708         os.symlink(link_src, link_dst)
709 Build.BuildContext.SAMBA_SCRIPT = SAMBA_SCRIPT
710
711
712 def copy_and_fix_python_path(task):
713     pattern='sys.path.insert(0, "bin/python")'
714     if task.env["PYTHONARCHDIR"] in sys.path and task.env["PYTHONDIR"] in sys.path:
715         replacement = ""
716     elif task.env["PYTHONARCHDIR"] == task.env["PYTHONDIR"]:
717         replacement="""sys.path.insert(0, "%s")""" % task.env["PYTHONDIR"]
718     else:
719         replacement="""sys.path.insert(0, "%s")
720 sys.path.insert(1, "%s")""" % (task.env["PYTHONARCHDIR"], task.env["PYTHONDIR"])
721
722     if task.env["PYTHON"][0] == "/":
723         replacement_shebang = "#!%s\n" % task.env["PYTHON"]
724     else:
725         replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PYTHON"]
726
727     installed_location=task.outputs[0].bldpath(task.env)
728     source_file = open(task.inputs[0].srcpath(task.env))
729     installed_file = open(installed_location, 'w')
730     lineno = 0
731     for line in source_file:
732         newline = line
733         if (lineno == 0 and task.env["PYTHON_SPECIFIED"] is True and
734                 line[:2] == "#!"):
735             newline = replacement_shebang
736         elif pattern in line:
737             newline = line.replace(pattern, replacement)
738         installed_file.write(newline)
739         lineno = lineno + 1
740     installed_file.close()
741     os.chmod(installed_location, 0755)
742     return 0
743
744 def copy_and_fix_perl_path(task):
745     pattern='use lib "$RealBin/lib";'
746
747     replacement = ""
748     if not task.env["PERL_LIB_INSTALL_DIR"] in task.env["PERL_INC"]:
749          replacement = 'use lib "%s";' % task.env["PERL_LIB_INSTALL_DIR"]
750
751     if task.env["PERL"][0] == "/":
752         replacement_shebang = "#!%s\n" % task.env["PERL"]
753     else:
754         replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PERL"]
755
756     installed_location=task.outputs[0].bldpath(task.env)
757     source_file = open(task.inputs[0].srcpath(task.env))
758     installed_file = open(installed_location, 'w')
759     lineno = 0
760     for line in source_file:
761         newline = line
762         if lineno == 0 and task.env["PERL_SPECIFIED"] == True and line[:2] == "#!":
763             newline = replacement_shebang
764         elif pattern in line:
765             newline = line.replace(pattern, replacement)
766         installed_file.write(newline)
767         lineno = lineno + 1
768     installed_file.close()
769     os.chmod(installed_location, 0755)
770     return 0
771
772
773 def install_file(bld, destdir, file, chmod=MODE_644, flat=False,
774                  python_fixup=False, perl_fixup=False,
775                  destname=None, base_name=None):
776     '''install a file'''
777     destdir = bld.EXPAND_VARIABLES(destdir)
778     if not destname:
779         destname = file
780         if flat:
781             destname = os.path.basename(destname)
782     dest = os.path.join(destdir, destname)
783     if python_fixup:
784         # fix the path python will use to find Samba modules
785         inst_file = file + '.inst'
786         bld.SAMBA_GENERATOR('python_%s' % destname,
787                             rule=copy_and_fix_python_path,
788                             dep_vars=["PYTHON","PYTHON_SPECIFIED","PYTHONDIR","PYTHONARCHDIR"],
789                             source=file,
790                             target=inst_file)
791         file = inst_file
792     if perl_fixup:
793         # fix the path perl will use to find Samba modules
794         inst_file = file + '.inst'
795         bld.SAMBA_GENERATOR('perl_%s' % destname,
796                             rule=copy_and_fix_perl_path,
797                             dep_vars=["PERL","PERL_SPECIFIED","PERL_LIB_INSTALL_DIR"],
798                             source=file,
799                             target=inst_file)
800         file = inst_file
801     if base_name:
802         file = os.path.join(base_name, file)
803     bld.install_as(dest, file, chmod=chmod)
804
805
806 def INSTALL_FILES(bld, destdir, files, chmod=MODE_644, flat=False,
807                   python_fixup=False, perl_fixup=False,
808                   destname=None, base_name=None):
809     '''install a set of files'''
810     for f in TO_LIST(files):
811         install_file(bld, destdir, f, chmod=chmod, flat=flat,
812                      python_fixup=python_fixup, perl_fixup=perl_fixup,
813                      destname=destname, base_name=base_name)
814 Build.BuildContext.INSTALL_FILES = INSTALL_FILES
815
816
817 def INSTALL_WILDCARD(bld, destdir, pattern, chmod=MODE_644, flat=False,
818                      python_fixup=False, exclude=None, trim_path=None):
819     '''install a set of files matching a wildcard pattern'''
820     files=TO_LIST(bld.path.ant_glob(pattern))
821     if trim_path:
822         files2 = []
823         for f in files:
824             files2.append(os_path_relpath(f, trim_path))
825         files = files2
826
827     if exclude:
828         for f in files[:]:
829             if fnmatch.fnmatch(f, exclude):
830                 files.remove(f)
831     INSTALL_FILES(bld, destdir, files, chmod=chmod, flat=flat,
832                   python_fixup=python_fixup, base_name=trim_path)
833 Build.BuildContext.INSTALL_WILDCARD = INSTALL_WILDCARD
834
835
836 def INSTALL_DIRS(bld, destdir, dirs):
837     '''install a set of directories'''
838     destdir = bld.EXPAND_VARIABLES(destdir)
839     dirs = bld.EXPAND_VARIABLES(dirs)
840     for d in TO_LIST(dirs):
841         bld.install_dir(os.path.join(destdir, d))
842 Build.BuildContext.INSTALL_DIRS = INSTALL_DIRS
843
844
845 def MANPAGES(bld, manpages, install):
846     '''build and install manual pages'''
847     bld.env.MAN_XSL = 'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl'
848     for m in manpages.split():
849         source = m + '.xml'
850         bld.SAMBA_GENERATOR(m,
851                             source=source,
852                             target=m,
853                             group='final',
854                             rule='${XSLTPROC} --xinclude -o ${TGT} --nonet ${MAN_XSL} ${SRC}'
855                             )
856         if install:
857             bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True)
858 Build.BuildContext.MANPAGES = MANPAGES
859
860 def SAMBAMANPAGES(bld, manpages, extra_source=None):
861     '''build and install manual pages'''
862     bld.env.SAMBA_EXPAND_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/expand-sambadoc.xsl'
863     bld.env.SAMBA_MAN_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/man.xsl'
864     bld.env.SAMBA_CATALOGS = 'file:///etc/xml/catalog file:///usr/local/share/xml/catalog file://' + bld.srcnode.abspath() + '/bin/default/docs-xml/build/catalog.xml'
865
866     for m in manpages.split():
867         source = m + '.xml'
868         if extra_source is not None:
869             source = [source, extra_source]
870         bld.SAMBA_GENERATOR(m,
871                             source=source,
872                             target=m,
873                             group='final',
874                             rule='''XML_CATALOG_FILES="${SAMBA_CATALOGS}"
875                                     export XML_CATALOG_FILES
876                                     ${XSLTPROC} --xinclude --stringparam noreference 0 -o ${TGT}.xml --nonet ${SAMBA_EXPAND_XSL} ${SRC[0].abspath(env)}
877                                     ${XSLTPROC} --nonet -o ${TGT} ${SAMBA_MAN_XSL} ${TGT}.xml'''
878                             )
879         bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True)
880 Build.BuildContext.SAMBAMANPAGES = SAMBAMANPAGES
881
882 #############################################################
883 # give a nicer display when building different types of files
884 def progress_display(self, msg, fname):
885     col1 = Logs.colors(self.color)
886     col2 = Logs.colors.NORMAL
887     total = self.position[1]
888     n = len(str(total))
889     fs = '[%%%dd/%%%dd] %s %%s%%s%%s\n' % (n, n, msg)
890     return fs % (self.position[0], self.position[1], col1, fname, col2)
891
892 def link_display(self):
893     if Options.options.progress_bar != 0:
894         return Task.Task.old_display(self)
895     fname = self.outputs[0].bldpath(self.env)
896     return progress_display(self, 'Linking', fname)
897 Task.TaskBase.classes['cc_link'].display = link_display
898
899 def samba_display(self):
900     if Options.options.progress_bar != 0:
901         return Task.Task.old_display(self)
902
903     targets    = LOCAL_CACHE(self, 'TARGET_TYPE')
904     if self.name in targets:
905         target_type = targets[self.name]
906         type_map = { 'GENERATOR' : 'Generating',
907                      'PROTOTYPE' : 'Generating'
908                      }
909         if target_type in type_map:
910             return progress_display(self, type_map[target_type], self.name)
911
912     if len(self.inputs) == 0:
913         return Task.Task.old_display(self)
914
915     fname = self.inputs[0].bldpath(self.env)
916     if fname[0:3] == '../':
917         fname = fname[3:]
918     ext_loc = fname.rfind('.')
919     if ext_loc == -1:
920         return Task.Task.old_display(self)
921     ext = fname[ext_loc:]
922
923     ext_map = { '.idl' : 'Compiling IDL',
924                 '.et'  : 'Compiling ERRTABLE',
925                 '.asn1': 'Compiling ASN1',
926                 '.c'   : 'Compiling' }
927     if ext in ext_map:
928         return progress_display(self, ext_map[ext], fname)
929     return Task.Task.old_display(self)
930
931 Task.TaskBase.classes['Task'].old_display = Task.TaskBase.classes['Task'].display
932 Task.TaskBase.classes['Task'].display = samba_display
933
934
935 @after('apply_link')
936 @feature('cshlib')
937 def apply_bundle_remove_dynamiclib_patch(self):
938     if self.env['MACBUNDLE'] or getattr(self,'mac_bundle',False):
939         if not getattr(self,'vnum',None):
940             try:
941                 self.env['LINKFLAGS'].remove('-dynamiclib')
942                 self.env['LINKFLAGS'].remove('-single_module')
943             except ValueError:
944                 pass