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