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