cmd.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. """distutils.cmd
  2. Provides the Command class, the base class for the command classes
  3. in the distutils.command package.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import os
  8. import re
  9. import sys
  10. from abc import abstractmethod
  11. from collections.abc import Callable, MutableSequence
  12. from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload
  13. from . import _modified, archive_util, dir_util, file_util, util
  14. from ._log import log
  15. from .errors import DistutilsOptionError
  16. if TYPE_CHECKING:
  17. # type-only import because of mutual dependence between these classes
  18. from distutils.dist import Distribution
  19. from typing_extensions import TypeVarTuple, Unpack
  20. _Ts = TypeVarTuple("_Ts")
  21. _StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]")
  22. _BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]")
  23. _CommandT = TypeVar("_CommandT", bound="Command")
  24. class Command:
  25. """Abstract base class for defining command classes, the "worker bees"
  26. of the Distutils. A useful analogy for command classes is to think of
  27. them as subroutines with local variables called "options". The options
  28. are "declared" in 'initialize_options()' and "defined" (given their
  29. final values, aka "finalized") in 'finalize_options()', both of which
  30. must be defined by every command class. The distinction between the
  31. two is necessary because option values might come from the outside
  32. world (command line, config file, ...), and any options dependent on
  33. other options must be computed *after* these outside influences have
  34. been processed -- hence 'finalize_options()'. The "body" of the
  35. subroutine, where it does all its work based on the values of its
  36. options, is the 'run()' method, which must also be implemented by every
  37. command class.
  38. """
  39. # 'sub_commands' formalizes the notion of a "family" of commands,
  40. # eg. "install" as the parent with sub-commands "install_lib",
  41. # "install_headers", etc. The parent of a family of commands
  42. # defines 'sub_commands' as a class attribute; it's a list of
  43. # (command_name : string, predicate : unbound_method | string | None)
  44. # tuples, where 'predicate' is a method of the parent command that
  45. # determines whether the corresponding command is applicable in the
  46. # current situation. (Eg. we "install_headers" is only applicable if
  47. # we have any C header files to install.) If 'predicate' is None,
  48. # that command is always applicable.
  49. #
  50. # 'sub_commands' is usually defined at the *end* of a class, because
  51. # predicates can be unbound methods, so they must already have been
  52. # defined. The canonical example is the "install" command.
  53. sub_commands: ClassVar[ # Any to work around variance issues
  54. list[tuple[str, Callable[[Any], bool] | None]]
  55. ] = []
  56. user_options: ClassVar[
  57. # Specifying both because list is invariant. Avoids mypy override assignment issues
  58. list[tuple[str, str, str]] | list[tuple[str, str | None, str]]
  59. ] = []
  60. # -- Creation/initialization methods -------------------------------
  61. def __init__(self, dist: Distribution) -> None:
  62. """Create and initialize a new Command object. Most importantly,
  63. invokes the 'initialize_options()' method, which is the real
  64. initializer and depends on the actual command being
  65. instantiated.
  66. """
  67. # late import because of mutual dependence between these classes
  68. from distutils.dist import Distribution
  69. if not isinstance(dist, Distribution):
  70. raise TypeError("dist must be a Distribution instance")
  71. if self.__class__ is Command:
  72. raise RuntimeError("Command is an abstract class")
  73. self.distribution = dist
  74. self.initialize_options()
  75. # Per-command versions of the global flags, so that the user can
  76. # customize Distutils' behaviour command-by-command and let some
  77. # commands fall back on the Distribution's behaviour. None means
  78. # "not defined, check self.distribution's copy", while 0 or 1 mean
  79. # false and true (duh). Note that this means figuring out the real
  80. # value of each flag is a touch complicated -- hence "self._dry_run"
  81. # will be handled by __getattr__, below.
  82. # XXX This needs to be fixed.
  83. self._dry_run = None
  84. # verbose is largely ignored, but needs to be set for
  85. # backwards compatibility (I think)?
  86. self.verbose = dist.verbose
  87. # Some commands define a 'self.force' option to ignore file
  88. # timestamps, but methods defined *here* assume that
  89. # 'self.force' exists for all commands. So define it here
  90. # just to be safe.
  91. self.force = None
  92. # The 'help' flag is just used for command-line parsing, so
  93. # none of that complicated bureaucracy is needed.
  94. self.help = False
  95. # 'finalized' records whether or not 'finalize_options()' has been
  96. # called. 'finalize_options()' itself should not pay attention to
  97. # this flag: it is the business of 'ensure_finalized()', which
  98. # always calls 'finalize_options()', to respect/update it.
  99. self.finalized = False
  100. # XXX A more explicit way to customize dry_run would be better.
  101. def __getattr__(self, attr):
  102. if attr == 'dry_run':
  103. myval = getattr(self, "_" + attr)
  104. if myval is None:
  105. return getattr(self.distribution, attr)
  106. else:
  107. return myval
  108. else:
  109. raise AttributeError(attr)
  110. def ensure_finalized(self) -> None:
  111. if not self.finalized:
  112. self.finalize_options()
  113. self.finalized = True
  114. # Subclasses must define:
  115. # initialize_options()
  116. # provide default values for all options; may be customized by
  117. # setup script, by options from config file(s), or by command-line
  118. # options
  119. # finalize_options()
  120. # decide on the final values for all options; this is called
  121. # after all possible intervention from the outside world
  122. # (command-line, option file, etc.) has been processed
  123. # run()
  124. # run the command: do whatever it is we're here to do,
  125. # controlled by the command's various option values
  126. @abstractmethod
  127. def initialize_options(self) -> None:
  128. """Set default values for all the options that this command
  129. supports. Note that these defaults may be overridden by other
  130. commands, by the setup script, by config files, or by the
  131. command-line. Thus, this is not the place to code dependencies
  132. between options; generally, 'initialize_options()' implementations
  133. are just a bunch of "self.foo = None" assignments.
  134. This method must be implemented by all command classes.
  135. """
  136. raise RuntimeError(
  137. f"abstract method -- subclass {self.__class__} must override"
  138. )
  139. @abstractmethod
  140. def finalize_options(self) -> None:
  141. """Set final values for all the options that this command supports.
  142. This is always called as late as possible, ie. after any option
  143. assignments from the command-line or from other commands have been
  144. done. Thus, this is the place to code option dependencies: if
  145. 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
  146. long as 'foo' still has the same value it was assigned in
  147. 'initialize_options()'.
  148. This method must be implemented by all command classes.
  149. """
  150. raise RuntimeError(
  151. f"abstract method -- subclass {self.__class__} must override"
  152. )
  153. def dump_options(self, header=None, indent=""):
  154. from distutils.fancy_getopt import longopt_xlate
  155. if header is None:
  156. header = f"command options for '{self.get_command_name()}':"
  157. self.announce(indent + header, level=logging.INFO)
  158. indent = indent + " "
  159. for option, _, _ in self.user_options:
  160. option = option.translate(longopt_xlate)
  161. if option[-1] == "=":
  162. option = option[:-1]
  163. value = getattr(self, option)
  164. self.announce(indent + f"{option} = {value}", level=logging.INFO)
  165. @abstractmethod
  166. def run(self) -> None:
  167. """A command's raison d'etre: carry out the action it exists to
  168. perform, controlled by the options initialized in
  169. 'initialize_options()', customized by other commands, the setup
  170. script, the command-line, and config files, and finalized in
  171. 'finalize_options()'. All terminal output and filesystem
  172. interaction should be done by 'run()'.
  173. This method must be implemented by all command classes.
  174. """
  175. raise RuntimeError(
  176. f"abstract method -- subclass {self.__class__} must override"
  177. )
  178. def announce(self, msg: object, level: int = logging.DEBUG) -> None:
  179. log.log(level, msg)
  180. def debug_print(self, msg: object) -> None:
  181. """Print 'msg' to stdout if the global DEBUG (taken from the
  182. DISTUTILS_DEBUG environment variable) flag is true.
  183. """
  184. from distutils.debug import DEBUG
  185. if DEBUG:
  186. print(msg)
  187. sys.stdout.flush()
  188. # -- Option validation methods -------------------------------------
  189. # (these are very handy in writing the 'finalize_options()' method)
  190. #
  191. # NB. the general philosophy here is to ensure that a particular option
  192. # value meets certain type and value constraints. If not, we try to
  193. # force it into conformance (eg. if we expect a list but have a string,
  194. # split the string on comma and/or whitespace). If we can't force the
  195. # option into conformance, raise DistutilsOptionError. Thus, command
  196. # classes need do nothing more than (eg.)
  197. # self.ensure_string_list('foo')
  198. # and they can be guaranteed that thereafter, self.foo will be
  199. # a list of strings.
  200. def _ensure_stringlike(self, option, what, default=None):
  201. val = getattr(self, option)
  202. if val is None:
  203. setattr(self, option, default)
  204. return default
  205. elif not isinstance(val, str):
  206. raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
  207. return val
  208. def ensure_string(self, option: str, default: str | None = None) -> None:
  209. """Ensure that 'option' is a string; if not defined, set it to
  210. 'default'.
  211. """
  212. self._ensure_stringlike(option, "string", default)
  213. def ensure_string_list(self, option: str) -> None:
  214. r"""Ensure that 'option' is a list of strings. If 'option' is
  215. currently a string, we split it either on /,\s*/ or /\s+/, so
  216. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  217. ["foo", "bar", "baz"].
  218. """
  219. val = getattr(self, option)
  220. if val is None:
  221. return
  222. elif isinstance(val, str):
  223. setattr(self, option, re.split(r',\s*|\s+', val))
  224. else:
  225. if isinstance(val, list):
  226. ok = all(isinstance(v, str) for v in val)
  227. else:
  228. ok = False
  229. if not ok:
  230. raise DistutilsOptionError(
  231. f"'{option}' must be a list of strings (got {val!r})"
  232. )
  233. def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
  234. val = self._ensure_stringlike(option, what, default)
  235. if val is not None and not tester(val):
  236. raise DistutilsOptionError(
  237. ("error in '%s' option: " + error_fmt) % (option, val)
  238. )
  239. def ensure_filename(self, option: str) -> None:
  240. """Ensure that 'option' is the name of an existing file."""
  241. self._ensure_tested_string(
  242. option, os.path.isfile, "filename", "'%s' does not exist or is not a file"
  243. )
  244. def ensure_dirname(self, option: str) -> None:
  245. self._ensure_tested_string(
  246. option,
  247. os.path.isdir,
  248. "directory name",
  249. "'%s' does not exist or is not a directory",
  250. )
  251. # -- Convenience methods for commands ------------------------------
  252. def get_command_name(self) -> str:
  253. if hasattr(self, 'command_name'):
  254. return self.command_name
  255. else:
  256. return self.__class__.__name__
  257. def set_undefined_options(
  258. self, src_cmd: str, *option_pairs: tuple[str, str]
  259. ) -> None:
  260. """Set the values of any "undefined" options from corresponding
  261. option values in some other command object. "Undefined" here means
  262. "is None", which is the convention used to indicate that an option
  263. has not been changed between 'initialize_options()' and
  264. 'finalize_options()'. Usually called from 'finalize_options()' for
  265. options that depend on some other command rather than another
  266. option of the same command. 'src_cmd' is the other command from
  267. which option values will be taken (a command object will be created
  268. for it if necessary); the remaining arguments are
  269. '(src_option,dst_option)' tuples which mean "take the value of
  270. 'src_option' in the 'src_cmd' command object, and copy it to
  271. 'dst_option' in the current command object".
  272. """
  273. # Option_pairs: list of (src_option, dst_option) tuples
  274. src_cmd_obj = self.distribution.get_command_obj(src_cmd)
  275. src_cmd_obj.ensure_finalized()
  276. for src_option, dst_option in option_pairs:
  277. if getattr(self, dst_option) is None:
  278. setattr(self, dst_option, getattr(src_cmd_obj, src_option))
  279. # NOTE: Because distutils is private to Setuptools and not all commands are exposed here,
  280. # not every possible command is enumerated in the signature.
  281. def get_finalized_command(self, command: str, create: bool = True) -> Command:
  282. """Wrapper around Distribution's 'get_command_obj()' method: find
  283. (create if necessary and 'create' is true) the command object for
  284. 'command', call its 'ensure_finalized()' method, and return the
  285. finalized command object.
  286. """
  287. cmd_obj = self.distribution.get_command_obj(command, create)
  288. cmd_obj.ensure_finalized()
  289. return cmd_obj
  290. # XXX rename to 'get_reinitialized_command()'? (should do the
  291. # same in dist.py, if so)
  292. @overload
  293. def reinitialize_command(
  294. self, command: str, reinit_subcommands: bool = False
  295. ) -> Command: ...
  296. @overload
  297. def reinitialize_command(
  298. self, command: _CommandT, reinit_subcommands: bool = False
  299. ) -> _CommandT: ...
  300. def reinitialize_command(
  301. self, command: str | Command, reinit_subcommands=False
  302. ) -> Command:
  303. return self.distribution.reinitialize_command(command, reinit_subcommands)
  304. def run_command(self, command: str) -> None:
  305. """Run some other command: uses the 'run_command()' method of
  306. Distribution, which creates and finalizes the command object if
  307. necessary and then invokes its 'run()' method.
  308. """
  309. self.distribution.run_command(command)
  310. def get_sub_commands(self) -> list[str]:
  311. """Determine the sub-commands that are relevant in the current
  312. distribution (ie., that need to be run). This is based on the
  313. 'sub_commands' class attribute: each tuple in that list may include
  314. a method that we call to determine if the subcommand needs to be
  315. run for the current distribution. Return a list of command names.
  316. """
  317. commands = []
  318. for cmd_name, method in self.sub_commands:
  319. if method is None or method(self):
  320. commands.append(cmd_name)
  321. return commands
  322. # -- External world manipulation -----------------------------------
  323. def warn(self, msg: object) -> None:
  324. log.warning("warning: %s: %s\n", self.get_command_name(), msg)
  325. def execute(
  326. self,
  327. func: Callable[[Unpack[_Ts]], object],
  328. args: tuple[Unpack[_Ts]],
  329. msg: object = None,
  330. level: int = 1,
  331. ) -> None:
  332. util.execute(func, args, msg, dry_run=self.dry_run)
  333. def mkpath(self, name: str, mode: int = 0o777) -> None:
  334. dir_util.mkpath(name, mode, dry_run=self.dry_run)
  335. @overload
  336. def copy_file(
  337. self,
  338. infile: str | os.PathLike[str],
  339. outfile: _StrPathT,
  340. preserve_mode: bool = True,
  341. preserve_times: bool = True,
  342. link: str | None = None,
  343. level: int = 1,
  344. ) -> tuple[_StrPathT | str, bool]: ...
  345. @overload
  346. def copy_file(
  347. self,
  348. infile: bytes | os.PathLike[bytes],
  349. outfile: _BytesPathT,
  350. preserve_mode: bool = True,
  351. preserve_times: bool = True,
  352. link: str | None = None,
  353. level: int = 1,
  354. ) -> tuple[_BytesPathT | bytes, bool]: ...
  355. def copy_file(
  356. self,
  357. infile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  358. outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  359. preserve_mode: bool = True,
  360. preserve_times: bool = True,
  361. link: str | None = None,
  362. level: int = 1,
  363. ) -> tuple[str | os.PathLike[str] | bytes | os.PathLike[bytes], bool]:
  364. """Copy a file respecting verbose, dry-run and force flags. (The
  365. former two default to whatever is in the Distribution object, and
  366. the latter defaults to false for commands that don't define it.)"""
  367. return file_util.copy_file(
  368. infile,
  369. outfile,
  370. preserve_mode,
  371. preserve_times,
  372. not self.force,
  373. link,
  374. dry_run=self.dry_run,
  375. )
  376. def copy_tree(
  377. self,
  378. infile: str | os.PathLike[str],
  379. outfile: str,
  380. preserve_mode: bool = True,
  381. preserve_times: bool = True,
  382. preserve_symlinks: bool = False,
  383. level: int = 1,
  384. ) -> list[str]:
  385. """Copy an entire directory tree respecting verbose, dry-run,
  386. and force flags.
  387. """
  388. return dir_util.copy_tree(
  389. infile,
  390. outfile,
  391. preserve_mode,
  392. preserve_times,
  393. preserve_symlinks,
  394. not self.force,
  395. dry_run=self.dry_run,
  396. )
  397. @overload
  398. def move_file(
  399. self, src: str | os.PathLike[str], dst: _StrPathT, level: int = 1
  400. ) -> _StrPathT | str: ...
  401. @overload
  402. def move_file(
  403. self, src: bytes | os.PathLike[bytes], dst: _BytesPathT, level: int = 1
  404. ) -> _BytesPathT | bytes: ...
  405. def move_file(
  406. self,
  407. src: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  408. dst: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  409. level: int = 1,
  410. ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]:
  411. """Move a file respecting dry-run flag."""
  412. return file_util.move_file(src, dst, dry_run=self.dry_run)
  413. def spawn(
  414. self, cmd: MutableSequence[str], search_path: bool = True, level: int = 1
  415. ) -> None:
  416. """Spawn an external command respecting dry-run flag."""
  417. from distutils.spawn import spawn
  418. spawn(cmd, search_path, dry_run=self.dry_run)
  419. @overload
  420. def make_archive(
  421. self,
  422. base_name: str,
  423. format: str,
  424. root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
  425. base_dir: str | None = None,
  426. owner: str | None = None,
  427. group: str | None = None,
  428. ) -> str: ...
  429. @overload
  430. def make_archive(
  431. self,
  432. base_name: str | os.PathLike[str],
  433. format: str,
  434. root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  435. base_dir: str | None = None,
  436. owner: str | None = None,
  437. group: str | None = None,
  438. ) -> str: ...
  439. def make_archive(
  440. self,
  441. base_name: str | os.PathLike[str],
  442. format: str,
  443. root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None,
  444. base_dir: str | None = None,
  445. owner: str | None = None,
  446. group: str | None = None,
  447. ) -> str:
  448. return archive_util.make_archive(
  449. base_name,
  450. format,
  451. root_dir,
  452. base_dir,
  453. dry_run=self.dry_run,
  454. owner=owner,
  455. group=group,
  456. )
  457. def make_file(
  458. self,
  459. infiles: str | list[str] | tuple[str, ...],
  460. outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes],
  461. func: Callable[[Unpack[_Ts]], object],
  462. args: tuple[Unpack[_Ts]],
  463. exec_msg: object = None,
  464. skip_msg: object = None,
  465. level: int = 1,
  466. ) -> None:
  467. """Special case of 'execute()' for operations that process one or
  468. more input files and generate one output file. Works just like
  469. 'execute()', except the operation is skipped and a different
  470. message printed if 'outfile' already exists and is newer than all
  471. files listed in 'infiles'. If the command defined 'self.force',
  472. and it is true, then the command is unconditionally run -- does no
  473. timestamp checks.
  474. """
  475. if skip_msg is None:
  476. skip_msg = f"skipping {outfile} (inputs unchanged)"
  477. # Allow 'infiles' to be a single string
  478. if isinstance(infiles, str):
  479. infiles = (infiles,)
  480. elif not isinstance(infiles, (list, tuple)):
  481. raise TypeError("'infiles' must be a string, or a list or tuple of strings")
  482. if exec_msg is None:
  483. exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles))
  484. # If 'outfile' must be regenerated (either because it doesn't
  485. # exist, is out-of-date, or the 'force' flag is true) then
  486. # perform the action that presumably regenerates it
  487. if self.force or _modified.newer_group(infiles, outfile):
  488. self.execute(func, args, exec_msg, level)
  489. # Otherwise, print the "skip" message
  490. else:
  491. log.debug(skip_msg)