0587f525aff376262e8f34b4f264c4e72617d0d3
[samba.git] / buildtools / wafsamba / samba_utils.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 errno
5 import os, sys, re, fnmatch, shlex, inspect
6 from optparse import SUPPRESS_HELP
7 from waflib import Build, Options, Utils, Task, Logs, Configure, Errors, Context
8 from waflib import Scripting
9 from waflib.TaskGen import feature, before, after
10 from waflib.Configure import ConfigurationContext
11 from waflib.Logs import debug
12 from waflib import ConfigSet
13 from waflib.Build import CACHE_SUFFIX
14
15 # TODO: make this a --option
16 LIB_PATH="shared"
17
18
19 PY3 = sys.version_info[0] == 3
20
21 if PY3:
22
23     # helper function to get a string from a variable that maybe 'str' or
24     # 'bytes' if 'bytes' then it is decoded using 'utf8'. If 'str' is passed
25     # it is returned unchanged
26     # Using this function is PY2/PY3 code should ensure in most cases
27     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
28     # decodes the variable (see PY2 implementation of this function below)
29     def get_string(bytesorstring):
30         tmp = bytesorstring
31         if isinstance(bytesorstring, bytes):
32             tmp = bytesorstring.decode('utf8')
33         elif not isinstance(bytesorstring, str):
34             raise ValueError('Expected byte of string for %s:%s' % (type(bytesorstring), bytesorstring))
35         return tmp
36
37 else:
38
39     # Helper function to return string.
40     # if 'str' or 'unicode' passed in they are returned unchanged
41     # otherwise an exception is generated
42     # Using this function is PY2/PY3 code should ensure in most cases
43     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
44     # decodes the variable (see PY3 implementation of this function above)
45     def get_string(bytesorstring):
46         tmp = bytesorstring
47         if not(isinstance(bytesorstring, str) or isinstance(bytesorstring, unicode)):
48             raise ValueError('Expected str or unicode for %s:%s' % (type(bytesorstring), bytesorstring))
49         return tmp
50
51 # sigh, python octal constants are a mess
52 MODE_644 = int('644', 8)
53 MODE_744 = int('744', 8)
54 MODE_755 = int('755', 8)
55 MODE_777 = int('777', 8)
56
57 def conf(f):
58     # override in order to propagate the argument "mandatory"
59     def fun(*k, **kw):
60         mandatory = True
61         if 'mandatory' in kw:
62             mandatory = kw['mandatory']
63             del kw['mandatory']
64
65         try:
66             return f(*k, **kw)
67         except Errors.ConfigurationError:
68             if mandatory:
69                 raise
70
71     fun.__name__ = f.__name__
72     if 'mandatory' in inspect.getsource(f):
73         fun = f
74
75     setattr(Configure.ConfigurationContext, f.__name__, fun)
76     setattr(Build.BuildContext, f.__name__, fun)
77     return f
78 Configure.conf = conf
79 Configure.conftest = conf
80
81 @conf
82 def SET_TARGET_TYPE(ctx, target, value):
83     '''set the target type of a target'''
84     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
85     if target in cache and cache[target] != 'EMPTY':
86         Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.path.abspath(), value, cache[target]))
87         sys.exit(1)
88     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
89     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.path.abspath()))
90     return True
91
92
93 def GET_TARGET_TYPE(ctx, target):
94     '''get target type from cache'''
95     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
96     if not target in cache:
97         return None
98     return cache[target]
99
100
101 def ADD_LD_LIBRARY_PATH(path):
102     '''add something to LD_LIBRARY_PATH'''
103     if 'LD_LIBRARY_PATH' in os.environ:
104         oldpath = os.environ['LD_LIBRARY_PATH']
105     else:
106         oldpath = ''
107     newpath = oldpath.split(':')
108     if not path in newpath:
109         newpath.append(path)
110         os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
111
112
113 def needs_private_lib(bld, target):
114     '''return True if a target links to a private library'''
115     for lib in getattr(target, "final_libs", []):
116         t = bld.get_tgen_by_name(lib)
117         if t and getattr(t, 'private_library', False):
118             return True
119     return False
120
121
122 def install_rpath(target):
123     '''the rpath value for installation'''
124     bld = target.bld
125     bld.env['RPATH'] = []
126     ret = set()
127     if bld.env.RPATH_ON_INSTALL:
128         ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
129     if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
130         ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
131     return list(ret)
132
133
134 def build_rpath(bld):
135     '''the rpath value for build'''
136     rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
137     bld.env['RPATH'] = []
138     if bld.env.RPATH_ON_BUILD:
139         return rpaths
140     for rpath in rpaths:
141         ADD_LD_LIBRARY_PATH(rpath)
142     return []
143
144
145 @conf
146 def LOCAL_CACHE(ctx, name):
147     '''return a named build cache dictionary, used to store
148        state inside other functions'''
149     if name in ctx.env:
150         return ctx.env[name]
151     ctx.env[name] = {}
152     return ctx.env[name]
153
154
155 @conf
156 def LOCAL_CACHE_SET(ctx, cachename, key, value):
157     '''set a value in a local cache'''
158     cache = LOCAL_CACHE(ctx, cachename)
159     cache[key] = value
160
161
162 @conf
163 def ASSERT(ctx, expression, msg):
164     '''a build assert call'''
165     if not expression:
166         raise Errors.WafError("ERROR: %s\n" % msg)
167 Build.BuildContext.ASSERT = ASSERT
168
169
170 def SUBDIR(bld, subdir, list):
171     '''create a list of files by pre-pending each with a subdir name'''
172     ret = ''
173     for l in TO_LIST(list):
174         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
175     return ret
176 Build.BuildContext.SUBDIR = SUBDIR
177
178
179 def dict_concat(d1, d2):
180     '''concatenate two dictionaries d1 += d2'''
181     for t in d2:
182         if t not in d1:
183             d1[t] = d2[t]
184
185 def ADD_COMMAND(opt, name, function):
186     '''add a new top level command to waf'''
187     Context.g_module.__dict__[name] = function
188     opt.name = function
189 Options.OptionsContext.ADD_COMMAND = ADD_COMMAND
190
191
192 @feature('c', 'cc', 'cshlib', 'cprogram')
193 @before('apply_core','exec_rule')
194 def process_depends_on(self):
195     '''The new depends_on attribute for build rules
196        allow us to specify a dependency on output from
197        a source generation rule'''
198     if getattr(self , 'depends_on', None):
199         lst = self.to_list(self.depends_on)
200         for x in lst:
201             y = self.bld.get_tgen_by_name(x)
202             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
203             y.post()
204             if getattr(y, 'more_includes', None):
205                   self.includes += " " + y.more_includes
206
207
208 def unique_list(seq):
209     '''return a uniquified list in the same order as the existing list'''
210     seen = {}
211     result = []
212     for item in seq:
213         if item in seen: continue
214         seen[item] = True
215         result.append(item)
216     return result
217
218
219 def TO_LIST(str, delimiter=None):
220     '''Split a list, preserving quoted strings and existing lists'''
221     if str is None:
222         return []
223     if isinstance(str, list):
224         # we need to return a new independent list...
225         return list(str)
226     if len(str) == 0:
227         return []
228     lst = str.split(delimiter)
229     # the string may have had quotes in it, now we
230     # check if we did have quotes, and use the slower shlex
231     # if we need to
232     for e in lst:
233         if e[0] == '"':
234             return shlex.split(str)
235     return lst
236
237
238 def subst_vars_error(string, env):
239     '''substitute vars, throw an error if a variable is not defined'''
240     lst = re.split('(\$\{\w+\})', string)
241     out = []
242     for v in lst:
243         if re.match('\$\{\w+\}', v):
244             vname = v[2:-1]
245             if not vname in env:
246                 raise KeyError("Failed to find variable %s in %s in env %s <%s>" % (vname, string, env.__class__, str(env)))
247             v = env[vname]
248             if isinstance(v, list):
249                 v = ' '.join(v)
250         out.append(v)
251     return ''.join(out)
252
253
254 @conf
255 def SUBST_ENV_VAR(ctx, varname):
256     '''Substitute an environment variable for any embedded variables'''
257     return subst_vars_error(ctx.env[varname], ctx.env)
258 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
259
260
261 def recursive_dirlist(dir, relbase, pattern=None):
262     '''recursive directory list'''
263     ret = []
264     for f in os.listdir(dir):
265         f2 = dir + '/' + f
266         if os.path.isdir(f2):
267             ret.extend(recursive_dirlist(f2, relbase))
268         else:
269             if pattern and not fnmatch.fnmatch(f, pattern):
270                 continue
271             ret.append(os.path.relpath(f2, relbase))
272     return ret
273
274
275 def symlink(src, dst, force=True):
276     """Can create symlink by force"""
277     try:
278         os.symlink(src, dst)
279     except OSError as exc:
280         if exc.errno == errno.EEXIST and force:
281             os.remove(dst)
282             os.symlink(src, dst)
283         else:
284             raise
285
286
287 def mkdir_p(dir):
288     '''like mkdir -p'''
289     if not dir:
290         return
291     if dir.endswith("/"):
292         mkdir_p(dir[:-1])
293         return
294     if os.path.isdir(dir):
295         return
296     mkdir_p(os.path.dirname(dir))
297     os.mkdir(dir)
298
299
300 def SUBST_VARS_RECURSIVE(string, env):
301     '''recursively expand variables'''
302     if string is None:
303         return string
304     limit=100
305     while (string.find('${') != -1 and limit > 0):
306         string = subst_vars_error(string, env)
307         limit -= 1
308     return string
309
310
311 @conf
312 def EXPAND_VARIABLES(ctx, varstr, vars=None):
313     '''expand variables from a user supplied dictionary
314
315     This is most useful when you pass vars=locals() to expand
316     all your local variables in strings
317     '''
318
319     if isinstance(varstr, list):
320         ret = []
321         for s in varstr:
322             ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
323         return ret
324
325     if not isinstance(varstr, str):
326         return varstr
327
328     env = ConfigSet.ConfigSet()
329     ret = varstr
330     # substitute on user supplied dict if avaiilable
331     if vars is not None:
332         for v in vars.keys():
333             env[v] = vars[v]
334         ret = SUBST_VARS_RECURSIVE(ret, env)
335
336     # if anything left, subst on the environment as well
337     if ret.find('${') != -1:
338         ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
339     # make sure there is nothing left. Also check for the common
340     # typo of $( instead of ${
341     if ret.find('${') != -1 or ret.find('$(') != -1:
342         Logs.error('Failed to substitute all variables in varstr=%s' % ret)
343         sys.exit(1)
344     return ret
345 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
346
347
348 def RUN_COMMAND(cmd,
349                 env=None,
350                 shell=False):
351     '''run a external command, return exit code or signal'''
352     if env:
353         cmd = SUBST_VARS_RECURSIVE(cmd, env)
354
355     status = os.system(cmd)
356     if os.WIFEXITED(status):
357         return os.WEXITSTATUS(status)
358     if os.WIFSIGNALED(status):
359         return - os.WTERMSIG(status)
360     Logs.error("Unknown exit reason %d for command: %s" % (status, cmd))
361     return -1
362
363
364 def RUN_PYTHON_TESTS(testfiles, pythonpath=None, extra_env=None):
365     env = LOAD_ENVIRONMENT()
366     if pythonpath is None:
367         pythonpath = os.path.join(Context.g_module.out, 'python')
368     result = 0
369     for interp in env.python_interpreters:
370         if not isinstance(interp, str):
371             interp = ' '.join(interp)
372         for testfile in testfiles:
373             cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
374             if extra_env:
375                 for key, value in extra_env.items():
376                     cmd = "%s=%s %s" % (key, value, cmd)
377             print('Running Python test with %s: %s' % (interp, testfile))
378             ret = RUN_COMMAND(cmd)
379             if ret:
380                 print('Python test failed: %s' % cmd)
381                 result = ret
382     return result
383
384
385 # make sure we have md5. some systems don't have it
386 try:
387     from hashlib import md5
388     # Even if hashlib.md5 exists, it may be unusable.
389     # Try to use MD5 function. In FIPS mode this will cause an exception
390     # and we'll get to the replacement code
391     foo = md5(b'abcd')
392 except:
393     try:
394         import md5
395         # repeat the same check here, mere success of import is not enough.
396         # Try to use MD5 function. In FIPS mode this will cause an exception
397         foo = md5.md5(b'abcd')
398     except:
399         Context.SIG_NIL = hash('abcd')
400         class replace_md5(object):
401             def __init__(self):
402                 self.val = None
403             def update(self, val):
404                 self.val = hash((self.val, val))
405             def digest(self):
406                 return str(self.val)
407             def hexdigest(self):
408                 return self.digest().encode('hex')
409         def replace_h_file(filename):
410             f = open(filename, 'rb')
411             m = replace_md5()
412             while (filename):
413                 filename = f.read(100000)
414                 m.update(filename)
415             f.close()
416             return m.digest()
417         Utils.md5 = replace_md5
418         Task.md5 = replace_md5
419         Utils.h_file = replace_h_file
420
421
422 def LOAD_ENVIRONMENT():
423     '''load the configuration environment, allowing access to env vars
424        from new commands'''
425     env = ConfigSet.ConfigSet()
426     try:
427         p = os.path.join(Context.g_module.out, 'c4che/default'+CACHE_SUFFIX)
428         env.load(p)
429     except (OSError, IOError):
430         pass
431     return env
432
433
434 def IS_NEWER(bld, file1, file2):
435     '''return True if file1 is newer than file2'''
436     curdir = bld.path.abspath()
437     t1 = os.stat(os.path.join(curdir, file1)).st_mtime
438     t2 = os.stat(os.path.join(curdir, file2)).st_mtime
439     return t1 > t2
440 Build.BuildContext.IS_NEWER = IS_NEWER
441
442
443 @conf
444 def RECURSE(ctx, directory):
445     '''recurse into a directory, relative to the curdir or top level'''
446     try:
447         visited_dirs = ctx.visited_dirs
448     except AttributeError:
449         visited_dirs = ctx.visited_dirs = set()
450     d = os.path.join(ctx.path.abspath(), directory)
451     if os.path.exists(d):
452         abspath = os.path.abspath(d)
453     else:
454         abspath = os.path.abspath(os.path.join(Context.g_module.top, directory))
455     ctxclass = ctx.__class__.__name__
456     key = ctxclass + ':' + abspath
457     if key in visited_dirs:
458         # already done it
459         return
460     visited_dirs.add(key)
461     relpath = os.path.relpath(abspath, ctx.path.abspath())
462     if ctxclass in ['tmp', 'OptionsContext', 'ConfigurationContext', 'BuildContext', 'ClangDbContext']:
463         return ctx.recurse(relpath)
464     if 'waflib.extras.compat15' in sys.modules:
465         return ctx.recurse(relpath)
466     Logs.error('Unknown RECURSE context class: {}'.format(ctxclass))
467     raise
468 Options.OptionsContext.RECURSE = RECURSE
469 Build.BuildContext.RECURSE = RECURSE
470
471
472 def CHECK_MAKEFLAGS(options):
473     '''check for MAKEFLAGS environment variable in case we are being
474     called from a Makefile try to honor a few make command line flags'''
475     if not 'WAF_MAKE' in os.environ:
476         return
477     makeflags = os.environ.get('MAKEFLAGS')
478     if makeflags is None:
479         makeflags = ""
480     jobs_set = False
481     jobs = None
482     # we need to use shlex.split to cope with the escaping of spaces
483     # in makeflags
484     for opt in shlex.split(makeflags):
485         # options can come either as -x or as x
486         if opt[0:2] == 'V=':
487             options.verbose = Logs.verbose = int(opt[2:])
488             if Logs.verbose > 0:
489                 Logs.zones = ['runner']
490             if Logs.verbose > 2:
491                 Logs.zones = ['*']
492         elif opt[0].isupper() and opt.find('=') != -1:
493             # this allows us to set waf options on the make command line
494             # for example, if you do "make FOO=blah", then we set the
495             # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
496             # you will see that the command line accessible options have their dest=
497             # set to uppercase, to allow for passing of options from make in this way
498             # this is also how "make test TESTS=testpattern" works, and
499             # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
500             loc = opt.find('=')
501             setattr(options, opt[0:loc], opt[loc+1:])
502         elif opt[0] != '-':
503             for v in opt:
504                 if re.search(r'j[0-9]*$', v):
505                     jobs_set = True
506                     jobs = opt.strip('j')
507                 elif v == 'k':
508                     options.keep = True
509         elif re.search(r'-j[0-9]*$', opt):
510             jobs_set = True
511             jobs = opt.strip('-j')
512         elif opt == '-k':
513             options.keep = True
514     if not jobs_set:
515         # default to one job
516         options.jobs = 1
517     elif jobs_set and jobs:
518         options.jobs = int(jobs)
519
520 waflib_options_parse_cmd_args = Options.OptionsContext.parse_cmd_args
521 def wafsamba_options_parse_cmd_args(self, _args=None, cwd=None, allow_unknown=False):
522     (options, commands, envvars) = \
523         waflib_options_parse_cmd_args(self,
524                                       _args=_args,
525                                       cwd=cwd,
526                                       allow_unknown=allow_unknown)
527     CHECK_MAKEFLAGS(options)
528     if options.jobs == 1:
529         #
530         # waflib.Runner.Parallel processes jobs inline if the possible number
531         # of jobs is just 1. But (at least in waf <= 2.0.12) it still calls
532         # create a waflib.Runner.Spawner() which creates a single
533         # waflib.Runner.Consumer() thread that tries to process jobs from the
534         # queue.
535         #
536         # This has strange effects, which are not noticed typically,
537         # but at least on AIX python has broken threading and fails
538         # in random ways.
539         #
540         # So we just add a dummy Spawner class.
541         class NoOpSpawner(object):
542             def __init__(self, master):
543                 return
544         from waflib import Runner
545         Runner.Spawner = NoOpSpawner
546     return options, commands, envvars
547 Options.OptionsContext.parse_cmd_args = wafsamba_options_parse_cmd_args
548
549 option_groups = {}
550
551 def option_group(opt, name):
552     '''find or create an option group'''
553     global option_groups
554     if name in option_groups:
555         return option_groups[name]
556     gr = opt.add_option_group(name)
557     option_groups[name] = gr
558     return gr
559 Options.OptionsContext.option_group = option_group
560
561
562 def save_file(filename, contents, create_dir=False):
563     '''save data to a file'''
564     if create_dir:
565         mkdir_p(os.path.dirname(filename))
566     try:
567         f = open(filename, 'w')
568         f.write(contents)
569         f.close()
570     except:
571         return False
572     return True
573
574
575 def load_file(filename):
576     '''return contents of a file'''
577     try:
578         f = open(filename, 'r')
579         r = f.read()
580         f.close()
581     except:
582         return None
583     return r
584
585
586 def reconfigure(ctx):
587     '''rerun configure if necessary'''
588     if not os.path.exists(os.environ.get('WAFLOCK', '.lock-wscript')):
589         raise Errors.WafError('configure has not been run')
590     import samba_wildcard
591     bld = samba_wildcard.fake_build_environment()
592     Configure.autoconfig = True
593     Scripting.check_configured(bld)
594
595
596 def map_shlib_extension(ctx, name, python=False):
597     '''map a filename with a shared library extension of .so to the real shlib name'''
598     if name is None:
599         return None
600     if name[-1:].isdigit():
601         # some libraries have specified versions in the wscript rule
602         return name
603     (root1, ext1) = os.path.splitext(name)
604     if python:
605         return ctx.env.pyext_PATTERN % root1
606     else:
607         (root2, ext2) = os.path.splitext(ctx.env.cshlib_PATTERN)
608     return root1+ext2
609 Build.BuildContext.map_shlib_extension = map_shlib_extension
610
611 def apply_pattern(filename, pattern):
612     '''apply a filename pattern to a filename that may have a directory component'''
613     dirname = os.path.dirname(filename)
614     if not dirname:
615         return pattern % filename
616     basename = os.path.basename(filename)
617     return os.path.join(dirname, pattern % basename)
618
619 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
620     """make a library filename
621          Options:
622               nolibprefix: don't include the lib prefix
623               version    : add a version number
624               python     : if we should use python module name conventions"""
625
626     if python:
627         libname = apply_pattern(name, ctx.env.pyext_PATTERN)
628     else:
629         libname = apply_pattern(name, ctx.env.cshlib_PATTERN)
630     if nolibprefix and libname[0:3] == 'lib':
631         libname = libname[3:]
632     if version:
633         if version[0] == '.':
634             version = version[1:]
635         (root, ext) = os.path.splitext(libname)
636         if ext == ".dylib":
637             # special case - version goes before the prefix
638             libname = "%s.%s%s" % (root, version, ext)
639         else:
640             libname = "%s%s.%s" % (root, ext, version)
641     return libname
642 Build.BuildContext.make_libname = make_libname
643
644
645 def get_tgt_list(bld):
646     '''return a list of build objects for samba'''
647
648     targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
649
650     # build a list of task generators we are interested in
651     tgt_list = []
652     for tgt in targets:
653         type = targets[tgt]
654         if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
655             continue
656         t = bld.get_tgen_by_name(tgt)
657         if t is None:
658             Logs.error("Target %s of type %s has no task generator" % (tgt, type))
659             sys.exit(1)
660         tgt_list.append(t)
661     return tgt_list
662
663 from waflib.Context import WSCRIPT_FILE
664 def PROCESS_SEPARATE_RULE(self, rule):
665     ''' cause waf to process additional script based on `rule'.
666         You should have file named wscript_<stage>_rule in the current directory
667         where stage is either 'configure' or 'build'
668     '''
669     stage = ''
670     if isinstance(self, Configure.ConfigurationContext):
671         stage = 'configure'
672     elif isinstance(self, Build.BuildContext):
673         stage = 'build'
674     file_path = os.path.join(self.path.abspath(), WSCRIPT_FILE+'_'+stage+'_'+rule)
675     node = self.root.find_node(file_path)
676     if node:
677         try:
678             cache = self.recurse_cache
679         except AttributeError:
680             cache = self.recurse_cache = {}
681         if node not in cache:
682             cache[node] = True
683             self.pre_recurse(node)
684             try:
685                 function_code = node.read('r', None)
686                 exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
687             finally:
688                 self.post_recurse(node)
689
690 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
691 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
692
693 def AD_DC_BUILD_IS_ENABLED(self):
694     if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
695         return True
696     return False
697
698 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED
699
700 @feature('cprogram', 'cshlib', 'cstaticlib')
701 @after('apply_lib_vars')
702 @before('apply_obj_vars')
703 def samba_before_apply_obj_vars(self):
704     """before apply_obj_vars for uselib, this removes the standard paths"""
705
706     def is_standard_libpath(env, path):
707         for _path in env.STANDARD_LIBPATH:
708             if _path == os.path.normpath(path):
709                 return True
710         return False
711
712     v = self.env
713
714     for i in v['RPATH']:
715         if is_standard_libpath(v, i):
716             v['RPATH'].remove(i)
717
718     for i in v['LIBPATH']:
719         if is_standard_libpath(v, i):
720             v['LIBPATH'].remove(i)
721
722 # Samba options are mostly on by default (administrators and packagers
723 # specify features to remove, not add), which is why default=True
724
725 def samba_add_onoff_option(opt, option, help=(), dest=None, default=True,
726                            with_name="with", without_name="without"):
727     if default is None:
728         default_str = "auto"
729     elif default is True:
730         default_str = "yes"
731     elif default is False:
732         default_str = "no"
733     else:
734         default_str = str(default)
735
736     if help == ():
737         help = ("Build with %s support (default=%s)" % (option, default_str))
738     if dest is None:
739         dest = "with_%s" % option.replace('-', '_')
740
741     with_val = "--%s-%s" % (with_name, option)
742     without_val = "--%s-%s" % (without_name, option)
743
744     opt.add_option(with_val, help=help, action="store_true", dest=dest,
745                    default=default)
746     opt.add_option(without_val, help=SUPPRESS_HELP, action="store_false",
747                    dest=dest)
748 Options.OptionsContext.samba_add_onoff_option = samba_add_onoff_option