You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

988 lines
39 KiB

6 years ago
  1. #
  2. # Copyright (c) 2001 - 2017 The SCons Foundation
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining
  5. # a copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish,
  8. # distribute, sublicense, and/or sell copies of the Software, and to
  9. # permit persons to whom the Software is furnished to do so, subject to
  10. # the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  16. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  17. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. #
  23. __revision__ = "src/engine/SCons/Script/SConsOptions.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  24. import optparse
  25. import re
  26. import sys
  27. import textwrap
  28. no_hyphen_re = re.compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))')
  29. try:
  30. from gettext import gettext
  31. except ImportError:
  32. def gettext(message):
  33. return message
  34. _ = gettext
  35. import SCons.Node.FS
  36. import SCons.Warnings
  37. OptionValueError = optparse.OptionValueError
  38. SUPPRESS_HELP = optparse.SUPPRESS_HELP
  39. diskcheck_all = SCons.Node.FS.diskcheck_types()
  40. def diskcheck_convert(value):
  41. if value is None:
  42. return []
  43. if not SCons.Util.is_List(value):
  44. value = value.split(',')
  45. result = []
  46. for v in value:
  47. v = v.lower()
  48. if v == 'all':
  49. result = diskcheck_all
  50. elif v == 'none':
  51. result = []
  52. elif v in diskcheck_all:
  53. result.append(v)
  54. else:
  55. raise ValueError(v)
  56. return result
  57. class SConsValues(optparse.Values):
  58. """
  59. Holder class for uniform access to SCons options, regardless
  60. of whether or not they can be set on the command line or in the
  61. SConscript files (using the SetOption() function).
  62. A SCons option value can originate three different ways:
  63. 1) set on the command line;
  64. 2) set in an SConscript file;
  65. 3) the default setting (from the the op.add_option()
  66. calls in the Parser() function, below).
  67. The command line always overrides a value set in a SConscript file,
  68. which in turn always overrides default settings. Because we want
  69. to support user-specified options in the SConscript file itself,
  70. though, we may not know about all of the options when the command
  71. line is first parsed, so we can't make all the necessary precedence
  72. decisions at the time the option is configured.
  73. The solution implemented in this class is to keep these different sets
  74. of settings separate (command line, SConscript file, and default)
  75. and to override the __getattr__() method to check them in turn.
  76. This should allow the rest of the code to just fetch values as
  77. attributes of an instance of this class, without having to worry
  78. about where they came from.
  79. Note that not all command line options are settable from SConscript
  80. files, and the ones that are must be explicitly added to the
  81. "settable" list in this class, and optionally validated and coerced
  82. in the set_option() method.
  83. """
  84. def __init__(self, defaults):
  85. self.__dict__['__defaults__'] = defaults
  86. self.__dict__['__SConscript_settings__'] = {}
  87. def __getattr__(self, attr):
  88. """
  89. Fetches an options value, checking first for explicit settings
  90. from the command line (which are direct attributes), then the
  91. SConscript file settings, then the default values.
  92. """
  93. try:
  94. return self.__dict__[attr]
  95. except KeyError:
  96. try:
  97. return self.__dict__['__SConscript_settings__'][attr]
  98. except KeyError:
  99. try:
  100. return getattr(self.__dict__['__defaults__'], attr)
  101. except KeyError:
  102. # Added because with py3 this is a new class,
  103. # not a classic class, and due to the way
  104. # In that case it will create an object without
  105. # __defaults__, and then query for __setstate__
  106. # which will throw an exception of KeyError
  107. # deepcopy() is expecting AttributeError if __setstate__
  108. # is not available.
  109. raise AttributeError(attr)
  110. settable = [
  111. 'clean',
  112. 'diskcheck',
  113. 'duplicate',
  114. 'help',
  115. 'implicit_cache',
  116. 'max_drift',
  117. 'md5_chunksize',
  118. 'no_exec',
  119. 'num_jobs',
  120. 'random',
  121. 'stack_size',
  122. 'warn',
  123. 'silent'
  124. ]
  125. def set_option(self, name, value):
  126. """
  127. Sets an option from an SConscript file.
  128. """
  129. if not name in self.settable:
  130. raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name)
  131. if name == 'num_jobs':
  132. try:
  133. value = int(value)
  134. if value < 1:
  135. raise ValueError
  136. except ValueError:
  137. raise SCons.Errors.UserError("A positive integer is required: %s"%repr(value))
  138. elif name == 'max_drift':
  139. try:
  140. value = int(value)
  141. except ValueError:
  142. raise SCons.Errors.UserError("An integer is required: %s"%repr(value))
  143. elif name == 'duplicate':
  144. try:
  145. value = str(value)
  146. except ValueError:
  147. raise SCons.Errors.UserError("A string is required: %s"%repr(value))
  148. if not value in SCons.Node.FS.Valid_Duplicates:
  149. raise SCons.Errors.UserError("Not a valid duplication style: %s" % value)
  150. # Set the duplicate style right away so it can affect linking
  151. # of SConscript files.
  152. SCons.Node.FS.set_duplicate(value)
  153. elif name == 'diskcheck':
  154. try:
  155. value = diskcheck_convert(value)
  156. except ValueError as v:
  157. raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v)
  158. if 'diskcheck' not in self.__dict__:
  159. # No --diskcheck= option was specified on the command line.
  160. # Set this right away so it can affect the rest of the
  161. # file/Node lookups while processing the SConscript files.
  162. SCons.Node.FS.set_diskcheck(value)
  163. elif name == 'stack_size':
  164. try:
  165. value = int(value)
  166. except ValueError:
  167. raise SCons.Errors.UserError("An integer is required: %s"%repr(value))
  168. elif name == 'md5_chunksize':
  169. try:
  170. value = int(value)
  171. except ValueError:
  172. raise SCons.Errors.UserError("An integer is required: %s"%repr(value))
  173. elif name == 'warn':
  174. if SCons.Util.is_String(value):
  175. value = [value]
  176. value = self.__SConscript_settings__.get(name, []) + value
  177. SCons.Warnings.process_warn_strings(value)
  178. self.__SConscript_settings__[name] = value
  179. class SConsOption(optparse.Option):
  180. def convert_value(self, opt, value):
  181. if value is not None:
  182. if self.nargs in (1, '?'):
  183. return self.check_value(opt, value)
  184. else:
  185. return tuple([self.check_value(opt, v) for v in value])
  186. def process(self, opt, value, values, parser):
  187. # First, convert the value(s) to the right type. Howl if any
  188. # value(s) are bogus.
  189. value = self.convert_value(opt, value)
  190. # And then take whatever action is expected of us.
  191. # This is a separate method to make life easier for
  192. # subclasses to add new actions.
  193. return self.take_action(
  194. self.action, self.dest, opt, value, values, parser)
  195. def _check_nargs_optional(self):
  196. if self.nargs == '?' and self._short_opts:
  197. fmt = "option %s: nargs='?' is incompatible with short options"
  198. raise SCons.Errors.UserError(fmt % self._short_opts[0])
  199. try:
  200. _orig_CONST_ACTIONS = optparse.Option.CONST_ACTIONS
  201. _orig_CHECK_METHODS = optparse.Option.CHECK_METHODS
  202. except AttributeError:
  203. # optparse.Option had no CONST_ACTIONS before Python 2.5.
  204. _orig_CONST_ACTIONS = ("store_const",)
  205. def _check_const(self):
  206. if self.action not in self.CONST_ACTIONS and self.const is not None:
  207. raise OptionError(
  208. "'const' must not be supplied for action %r" % self.action,
  209. self)
  210. # optparse.Option collects its list of unbound check functions
  211. # up front. This sucks because it means we can't just override
  212. # the _check_const() function like a normal method, we have to
  213. # actually replace it in the list. This seems to be the most
  214. # straightforward way to do that.
  215. _orig_CHECK_METHODS = [optparse.Option._check_action,
  216. optparse.Option._check_type,
  217. optparse.Option._check_choice,
  218. optparse.Option._check_dest,
  219. _check_const,
  220. optparse.Option._check_nargs,
  221. optparse.Option._check_callback]
  222. CHECK_METHODS = _orig_CHECK_METHODS + [_check_nargs_optional]
  223. CONST_ACTIONS = _orig_CONST_ACTIONS + optparse.Option.TYPED_ACTIONS
  224. class SConsOptionGroup(optparse.OptionGroup):
  225. """
  226. A subclass for SCons-specific option groups.
  227. The only difference between this and the base class is that we print
  228. the group's help text flush left, underneath their own title but
  229. lined up with the normal "SCons Options".
  230. """
  231. def format_help(self, formatter):
  232. """
  233. Format an option group's help text, outdenting the title so it's
  234. flush with the "SCons Options" title we print at the top.
  235. """
  236. formatter.dedent()
  237. result = formatter.format_heading(self.title)
  238. formatter.indent()
  239. result = result + optparse.OptionContainer.format_help(self, formatter)
  240. return result
  241. class SConsOptionParser(optparse.OptionParser):
  242. preserve_unknown_options = False
  243. def error(self, msg):
  244. # overridden OptionValueError exception handler
  245. self.print_usage(sys.stderr)
  246. sys.stderr.write("SCons Error: %s\n" % msg)
  247. sys.exit(2)
  248. def _process_long_opt(self, rargs, values):
  249. """
  250. SCons-specific processing of long options.
  251. This is copied directly from the normal
  252. optparse._process_long_opt() method, except that, if configured
  253. to do so, we catch the exception thrown when an unknown option
  254. is encountered and just stick it back on the "leftover" arguments
  255. for later (re-)processing.
  256. """
  257. arg = rargs.pop(0)
  258. # Value explicitly attached to arg? Pretend it's the next
  259. # argument.
  260. if "=" in arg:
  261. (opt, next_arg) = arg.split("=", 1)
  262. rargs.insert(0, next_arg)
  263. had_explicit_value = True
  264. else:
  265. opt = arg
  266. had_explicit_value = False
  267. try:
  268. opt = self._match_long_opt(opt)
  269. except optparse.BadOptionError:
  270. if self.preserve_unknown_options:
  271. # SCons-specific: if requested, add unknown options to
  272. # the "leftover arguments" list for later processing.
  273. self.largs.append(arg)
  274. if had_explicit_value:
  275. # The unknown option will be re-processed later,
  276. # so undo the insertion of the explicit value.
  277. rargs.pop(0)
  278. return
  279. raise
  280. option = self._long_opt[opt]
  281. if option.takes_value():
  282. nargs = option.nargs
  283. if nargs == '?':
  284. if had_explicit_value:
  285. value = rargs.pop(0)
  286. else:
  287. value = option.const
  288. elif len(rargs) < nargs:
  289. if nargs == 1:
  290. if not option.choices:
  291. self.error(_("%s option requires an argument") % opt)
  292. else:
  293. msg = _("%s option requires an argument " % opt)
  294. msg += _("(choose from %s)"
  295. % ', '.join(option.choices))
  296. self.error(msg)
  297. else:
  298. self.error(_("%s option requires %d arguments")
  299. % (opt, nargs))
  300. elif nargs == 1:
  301. value = rargs.pop(0)
  302. else:
  303. value = tuple(rargs[0:nargs])
  304. del rargs[0:nargs]
  305. elif had_explicit_value:
  306. self.error(_("%s option does not take a value") % opt)
  307. else:
  308. value = None
  309. option.process(opt, value, values, self)
  310. def reparse_local_options(self):
  311. """
  312. Re-parse the leftover command-line options stored
  313. in self.largs, so that any value overridden on the
  314. command line is immediately available if the user turns
  315. around and does a GetOption() right away.
  316. We mimic the processing of the single args
  317. in the original OptionParser._process_args(), but here we
  318. allow exact matches for long-opts only (no partial
  319. argument names!).
  320. Else, this would lead to problems in add_local_option()
  321. below. When called from there, we try to reparse the
  322. command-line arguments that
  323. 1. haven't been processed so far (self.largs), but
  324. 2. are possibly not added to the list of options yet.
  325. So, when we only have a value for "--myargument" yet,
  326. a command-line argument of "--myarg=test" would set it.
  327. Responsible for this behaviour is the method
  328. _match_long_opt(), which allows for partial matches of
  329. the option name, as long as the common prefix appears to
  330. be unique.
  331. This would lead to further confusion, because we might want
  332. to add another option "--myarg" later on (see issue #2929).
  333. """
  334. rargs = []
  335. largs_restore = []
  336. # Loop over all remaining arguments
  337. skip = False
  338. for l in self.largs:
  339. if skip:
  340. # Accept all remaining arguments as they are
  341. largs_restore.append(l)
  342. else:
  343. if len(l) > 2 and l[0:2] == "--":
  344. # Check long option
  345. lopt = (l,)
  346. if "=" in l:
  347. # Split into option and value
  348. lopt = l.split("=", 1)
  349. if lopt[0] in self._long_opt:
  350. # Argument is already known
  351. rargs.append('='.join(lopt))
  352. else:
  353. # Not known yet, so reject for now
  354. largs_restore.append('='.join(lopt))
  355. else:
  356. if l == "--" or l == "-":
  357. # Stop normal processing and don't
  358. # process the rest of the command-line opts
  359. largs_restore.append(l)
  360. skip = True
  361. else:
  362. rargs.append(l)
  363. # Parse the filtered list
  364. self.parse_args(rargs, self.values)
  365. # Restore the list of remaining arguments for the
  366. # next call of AddOption/add_local_option...
  367. self.largs = self.largs + largs_restore
  368. def add_local_option(self, *args, **kw):
  369. """
  370. Adds a local option to the parser.
  371. This is initiated by a SetOption() call to add a user-defined
  372. command-line option. We add the option to a separate option
  373. group for the local options, creating the group if necessary.
  374. """
  375. try:
  376. group = self.local_option_group
  377. except AttributeError:
  378. group = SConsOptionGroup(self, 'Local Options')
  379. group = self.add_option_group(group)
  380. self.local_option_group = group
  381. result = group.add_option(*args, **kw)
  382. if result:
  383. # The option was added successfully. We now have to add the
  384. # default value to our object that holds the default values
  385. # (so that an attempt to fetch the option's attribute will
  386. # yield the default value when not overridden) and then
  387. # we re-parse the leftover command-line options, so that
  388. # any value overridden on the command line is immediately
  389. # available if the user turns around and does a GetOption()
  390. # right away.
  391. setattr(self.values.__defaults__, result.dest, result.default)
  392. self.reparse_local_options()
  393. return result
  394. class SConsIndentedHelpFormatter(optparse.IndentedHelpFormatter):
  395. def format_usage(self, usage):
  396. return "usage: %s\n" % usage
  397. def format_heading(self, heading):
  398. """
  399. This translates any heading of "options" or "Options" into
  400. "SCons Options." Unfortunately, we have to do this here,
  401. because those titles are hard-coded in the optparse calls.
  402. """
  403. if heading == 'Options':
  404. heading = "SCons Options"
  405. return optparse.IndentedHelpFormatter.format_heading(self, heading)
  406. def format_option(self, option):
  407. """
  408. A copy of the normal optparse.IndentedHelpFormatter.format_option()
  409. method. This has been snarfed so we can modify text wrapping to
  410. out liking:
  411. -- add our own regular expression that doesn't break on hyphens
  412. (so things like --no-print-directory don't get broken);
  413. -- wrap the list of options themselves when it's too long
  414. (the wrapper.fill(opts) call below);
  415. -- set the subsequent_indent when wrapping the help_text.
  416. """
  417. # The help for each option consists of two parts:
  418. # * the opt strings and metavars
  419. # eg. ("-x", or "-fFILENAME, --file=FILENAME")
  420. # * the user-supplied help string
  421. # eg. ("turn on expert mode", "read data from FILENAME")
  422. #
  423. # If possible, we write both of these on the same line:
  424. # -x turn on expert mode
  425. #
  426. # But if the opt string list is too long, we put the help
  427. # string on a second line, indented to the same column it would
  428. # start in if it fit on the first line.
  429. # -fFILENAME, --file=FILENAME
  430. # read data from FILENAME
  431. result = []
  432. opts = self.option_strings[option]
  433. opt_width = self.help_position - self.current_indent - 2
  434. if len(opts) > opt_width:
  435. wrapper = textwrap.TextWrapper(width=self.width,
  436. initial_indent = ' ',
  437. subsequent_indent = ' ')
  438. wrapper.wordsep_re = no_hyphen_re
  439. opts = wrapper.fill(opts) + '\n'
  440. indent_first = self.help_position
  441. else: # start help on same line as opts
  442. opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
  443. indent_first = 0
  444. result.append(opts)
  445. if option.help:
  446. help_text = self.expand_default(option)
  447. # SCons: indent every line of the help text but the first.
  448. wrapper = textwrap.TextWrapper(width=self.help_width,
  449. subsequent_indent = ' ')
  450. wrapper.wordsep_re = no_hyphen_re
  451. help_lines = wrapper.wrap(help_text)
  452. result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
  453. for line in help_lines[1:]:
  454. result.append("%*s%s\n" % (self.help_position, "", line))
  455. elif opts[-1] != "\n":
  456. result.append("\n")
  457. return "".join(result)
  458. def Parser(version):
  459. """
  460. Returns an options parser object initialized with the standard
  461. SCons options.
  462. """
  463. formatter = SConsIndentedHelpFormatter(max_help_position=30)
  464. op = SConsOptionParser(option_class=SConsOption,
  465. add_help_option=False,
  466. formatter=formatter,
  467. usage="usage: scons [OPTION] [TARGET] ...",)
  468. op.preserve_unknown_options = True
  469. op.version = version
  470. # Add the options to the parser we just created.
  471. #
  472. # These are in the order we want them to show up in the -H help
  473. # text, basically alphabetical. Each op.add_option() call below
  474. # should have a consistent format:
  475. #
  476. # op.add_option("-L", "--long-option-name",
  477. # nargs=1, type="string",
  478. # dest="long_option_name", default='foo',
  479. # action="callback", callback=opt_long_option,
  480. # help="help text goes here",
  481. # metavar="VAR")
  482. #
  483. # Even though the optparse module constructs reasonable default
  484. # destination names from the long option names, we're going to be
  485. # explicit about each one for easier readability and so this code
  486. # will at least show up when grepping the source for option attribute
  487. # names, or otherwise browsing the source code.
  488. # options ignored for compatibility
  489. def opt_ignore(option, opt, value, parser):
  490. sys.stderr.write("Warning: ignoring %s option\n" % opt)
  491. op.add_option("-b", "-d", "-e", "-m", "-S", "-t", "-w",
  492. "--environment-overrides",
  493. "--no-keep-going",
  494. "--no-print-directory",
  495. "--print-directory",
  496. "--stop",
  497. "--touch",
  498. action="callback", callback=opt_ignore,
  499. help="Ignored for compatibility.")
  500. op.add_option('-c', '--clean', '--remove',
  501. dest="clean", default=False,
  502. action="store_true",
  503. help="Remove specified targets and dependencies.")
  504. op.add_option('-C', '--directory',
  505. nargs=1, type="string",
  506. dest="directory", default=[],
  507. action="append",
  508. help="Change to DIR before doing anything.",
  509. metavar="DIR")
  510. op.add_option('--cache-debug',
  511. nargs=1,
  512. dest="cache_debug", default=None,
  513. action="store",
  514. help="Print CacheDir debug info to FILE.",
  515. metavar="FILE")
  516. op.add_option('--cache-disable', '--no-cache',
  517. dest='cache_disable', default=False,
  518. action="store_true",
  519. help="Do not retrieve built targets from CacheDir.")
  520. op.add_option('--cache-force', '--cache-populate',
  521. dest='cache_force', default=False,
  522. action="store_true",
  523. help="Copy already-built targets into the CacheDir.")
  524. op.add_option('--cache-readonly',
  525. dest='cache_readonly', default=False,
  526. action="store_true",
  527. help="Do not update CacheDir with built targets.")
  528. op.add_option('--cache-show',
  529. dest='cache_show', default=False,
  530. action="store_true",
  531. help="Print build actions for files from CacheDir.")
  532. def opt_invalid(group, value, options):
  533. errmsg = "`%s' is not a valid %s option type, try:\n" % (value, group)
  534. return errmsg + " %s" % ", ".join(options)
  535. config_options = ["auto", "force" ,"cache"]
  536. opt_config_help = "Controls Configure subsystem: %s." \
  537. % ", ".join(config_options)
  538. op.add_option('--config',
  539. nargs=1, choices=config_options,
  540. dest="config", default="auto",
  541. help = opt_config_help,
  542. metavar="MODE")
  543. op.add_option('-D',
  544. dest="climb_up", default=None,
  545. action="store_const", const=2,
  546. help="Search up directory tree for SConstruct, "
  547. "build all Default() targets.")
  548. deprecated_debug_options = {
  549. "dtree" : '; please use --tree=derived instead',
  550. "nomemoizer" : ' and has no effect',
  551. "stree" : '; please use --tree=all,status instead',
  552. "tree" : '; please use --tree=all instead',
  553. }
  554. debug_options = ["count", "duplicate", "explain", "findlibs",
  555. "includes", "memoizer", "memory", "objects",
  556. "pdb", "prepare", "presub", "stacktrace",
  557. "time"]
  558. def opt_debug(option, opt, value__, parser,
  559. debug_options=debug_options,
  560. deprecated_debug_options=deprecated_debug_options):
  561. for value in value__.split(','):
  562. if value in debug_options:
  563. parser.values.debug.append(value)
  564. elif value in list(deprecated_debug_options.keys()):
  565. parser.values.debug.append(value)
  566. try:
  567. parser.values.delayed_warnings
  568. except AttributeError:
  569. parser.values.delayed_warnings = []
  570. msg = deprecated_debug_options[value]
  571. w = "The --debug=%s option is deprecated%s." % (value, msg)
  572. t = (SCons.Warnings.DeprecatedDebugOptionsWarning, w)
  573. parser.values.delayed_warnings.append(t)
  574. else:
  575. raise OptionValueError(opt_invalid('debug', value, debug_options))
  576. opt_debug_help = "Print various types of debugging information: %s." \
  577. % ", ".join(debug_options)
  578. op.add_option('--debug',
  579. nargs=1, type="string",
  580. dest="debug", default=[],
  581. action="callback", callback=opt_debug,
  582. help=opt_debug_help,
  583. metavar="TYPE")
  584. def opt_diskcheck(option, opt, value, parser):
  585. try:
  586. diskcheck_value = diskcheck_convert(value)
  587. except ValueError as e:
  588. raise OptionValueError("`%s' is not a valid diskcheck type" % e)
  589. setattr(parser.values, option.dest, diskcheck_value)
  590. op.add_option('--diskcheck',
  591. nargs=1, type="string",
  592. dest='diskcheck', default=None,
  593. action="callback", callback=opt_diskcheck,
  594. help="Enable specific on-disk checks.",
  595. metavar="TYPE")
  596. def opt_duplicate(option, opt, value, parser):
  597. if not value in SCons.Node.FS.Valid_Duplicates:
  598. raise OptionValueError(opt_invalid('duplication', value,
  599. SCons.Node.FS.Valid_Duplicates))
  600. setattr(parser.values, option.dest, value)
  601. # Set the duplicate style right away so it can affect linking
  602. # of SConscript files.
  603. SCons.Node.FS.set_duplicate(value)
  604. opt_duplicate_help = "Set the preferred duplication methods. Must be one of " \
  605. + ", ".join(SCons.Node.FS.Valid_Duplicates)
  606. op.add_option('--duplicate',
  607. nargs=1, type="string",
  608. dest="duplicate", default='hard-soft-copy',
  609. action="callback", callback=opt_duplicate,
  610. help=opt_duplicate_help)
  611. op.add_option('-f', '--file', '--makefile', '--sconstruct',
  612. nargs=1, type="string",
  613. dest="file", default=[],
  614. action="append",
  615. help="Read FILE as the top-level SConstruct file.")
  616. op.add_option('-h', '--help',
  617. dest="help", default=False,
  618. action="store_true",
  619. help="Print defined help message, or this one.")
  620. op.add_option("-H", "--help-options",
  621. action="help",
  622. help="Print this message and exit.")
  623. op.add_option('-i', '--ignore-errors',
  624. dest='ignore_errors', default=False,
  625. action="store_true",
  626. help="Ignore errors from build actions.")
  627. op.add_option('-I', '--include-dir',
  628. nargs=1,
  629. dest='include_dir', default=[],
  630. action="append",
  631. help="Search DIR for imported Python modules.",
  632. metavar="DIR")
  633. op.add_option('--implicit-cache',
  634. dest='implicit_cache', default=False,
  635. action="store_true",
  636. help="Cache implicit dependencies")
  637. def opt_implicit_deps(option, opt, value, parser):
  638. setattr(parser.values, 'implicit_cache', True)
  639. setattr(parser.values, option.dest, True)
  640. op.add_option('--implicit-deps-changed',
  641. dest="implicit_deps_changed", default=False,
  642. action="callback", callback=opt_implicit_deps,
  643. help="Ignore cached implicit dependencies.")
  644. op.add_option('--implicit-deps-unchanged',
  645. dest="implicit_deps_unchanged", default=False,
  646. action="callback", callback=opt_implicit_deps,
  647. help="Ignore changes in implicit dependencies.")
  648. op.add_option('--interact', '--interactive',
  649. dest='interactive', default=False,
  650. action="store_true",
  651. help="Run in interactive mode.")
  652. op.add_option('-j', '--jobs',
  653. nargs=1, type="int",
  654. dest="num_jobs", default=1,
  655. action="store",
  656. help="Allow N jobs at once.",
  657. metavar="N")
  658. op.add_option('-k', '--keep-going',
  659. dest='keep_going', default=False,
  660. action="store_true",
  661. help="Keep going when a target can't be made.")
  662. op.add_option('--max-drift',
  663. nargs=1, type="int",
  664. dest='max_drift', default=SCons.Node.FS.default_max_drift,
  665. action="store",
  666. help="Set maximum system clock drift to N seconds.",
  667. metavar="N")
  668. op.add_option('--md5-chunksize',
  669. nargs=1, type="int",
  670. dest='md5_chunksize', default=SCons.Node.FS.File.md5_chunksize,
  671. action="store",
  672. help="Set chunk-size for MD5 signature computation to N kilobytes.",
  673. metavar="N")
  674. op.add_option('-n', '--no-exec', '--just-print', '--dry-run', '--recon',
  675. dest='no_exec', default=False,
  676. action="store_true",
  677. help="Don't build; just print commands.")
  678. op.add_option('--no-site-dir',
  679. dest='no_site_dir', default=False,
  680. action="store_true",
  681. help="Don't search or use the usual site_scons dir.")
  682. op.add_option('--profile',
  683. nargs=1,
  684. dest="profile_file", default=None,
  685. action="store",
  686. help="Profile SCons and put results in FILE.",
  687. metavar="FILE")
  688. op.add_option('-q', '--question',
  689. dest="question", default=False,
  690. action="store_true",
  691. help="Don't build; exit status says if up to date.")
  692. op.add_option('-Q',
  693. dest='no_progress', default=False,
  694. action="store_true",
  695. help="Suppress \"Reading/Building\" progress messages.")
  696. op.add_option('--random',
  697. dest="random", default=False,
  698. action="store_true",
  699. help="Build dependencies in random order.")
  700. op.add_option('-s', '--silent', '--quiet',
  701. dest="silent", default=False,
  702. action="store_true",
  703. help="Don't print commands.")
  704. op.add_option('--site-dir',
  705. nargs=1,
  706. dest='site_dir', default=None,
  707. action="store",
  708. help="Use DIR instead of the usual site_scons dir.",
  709. metavar="DIR")
  710. op.add_option('--stack-size',
  711. nargs=1, type="int",
  712. dest='stack_size',
  713. action="store",
  714. help="Set the stack size of the threads used to run jobs to N kilobytes.",
  715. metavar="N")
  716. op.add_option('--taskmastertrace',
  717. nargs=1,
  718. dest="taskmastertrace_file", default=None,
  719. action="store",
  720. help="Trace Node evaluation to FILE.",
  721. metavar="FILE")
  722. tree_options = ["all", "derived", "prune", "status"]
  723. def opt_tree(option, opt, value, parser, tree_options=tree_options):
  724. from . import Main
  725. tp = Main.TreePrinter()
  726. for o in value.split(','):
  727. if o == 'all':
  728. tp.derived = False
  729. elif o == 'derived':
  730. tp.derived = True
  731. elif o == 'prune':
  732. tp.prune = True
  733. elif o == 'status':
  734. tp.status = True
  735. else:
  736. raise OptionValueError(opt_invalid('--tree', o, tree_options))
  737. parser.values.tree_printers.append(tp)
  738. opt_tree_help = "Print a dependency tree in various formats: %s." \
  739. % ", ".join(tree_options)
  740. op.add_option('--tree',
  741. nargs=1, type="string",
  742. dest="tree_printers", default=[],
  743. action="callback", callback=opt_tree,
  744. help=opt_tree_help,
  745. metavar="OPTIONS")
  746. op.add_option('-u', '--up', '--search-up',
  747. dest="climb_up", default=0,
  748. action="store_const", const=1,
  749. help="Search up directory tree for SConstruct, "
  750. "build targets at or below current directory.")
  751. op.add_option('-U',
  752. dest="climb_up", default=0,
  753. action="store_const", const=3,
  754. help="Search up directory tree for SConstruct, "
  755. "build Default() targets from local SConscript.")
  756. def opt_version(option, opt, value, parser):
  757. sys.stdout.write(parser.version + '\n')
  758. sys.exit(0)
  759. op.add_option("-v", "--version",
  760. action="callback", callback=opt_version,
  761. help="Print the SCons version number and exit.")
  762. def opt_warn(option, opt, value, parser, tree_options=tree_options):
  763. if SCons.Util.is_String(value):
  764. value = value.split(',')
  765. parser.values.warn.extend(value)
  766. op.add_option('--warn', '--warning',
  767. nargs=1, type="string",
  768. dest="warn", default=[],
  769. action="callback", callback=opt_warn,
  770. help="Enable or disable warnings.",
  771. metavar="WARNING-SPEC")
  772. op.add_option('-Y', '--repository', '--srcdir',
  773. nargs=1,
  774. dest="repository", default=[],
  775. action="append",
  776. help="Search REPOSITORY for source and target files.")
  777. # Options from Make and Cons classic that we do not yet support,
  778. # but which we may support someday and whose (potential) meanings
  779. # we don't want to change. These all get a "the -X option is not
  780. # yet implemented" message and don't show up in the help output.
  781. def opt_not_yet(option, opt, value, parser):
  782. msg = "Warning: the %s option is not yet implemented\n" % opt
  783. sys.stderr.write(msg)
  784. op.add_option('-l', '--load-average', '--max-load',
  785. nargs=1, type="float",
  786. dest="load_average", default=0,
  787. action="callback", callback=opt_not_yet,
  788. # action="store",
  789. # help="Don't start multiple jobs unless load is below "
  790. # "LOAD-AVERAGE."
  791. help=SUPPRESS_HELP)
  792. op.add_option('--list-actions',
  793. dest="list_actions",
  794. action="callback", callback=opt_not_yet,
  795. # help="Don't build; list files and build actions."
  796. help=SUPPRESS_HELP)
  797. op.add_option('--list-derived',
  798. dest="list_derived",
  799. action="callback", callback=opt_not_yet,
  800. # help="Don't build; list files that would be built."
  801. help=SUPPRESS_HELP)
  802. op.add_option('--list-where',
  803. dest="list_where",
  804. action="callback", callback=opt_not_yet,
  805. # help="Don't build; list files and where defined."
  806. help=SUPPRESS_HELP)
  807. op.add_option('-o', '--old-file', '--assume-old',
  808. nargs=1, type="string",
  809. dest="old_file", default=[],
  810. action="callback", callback=opt_not_yet,
  811. # action="append",
  812. # help = "Consider FILE to be old; don't rebuild it."
  813. help=SUPPRESS_HELP)
  814. op.add_option('--override',
  815. nargs=1, type="string",
  816. action="callback", callback=opt_not_yet,
  817. dest="override",
  818. # help="Override variables as specified in FILE."
  819. help=SUPPRESS_HELP)
  820. op.add_option('-p',
  821. action="callback", callback=opt_not_yet,
  822. dest="p",
  823. # help="Print internal environments/objects."
  824. help=SUPPRESS_HELP)
  825. op.add_option('-r', '-R', '--no-builtin-rules', '--no-builtin-variables',
  826. action="callback", callback=opt_not_yet,
  827. dest="no_builtin_rules",
  828. # help="Clear default environments and variables."
  829. help=SUPPRESS_HELP)
  830. op.add_option('--write-filenames',
  831. nargs=1, type="string",
  832. dest="write_filenames",
  833. action="callback", callback=opt_not_yet,
  834. # help="Write all filenames examined into FILE."
  835. help=SUPPRESS_HELP)
  836. op.add_option('-W', '--new-file', '--assume-new', '--what-if',
  837. nargs=1, type="string",
  838. dest="new_file",
  839. action="callback", callback=opt_not_yet,
  840. # help="Consider FILE to be changed."
  841. help=SUPPRESS_HELP)
  842. op.add_option('--warn-undefined-variables',
  843. dest="warn_undefined_variables",
  844. action="callback", callback=opt_not_yet,
  845. # help="Warn when an undefined variable is referenced."
  846. help=SUPPRESS_HELP)
  847. return op
  848. # Local Variables:
  849. # tab-width:4
  850. # indent-tabs-mode:nil
  851. # End:
  852. # vim: set expandtab tabstop=4 shiftwidth=4: