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.

376 lines
13 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. from __future__ import print_function
  23. __revision__ = "src/engine/SCons/Script/Interactive.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  24. __doc__ = """
  25. SCons interactive mode
  26. """
  27. # TODO:
  28. #
  29. # This has the potential to grow into something with a really big life
  30. # of its own, which might or might not be a good thing. Nevertheless,
  31. # here are some enhancements that will probably be requested some day
  32. # and are worth keeping in mind (assuming this takes off):
  33. #
  34. # - A command to re-read / re-load the SConscript files. This may
  35. # involve allowing people to specify command-line options (e.g. -f,
  36. # -I, --no-site-dir) that affect how the SConscript files are read.
  37. #
  38. # - Additional command-line options on the "build" command.
  39. #
  40. # Of the supported options that seemed to make sense (after a quick
  41. # pass through the list), the ones that seemed likely enough to be
  42. # used are listed in the man page and have explicit test scripts.
  43. #
  44. # These had code changed in Script/Main.py to support them, but didn't
  45. # seem likely to be used regularly, so had no test scripts added:
  46. #
  47. # build --diskcheck=*
  48. # build --implicit-cache=*
  49. # build --implicit-deps-changed=*
  50. # build --implicit-deps-unchanged=*
  51. #
  52. # These look like they should "just work" with no changes to the
  53. # existing code, but like those above, look unlikely to be used and
  54. # therefore had no test scripts added:
  55. #
  56. # build --random
  57. #
  58. # These I'm not sure about. They might be useful for individual
  59. # "build" commands, and may even work, but they seem unlikely enough
  60. # that we'll wait until they're requested before spending any time on
  61. # writing test scripts for them, or investigating whether they work.
  62. #
  63. # build -q [??? is there a useful analog to the exit status?]
  64. # build --duplicate=
  65. # build --profile=
  66. # build --max-drift=
  67. # build --warn=*
  68. # build --Y
  69. #
  70. # - Most of the SCons command-line options that the "build" command
  71. # supports should be settable as default options that apply to all
  72. # subsequent "build" commands. Maybe a "set {option}" command that
  73. # maps to "SetOption('{option}')".
  74. #
  75. # - Need something in the 'help' command that prints the -h output.
  76. #
  77. # - A command to run the configure subsystem separately (must see how
  78. # this interacts with the new automake model).
  79. #
  80. # - Command-line completion of target names; maybe even of SCons options?
  81. # Completion is something that's supported by the Python cmd module,
  82. # so this should be doable without too much trouble.
  83. #
  84. import cmd
  85. import copy
  86. import os
  87. import re
  88. import shlex
  89. import sys
  90. try:
  91. import readline
  92. except ImportError:
  93. pass
  94. class SConsInteractiveCmd(cmd.Cmd):
  95. """\
  96. build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym.
  97. clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. 'c' is a synonym.
  98. exit Exit SCons interactive mode.
  99. help [COMMAND] Prints help for the specified COMMAND. 'h' and '?' are synonyms.
  100. shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms.
  101. version Prints SCons version information.
  102. """
  103. synonyms = {
  104. 'b' : 'build',
  105. 'c' : 'clean',
  106. 'h' : 'help',
  107. 'scons' : 'build',
  108. 'sh' : 'shell',
  109. }
  110. def __init__(self, **kw):
  111. cmd.Cmd.__init__(self)
  112. for key, val in kw.items():
  113. setattr(self, key, val)
  114. if sys.platform == 'win32':
  115. self.shell_variable = 'COMSPEC'
  116. else:
  117. self.shell_variable = 'SHELL'
  118. def default(self, argv):
  119. print("*** Unknown command: %s" % argv[0])
  120. def onecmd(self, line):
  121. line = line.strip()
  122. if not line:
  123. print(self.lastcmd)
  124. return self.emptyline()
  125. self.lastcmd = line
  126. if line[0] == '!':
  127. line = 'shell ' + line[1:]
  128. elif line[0] == '?':
  129. line = 'help ' + line[1:]
  130. if os.sep == '\\':
  131. line = line.replace('\\', '\\\\')
  132. argv = shlex.split(line)
  133. argv[0] = self.synonyms.get(argv[0], argv[0])
  134. if not argv[0]:
  135. return self.default(line)
  136. else:
  137. try:
  138. func = getattr(self, 'do_' + argv[0])
  139. except AttributeError:
  140. return self.default(argv)
  141. return func(argv)
  142. def do_build(self, argv):
  143. """\
  144. build [TARGETS] Build the specified TARGETS and their
  145. dependencies. 'b' is a synonym.
  146. """
  147. import SCons.Node
  148. import SCons.SConsign
  149. import SCons.Script.Main
  150. options = copy.deepcopy(self.options)
  151. options, targets = self.parser.parse_args(argv[1:], values=options)
  152. SCons.Script.COMMAND_LINE_TARGETS = targets
  153. if targets:
  154. SCons.Script.BUILD_TARGETS = targets
  155. else:
  156. # If the user didn't specify any targets on the command line,
  157. # use the list of default targets.
  158. SCons.Script.BUILD_TARGETS = SCons.Script._build_plus_default
  159. nodes = SCons.Script.Main._build_targets(self.fs,
  160. options,
  161. targets,
  162. self.target_top)
  163. if not nodes:
  164. return
  165. # Call each of the Node's alter_targets() methods, which may
  166. # provide additional targets that ended up as part of the build
  167. # (the canonical example being a VariantDir() when we're building
  168. # from a source directory) and which we therefore need their
  169. # state cleared, too.
  170. x = []
  171. for n in nodes:
  172. x.extend(n.alter_targets()[0])
  173. nodes.extend(x)
  174. # Clean up so that we can perform the next build correctly.
  175. #
  176. # We do this by walking over all the children of the targets,
  177. # and clearing their state.
  178. #
  179. # We currently have to re-scan each node to find their
  180. # children, because built nodes have already been partially
  181. # cleared and don't remember their children. (In scons
  182. # 0.96.1 and earlier, this wasn't the case, and we didn't
  183. # have to re-scan the nodes.)
  184. #
  185. # Because we have to re-scan each node, we can't clear the
  186. # nodes as we walk over them, because we may end up rescanning
  187. # a cleared node as we scan a later node. Therefore, only
  188. # store the list of nodes that need to be cleared as we walk
  189. # the tree, and clear them in a separate pass.
  190. #
  191. # XXX: Someone more familiar with the inner workings of scons
  192. # may be able to point out a more efficient way to do this.
  193. SCons.Script.Main.progress_display("scons: Clearing cached node information ...")
  194. seen_nodes = {}
  195. def get_unseen_children(node, parent, seen_nodes=seen_nodes):
  196. def is_unseen(node, seen_nodes=seen_nodes):
  197. return node not in seen_nodes
  198. return [child for child in node.children(scan=1) if is_unseen(child)]
  199. def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes):
  200. seen_nodes[node] = 1
  201. # If this file is in a VariantDir and has a
  202. # corresponding source file in the source tree, remember the
  203. # node in the source tree, too. This is needed in
  204. # particular to clear cached implicit dependencies on the
  205. # source file, since the scanner will scan it if the
  206. # VariantDir was created with duplicate=0.
  207. try:
  208. rfile_method = node.rfile
  209. except AttributeError:
  210. return
  211. else:
  212. rfile = rfile_method()
  213. if rfile != node:
  214. seen_nodes[rfile] = 1
  215. for node in nodes:
  216. walker = SCons.Node.Walker(node,
  217. kids_func=get_unseen_children,
  218. eval_func=add_to_seen_nodes)
  219. n = walker.get_next()
  220. while n:
  221. n = walker.get_next()
  222. for node in list(seen_nodes.keys()):
  223. # Call node.clear() to clear most of the state
  224. node.clear()
  225. # node.clear() doesn't reset node.state, so call
  226. # node.set_state() to reset it manually
  227. node.set_state(SCons.Node.no_state)
  228. node.implicit = None
  229. # Debug: Uncomment to verify that all Taskmaster reference
  230. # counts have been reset to zero.
  231. #if node.ref_count != 0:
  232. # from SCons.Debug import Trace
  233. # Trace('node %s, ref_count %s !!!\n' % (node, node.ref_count))
  234. SCons.SConsign.Reset()
  235. SCons.Script.Main.progress_display("scons: done clearing node information.")
  236. def do_clean(self, argv):
  237. """\
  238. clean [TARGETS] Clean (remove) the specified TARGETS
  239. and their dependencies. 'c' is a synonym.
  240. """
  241. return self.do_build(['build', '--clean'] + argv[1:])
  242. def do_EOF(self, argv):
  243. print()
  244. self.do_exit(argv)
  245. def _do_one_help(self, arg):
  246. try:
  247. # If help_<arg>() exists, then call it.
  248. func = getattr(self, 'help_' + arg)
  249. except AttributeError:
  250. try:
  251. func = getattr(self, 'do_' + arg)
  252. except AttributeError:
  253. doc = None
  254. else:
  255. doc = self._doc_to_help(func)
  256. if doc:
  257. sys.stdout.write(doc + '\n')
  258. sys.stdout.flush()
  259. else:
  260. doc = self.strip_initial_spaces(func())
  261. if doc:
  262. sys.stdout.write(doc + '\n')
  263. sys.stdout.flush()
  264. def _doc_to_help(self, obj):
  265. doc = obj.__doc__
  266. if doc is None:
  267. return ''
  268. return self._strip_initial_spaces(doc)
  269. def _strip_initial_spaces(self, s):
  270. lines = s.split('\n')
  271. spaces = re.match(' *', lines[0]).group(0)
  272. def strip_spaces(l, spaces=spaces):
  273. if l[:len(spaces)] == spaces:
  274. l = l[len(spaces):]
  275. return l
  276. lines = list(map(strip_spaces, lines))
  277. return '\n'.join(lines)
  278. def do_exit(self, argv):
  279. """\
  280. exit Exit SCons interactive mode.
  281. """
  282. sys.exit(0)
  283. def do_help(self, argv):
  284. """\
  285. help [COMMAND] Prints help for the specified COMMAND. 'h'
  286. and '?' are synonyms.
  287. """
  288. if argv[1:]:
  289. for arg in argv[1:]:
  290. if self._do_one_help(arg):
  291. break
  292. else:
  293. # If bare 'help' is called, print this class's doc
  294. # string (if it has one).
  295. doc = self._doc_to_help(self.__class__)
  296. if doc:
  297. sys.stdout.write(doc + '\n')
  298. sys.stdout.flush()
  299. def do_shell(self, argv):
  300. """\
  301. shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and
  302. '!' are synonyms.
  303. """
  304. import subprocess
  305. argv = argv[1:]
  306. if not argv:
  307. argv = os.environ[self.shell_variable]
  308. try:
  309. # Per "[Python-Dev] subprocess insufficiently platform-independent?"
  310. # http://mail.python.org/pipermail/python-dev/2008-August/081979.html "+
  311. # Doing the right thing with an argument list currently
  312. # requires different shell= values on Windows and Linux.
  313. p = subprocess.Popen(argv, shell=(sys.platform=='win32'))
  314. except EnvironmentError as e:
  315. sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror))
  316. else:
  317. p.wait()
  318. def do_version(self, argv):
  319. """\
  320. version Prints SCons version information.
  321. """
  322. sys.stdout.write(self.parser.version + '\n')
  323. def interact(fs, parser, options, targets, target_top):
  324. c = SConsInteractiveCmd(prompt = 'scons>>> ',
  325. fs = fs,
  326. parser = parser,
  327. options = options,
  328. targets = targets,
  329. target_top = target_top)
  330. c.cmdloop()
  331. # Local Variables:
  332. # tab-width:4
  333. # indent-tabs-mode:nil
  334. # End:
  335. # vim: set expandtab tabstop=4 shiftwidth=4: