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