cmd.py 21 KB

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