dist.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. """distutils.dist
  2. Provides the Distribution class, which represents the module distribution
  3. being built/installed/distributed.
  4. """
  5. from __future__ import annotations
  6. import contextlib
  7. import logging
  8. import os
  9. import pathlib
  10. import re
  11. import sys
  12. import warnings
  13. from collections.abc import Iterable, MutableMapping
  14. from email import message_from_file
  15. from typing import (
  16. IO,
  17. TYPE_CHECKING,
  18. Any,
  19. ClassVar,
  20. Literal,
  21. TypeVar,
  22. Union,
  23. overload,
  24. )
  25. from packaging.utils import canonicalize_name, canonicalize_version
  26. from ._log import log
  27. from .debug import DEBUG
  28. from .errors import (
  29. DistutilsArgError,
  30. DistutilsClassError,
  31. DistutilsModuleError,
  32. DistutilsOptionError,
  33. )
  34. from .fancy_getopt import FancyGetopt, translate_longopt
  35. from .util import check_environ, rfc822_escape, strtobool
  36. if TYPE_CHECKING:
  37. from _typeshed import SupportsWrite
  38. from typing_extensions import TypeAlias
  39. # type-only import because of mutual dependence between these modules
  40. from .cmd import Command
  41. _CommandT = TypeVar("_CommandT", bound="Command")
  42. _OptionsList: TypeAlias = list[
  43. Union[tuple[str, Union[str, None], str, int], tuple[str, Union[str, None], str]]
  44. ]
  45. # Regex to define acceptable Distutils command names. This is not *quite*
  46. # the same as a Python NAME -- I don't allow leading underscores. The fact
  47. # that they're very similar is no coincidence; the default naming scheme is
  48. # to look for a Python module named after the command.
  49. command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
  50. def _ensure_list(value: str | Iterable[str], fieldname) -> str | list[str]:
  51. if isinstance(value, str):
  52. # a string containing comma separated values is okay. It will
  53. # be converted to a list by Distribution.finalize_options().
  54. pass
  55. elif not isinstance(value, list):
  56. # passing a tuple or an iterator perhaps, warn and convert
  57. typename = type(value).__name__
  58. msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"
  59. msg = msg.format(**locals())
  60. log.warning(msg)
  61. value = list(value)
  62. return value
  63. class Distribution:
  64. """The core of the Distutils. Most of the work hiding behind 'setup'
  65. is really done within a Distribution instance, which farms the work out
  66. to the Distutils commands specified on the command line.
  67. Setup scripts will almost never instantiate Distribution directly,
  68. unless the 'setup()' function is totally inadequate to their needs.
  69. However, it is conceivable that a setup script might wish to subclass
  70. Distribution for some specialized purpose, and then pass the subclass
  71. to 'setup()' as the 'distclass' keyword argument. If so, it is
  72. necessary to respect the expectations that 'setup' has of Distribution.
  73. See the code for 'setup()', in core.py, for details.
  74. """
  75. # 'global_options' describes the command-line options that may be
  76. # supplied to the setup script prior to any actual commands.
  77. # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
  78. # these global options. This list should be kept to a bare minimum,
  79. # since every global option is also valid as a command option -- and we
  80. # don't want to pollute the commands with too many options that they
  81. # have minimal control over.
  82. # The fourth entry for verbose means that it can be repeated.
  83. global_options: ClassVar[_OptionsList] = [
  84. ('verbose', 'v', "run verbosely (default)", 1),
  85. ('quiet', 'q', "run quietly (turns verbosity off)"),
  86. ('dry-run', 'n', "don't actually do anything"),
  87. ('help', 'h', "show detailed help message"),
  88. ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
  89. ]
  90. # 'common_usage' is a short (2-3 line) string describing the common
  91. # usage of the setup script.
  92. common_usage: ClassVar[str] = """\
  93. Common commands: (see '--help-commands' for more)
  94. setup.py build will build the package underneath 'build/'
  95. setup.py install will install the package
  96. """
  97. # options that are not propagated to the commands
  98. display_options: ClassVar[_OptionsList] = [
  99. ('help-commands', None, "list all available commands"),
  100. ('name', None, "print package name"),
  101. ('version', 'V', "print package version"),
  102. ('fullname', None, "print <package name>-<version>"),
  103. ('author', None, "print the author's name"),
  104. ('author-email', None, "print the author's email address"),
  105. ('maintainer', None, "print the maintainer's name"),
  106. ('maintainer-email', None, "print the maintainer's email address"),
  107. ('contact', None, "print the maintainer's name if known, else the author's"),
  108. (
  109. 'contact-email',
  110. None,
  111. "print the maintainer's email address if known, else the author's",
  112. ),
  113. ('url', None, "print the URL for this package"),
  114. ('license', None, "print the license of the package"),
  115. ('licence', None, "alias for --license"),
  116. ('description', None, "print the package description"),
  117. ('long-description', None, "print the long package description"),
  118. ('platforms', None, "print the list of platforms"),
  119. ('classifiers', None, "print the list of classifiers"),
  120. ('keywords', None, "print the list of keywords"),
  121. ('provides', None, "print the list of packages/modules provided"),
  122. ('requires', None, "print the list of packages/modules required"),
  123. ('obsoletes', None, "print the list of packages/modules made obsolete"),
  124. ]
  125. display_option_names: ClassVar[list[str]] = [
  126. translate_longopt(x[0]) for x in display_options
  127. ]
  128. # negative options are options that exclude other options
  129. negative_opt: ClassVar[dict[str, str]] = {'quiet': 'verbose'}
  130. # -- Creation/initialization methods -------------------------------
  131. # Can't Unpack a TypedDict with optional properties, so using Any instead
  132. def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None: # noqa: C901
  133. """Construct a new Distribution instance: initialize all the
  134. attributes of a Distribution, and then use 'attrs' (a dictionary
  135. mapping attribute names to values) to assign some of those
  136. attributes their "real" values. (Any attributes not mentioned in
  137. 'attrs' will be assigned to some null value: 0, None, an empty list
  138. or dictionary, etc.) Most importantly, initialize the
  139. 'command_obj' attribute to the empty dictionary; this will be
  140. filled in with real command objects by 'parse_command_line()'.
  141. """
  142. # Default values for our command-line options
  143. self.verbose = True
  144. self.dry_run = False
  145. self.help = False
  146. for attr in self.display_option_names:
  147. setattr(self, attr, False)
  148. # Store the distribution meta-data (name, version, author, and so
  149. # forth) in a separate object -- we're getting to have enough
  150. # information here (and enough command-line options) that it's
  151. # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
  152. # object in a sneaky and underhanded (but efficient!) way.
  153. self.metadata = DistributionMetadata()
  154. for basename in self.metadata._METHOD_BASENAMES:
  155. method_name = "get_" + basename
  156. setattr(self, method_name, getattr(self.metadata, method_name))
  157. # 'cmdclass' maps command names to class objects, so we
  158. # can 1) quickly figure out which class to instantiate when
  159. # we need to create a new command object, and 2) have a way
  160. # for the setup script to override command classes
  161. self.cmdclass: dict[str, type[Command]] = {}
  162. # 'command_packages' is a list of packages in which commands
  163. # are searched for. The factory for command 'foo' is expected
  164. # to be named 'foo' in the module 'foo' in one of the packages
  165. # named here. This list is searched from the left; an error
  166. # is raised if no named package provides the command being
  167. # searched for. (Always access using get_command_packages().)
  168. self.command_packages: str | list[str] | None = None
  169. # 'script_name' and 'script_args' are usually set to sys.argv[0]
  170. # and sys.argv[1:], but they can be overridden when the caller is
  171. # not necessarily a setup script run from the command-line.
  172. self.script_name: str | os.PathLike[str] | None = None
  173. self.script_args: list[str] | None = None
  174. # 'command_options' is where we store command options between
  175. # parsing them (from config files, the command-line, etc.) and when
  176. # they are actually needed -- ie. when the command in question is
  177. # instantiated. It is a dictionary of dictionaries of 2-tuples:
  178. # command_options = { command_name : { option : (source, value) } }
  179. self.command_options: dict[str, dict[str, tuple[str, str]]] = {}
  180. # 'dist_files' is the list of (command, pyversion, file) that
  181. # have been created by any dist commands run so far. This is
  182. # filled regardless of whether the run is dry or not. pyversion
  183. # gives sysconfig.get_python_version() if the dist file is
  184. # specific to a Python version, 'any' if it is good for all
  185. # Python versions on the target platform, and '' for a source
  186. # file. pyversion should not be used to specify minimum or
  187. # maximum required Python versions; use the metainfo for that
  188. # instead.
  189. self.dist_files: list[tuple[str, str, str]] = []
  190. # These options are really the business of various commands, rather
  191. # than of the Distribution itself. We provide aliases for them in
  192. # Distribution as a convenience to the developer.
  193. self.packages = None
  194. self.package_data: dict[str, list[str]] = {}
  195. self.package_dir = None
  196. self.py_modules = None
  197. self.libraries = None
  198. self.headers = None
  199. self.ext_modules = None
  200. self.ext_package = None
  201. self.include_dirs = None
  202. self.extra_path = None
  203. self.scripts = None
  204. self.data_files = None
  205. self.password = ''
  206. # And now initialize bookkeeping stuff that can't be supplied by
  207. # the caller at all. 'command_obj' maps command names to
  208. # Command instances -- that's how we enforce that every command
  209. # class is a singleton.
  210. self.command_obj: dict[str, Command] = {}
  211. # 'have_run' maps command names to boolean values; it keeps track
  212. # of whether we have actually run a particular command, to make it
  213. # cheap to "run" a command whenever we think we might need to -- if
  214. # it's already been done, no need for expensive filesystem
  215. # operations, we just check the 'have_run' dictionary and carry on.
  216. # It's only safe to query 'have_run' for a command class that has
  217. # been instantiated -- a false value will be inserted when the
  218. # command object is created, and replaced with a true value when
  219. # the command is successfully run. Thus it's probably best to use
  220. # '.get()' rather than a straight lookup.
  221. self.have_run: dict[str, bool] = {}
  222. # Now we'll use the attrs dictionary (ultimately, keyword args from
  223. # the setup script) to possibly override any or all of these
  224. # distribution options.
  225. if attrs:
  226. # Pull out the set of command options and work on them
  227. # specifically. Note that this order guarantees that aliased
  228. # command options will override any supplied redundantly
  229. # through the general options dictionary.
  230. options = attrs.get('options')
  231. if options is not None:
  232. del attrs['options']
  233. for command, cmd_options in options.items():
  234. opt_dict = self.get_option_dict(command)
  235. for opt, val in cmd_options.items():
  236. opt_dict[opt] = ("setup script", val)
  237. if 'licence' in attrs:
  238. attrs['license'] = attrs['licence']
  239. del attrs['licence']
  240. msg = "'licence' distribution option is deprecated; use 'license'"
  241. warnings.warn(msg)
  242. # Now work on the rest of the attributes. Any attribute that's
  243. # not already defined is invalid!
  244. for key, val in attrs.items():
  245. if hasattr(self.metadata, "set_" + key):
  246. getattr(self.metadata, "set_" + key)(val)
  247. elif hasattr(self.metadata, key):
  248. setattr(self.metadata, key, val)
  249. elif hasattr(self, key):
  250. setattr(self, key, val)
  251. else:
  252. msg = f"Unknown distribution option: {key!r}"
  253. warnings.warn(msg)
  254. # no-user-cfg is handled before other command line args
  255. # because other args override the config files, and this
  256. # one is needed before we can load the config files.
  257. # If attrs['script_args'] wasn't passed, assume false.
  258. #
  259. # This also make sure we just look at the global options
  260. self.want_user_cfg = True
  261. if self.script_args is not None:
  262. # Coerce any possible iterable from attrs into a list
  263. self.script_args = list(self.script_args)
  264. for arg in self.script_args:
  265. if not arg.startswith('-'):
  266. break
  267. if arg == '--no-user-cfg':
  268. self.want_user_cfg = False
  269. break
  270. self.finalize_options()
  271. def get_option_dict(self, command):
  272. """Get the option dictionary for a given command. If that
  273. command's option dictionary hasn't been created yet, then create it
  274. and return the new dictionary; otherwise, return the existing
  275. option dictionary.
  276. """
  277. dict = self.command_options.get(command)
  278. if dict is None:
  279. dict = self.command_options[command] = {}
  280. return dict
  281. def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None:
  282. from pprint import pformat
  283. if commands is None: # dump all command option dicts
  284. commands = sorted(self.command_options.keys())
  285. if header is not None:
  286. self.announce(indent + header)
  287. indent = indent + " "
  288. if not commands:
  289. self.announce(indent + "no commands known yet")
  290. return
  291. for cmd_name in commands:
  292. opt_dict = self.command_options.get(cmd_name)
  293. if opt_dict is None:
  294. self.announce(indent + f"no option dict for '{cmd_name}' command")
  295. else:
  296. self.announce(indent + f"option dict for '{cmd_name}' command:")
  297. out = pformat(opt_dict)
  298. for line in out.split('\n'):
  299. self.announce(indent + " " + line)
  300. # -- Config file finding/parsing methods ---------------------------
  301. def find_config_files(self):
  302. """Find as many configuration files as should be processed for this
  303. platform, and return a list of filenames in the order in which they
  304. should be parsed. The filenames returned are guaranteed to exist
  305. (modulo nasty race conditions).
  306. There are multiple possible config files:
  307. - distutils.cfg in the Distutils installation directory (i.e.
  308. where the top-level Distutils __inst__.py file lives)
  309. - a file in the user's home directory named .pydistutils.cfg
  310. on Unix and pydistutils.cfg on Windows/Mac; may be disabled
  311. with the ``--no-user-cfg`` option
  312. - setup.cfg in the current directory
  313. - a file named by an environment variable
  314. """
  315. check_environ()
  316. files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]
  317. if DEBUG:
  318. self.announce("using config files: {}".format(', '.join(files)))
  319. return files
  320. def _gen_paths(self):
  321. # The system-wide Distutils config file
  322. sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent
  323. yield sys_dir / "distutils.cfg"
  324. # The per-user config file
  325. prefix = '.' * (os.name == 'posix')
  326. filename = prefix + 'pydistutils.cfg'
  327. if self.want_user_cfg:
  328. with contextlib.suppress(RuntimeError):
  329. yield pathlib.Path('~').expanduser() / filename
  330. # All platforms support local setup.cfg
  331. yield pathlib.Path('setup.cfg')
  332. # Additional config indicated in the environment
  333. with contextlib.suppress(TypeError):
  334. yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG"))
  335. def parse_config_files(self, filenames=None): # noqa: C901
  336. from configparser import ConfigParser
  337. # Ignore install directory options if we have a venv
  338. if sys.prefix != sys.base_prefix:
  339. ignore_options = [
  340. 'install-base',
  341. 'install-platbase',
  342. 'install-lib',
  343. 'install-platlib',
  344. 'install-purelib',
  345. 'install-headers',
  346. 'install-scripts',
  347. 'install-data',
  348. 'prefix',
  349. 'exec-prefix',
  350. 'home',
  351. 'user',
  352. 'root',
  353. ]
  354. else:
  355. ignore_options = []
  356. ignore_options = frozenset(ignore_options)
  357. if filenames is None:
  358. filenames = self.find_config_files()
  359. if DEBUG:
  360. self.announce("Distribution.parse_config_files():")
  361. parser = ConfigParser()
  362. for filename in filenames:
  363. if DEBUG:
  364. self.announce(f" reading {filename}")
  365. parser.read(filename, encoding='utf-8')
  366. for section in parser.sections():
  367. options = parser.options(section)
  368. opt_dict = self.get_option_dict(section)
  369. for opt in options:
  370. if opt != '__name__' and opt not in ignore_options:
  371. val = parser.get(section, opt)
  372. opt = opt.replace('-', '_')
  373. opt_dict[opt] = (filename, val)
  374. # Make the ConfigParser forget everything (so we retain
  375. # the original filenames that options come from)
  376. parser.__init__()
  377. # If there was a "global" section in the config file, use it
  378. # to set Distribution options.
  379. if 'global' in self.command_options:
  380. for opt, (_src, val) in self.command_options['global'].items():
  381. alias = self.negative_opt.get(opt)
  382. try:
  383. if alias:
  384. setattr(self, alias, not strtobool(val))
  385. elif opt in ('verbose', 'dry_run'): # ugh!
  386. setattr(self, opt, strtobool(val))
  387. else:
  388. setattr(self, opt, val)
  389. except ValueError as msg:
  390. raise DistutilsOptionError(msg)
  391. # -- Command-line parsing methods ----------------------------------
  392. def parse_command_line(self):
  393. """Parse the setup script's command line, taken from the
  394. 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
  395. -- see 'setup()' in core.py). This list is first processed for
  396. "global options" -- options that set attributes of the Distribution
  397. instance. Then, it is alternately scanned for Distutils commands
  398. and options for that command. Each new command terminates the
  399. options for the previous command. The allowed options for a
  400. command are determined by the 'user_options' attribute of the
  401. command class -- thus, we have to be able to load command classes
  402. in order to parse the command line. Any error in that 'options'
  403. attribute raises DistutilsGetoptError; any error on the
  404. command-line raises DistutilsArgError. If no Distutils commands
  405. were found on the command line, raises DistutilsArgError. Return
  406. true if command-line was successfully parsed and we should carry
  407. on with executing commands; false if no errors but we shouldn't
  408. execute commands (currently, this only happens if user asks for
  409. help).
  410. """
  411. #
  412. # We now have enough information to show the Macintosh dialog
  413. # that allows the user to interactively specify the "command line".
  414. #
  415. toplevel_options = self._get_toplevel_options()
  416. # We have to parse the command line a bit at a time -- global
  417. # options, then the first command, then its options, and so on --
  418. # because each command will be handled by a different class, and
  419. # the options that are valid for a particular class aren't known
  420. # until we have loaded the command class, which doesn't happen
  421. # until we know what the command is.
  422. self.commands = []
  423. parser = FancyGetopt(toplevel_options + self.display_options)
  424. parser.set_negative_aliases(self.negative_opt)
  425. parser.set_aliases({'licence': 'license'})
  426. args = parser.getopt(args=self.script_args, object=self)
  427. option_order = parser.get_option_order()
  428. logging.getLogger().setLevel(logging.WARN - 10 * self.verbose)
  429. # for display options we return immediately
  430. if self.handle_display_options(option_order):
  431. return
  432. while args:
  433. args = self._parse_command_opts(parser, args)
  434. if args is None: # user asked for help (and got it)
  435. return
  436. # Handle the cases of --help as a "global" option, ie.
  437. # "setup.py --help" and "setup.py --help command ...". For the
  438. # former, we show global options (--verbose, --dry-run, etc.)
  439. # and display-only options (--name, --version, etc.); for the
  440. # latter, we omit the display-only options and show help for
  441. # each command listed on the command line.
  442. if self.help:
  443. self._show_help(
  444. parser, display_options=len(self.commands) == 0, commands=self.commands
  445. )
  446. return
  447. # Oops, no commands found -- an end-user error
  448. if not self.commands:
  449. raise DistutilsArgError("no commands supplied")
  450. # All is well: return true
  451. return True
  452. def _get_toplevel_options(self):
  453. """Return the non-display options recognized at the top level.
  454. This includes options that are recognized *only* at the top
  455. level as well as options recognized for commands.
  456. """
  457. return self.global_options + [
  458. (
  459. "command-packages=",
  460. None,
  461. "list of packages that provide distutils commands",
  462. ),
  463. ]
  464. def _parse_command_opts(self, parser, args): # noqa: C901
  465. """Parse the command-line options for a single command.
  466. 'parser' must be a FancyGetopt instance; 'args' must be the list
  467. of arguments, starting with the current command (whose options
  468. we are about to parse). Returns a new version of 'args' with
  469. the next command at the front of the list; will be the empty
  470. list if there are no more commands on the command line. Returns
  471. None if the user asked for help on this command.
  472. """
  473. # late import because of mutual dependence between these modules
  474. from distutils.cmd import Command
  475. # Pull the current command from the head of the command line
  476. command = args[0]
  477. if not command_re.match(command):
  478. raise SystemExit(f"invalid command name '{command}'")
  479. self.commands.append(command)
  480. # Dig up the command class that implements this command, so we
  481. # 1) know that it's a valid command, and 2) know which options
  482. # it takes.
  483. try:
  484. cmd_class = self.get_command_class(command)
  485. except DistutilsModuleError as msg:
  486. raise DistutilsArgError(msg)
  487. # Require that the command class be derived from Command -- want
  488. # to be sure that the basic "command" interface is implemented.
  489. if not issubclass(cmd_class, Command):
  490. raise DistutilsClassError(
  491. f"command class {cmd_class} must subclass Command"
  492. )
  493. # Also make sure that the command object provides a list of its
  494. # known options.
  495. if not (
  496. hasattr(cmd_class, 'user_options')
  497. and isinstance(cmd_class.user_options, list)
  498. ):
  499. msg = (
  500. "command class %s must provide "
  501. "'user_options' attribute (a list of tuples)"
  502. )
  503. raise DistutilsClassError(msg % cmd_class)
  504. # If the command class has a list of negative alias options,
  505. # merge it in with the global negative aliases.
  506. negative_opt = self.negative_opt
  507. if hasattr(cmd_class, 'negative_opt'):
  508. negative_opt = negative_opt.copy()
  509. negative_opt.update(cmd_class.negative_opt)
  510. # Check for help_options in command class. They have a different
  511. # format (tuple of four) so we need to preprocess them here.
  512. if hasattr(cmd_class, 'help_options') and isinstance(
  513. cmd_class.help_options, list
  514. ):
  515. help_options = fix_help_options(cmd_class.help_options)
  516. else:
  517. help_options = []
  518. # All commands support the global options too, just by adding
  519. # in 'global_options'.
  520. parser.set_option_table(
  521. self.global_options + cmd_class.user_options + help_options
  522. )
  523. parser.set_negative_aliases(negative_opt)
  524. (args, opts) = parser.getopt(args[1:])
  525. if hasattr(opts, 'help') and opts.help:
  526. self._show_help(parser, display_options=False, commands=[cmd_class])
  527. return
  528. if hasattr(cmd_class, 'help_options') and isinstance(
  529. cmd_class.help_options, list
  530. ):
  531. help_option_found = 0
  532. for help_option, _short, _desc, func in cmd_class.help_options:
  533. if hasattr(opts, parser.get_attr_name(help_option)):
  534. help_option_found = 1
  535. if callable(func):
  536. func()
  537. else:
  538. raise DistutilsClassError(
  539. f"invalid help function {func!r} for help option '{help_option}': "
  540. "must be a callable object (function, etc.)"
  541. )
  542. if help_option_found:
  543. return
  544. # Put the options from the command-line into their official
  545. # holding pen, the 'command_options' dictionary.
  546. opt_dict = self.get_option_dict(command)
  547. for name, value in vars(opts).items():
  548. opt_dict[name] = ("command line", value)
  549. return args
  550. def finalize_options(self) -> None:
  551. """Set final values for all the options on the Distribution
  552. instance, analogous to the .finalize_options() method of Command
  553. objects.
  554. """
  555. for attr in ('keywords', 'platforms'):
  556. value = getattr(self.metadata, attr)
  557. if value is None:
  558. continue
  559. if isinstance(value, str):
  560. value = [elm.strip() for elm in value.split(',')]
  561. setattr(self.metadata, attr, value)
  562. def _show_help(
  563. self, parser, global_options=True, display_options=True, commands: Iterable = ()
  564. ):
  565. """Show help for the setup script command-line in the form of
  566. several lists of command-line options. 'parser' should be a
  567. FancyGetopt instance; do not expect it to be returned in the
  568. same state, as its option table will be reset to make it
  569. generate the correct help text.
  570. If 'global_options' is true, lists the global options:
  571. --verbose, --dry-run, etc. If 'display_options' is true, lists
  572. the "display-only" options: --name, --version, etc. Finally,
  573. lists per-command help for every command name or command class
  574. in 'commands'.
  575. """
  576. # late import because of mutual dependence between these modules
  577. from distutils.cmd import Command
  578. from distutils.core import gen_usage
  579. if global_options:
  580. if display_options:
  581. options = self._get_toplevel_options()
  582. else:
  583. options = self.global_options
  584. parser.set_option_table(options)
  585. parser.print_help(self.common_usage + "\nGlobal options:")
  586. print()
  587. if display_options:
  588. parser.set_option_table(self.display_options)
  589. parser.print_help(
  590. "Information display options (just display information, ignore any commands)"
  591. )
  592. print()
  593. for command in commands:
  594. if isinstance(command, type) and issubclass(command, Command):
  595. klass = command
  596. else:
  597. klass = self.get_command_class(command)
  598. if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):
  599. parser.set_option_table(
  600. klass.user_options + fix_help_options(klass.help_options)
  601. )
  602. else:
  603. parser.set_option_table(klass.user_options)
  604. parser.print_help(f"Options for '{klass.__name__}' command:")
  605. print()
  606. print(gen_usage(self.script_name))
  607. def handle_display_options(self, option_order):
  608. """If there were any non-global "display-only" options
  609. (--help-commands or the metadata display options) on the command
  610. line, display the requested info and return true; else return
  611. false.
  612. """
  613. from distutils.core import gen_usage
  614. # User just wants a list of commands -- we'll print it out and stop
  615. # processing now (ie. if they ran "setup --help-commands foo bar",
  616. # we ignore "foo bar").
  617. if self.help_commands:
  618. self.print_commands()
  619. print()
  620. print(gen_usage(self.script_name))
  621. return 1
  622. # If user supplied any of the "display metadata" options, then
  623. # display that metadata in the order in which the user supplied the
  624. # metadata options.
  625. any_display_options = 0
  626. is_display_option = set()
  627. for option in self.display_options:
  628. is_display_option.add(option[0])
  629. for opt, val in option_order:
  630. if val and opt in is_display_option:
  631. opt = translate_longopt(opt)
  632. value = getattr(self.metadata, "get_" + opt)()
  633. if opt in ('keywords', 'platforms'):
  634. print(','.join(value))
  635. elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):
  636. print('\n'.join(value))
  637. else:
  638. print(value)
  639. any_display_options = 1
  640. return any_display_options
  641. def print_command_list(self, commands, header, max_length) -> None:
  642. """Print a subset of the list of all commands -- used by
  643. 'print_commands()'.
  644. """
  645. print(header + ":")
  646. for cmd in commands:
  647. klass = self.cmdclass.get(cmd)
  648. if not klass:
  649. klass = self.get_command_class(cmd)
  650. try:
  651. description = klass.description
  652. except AttributeError:
  653. description = "(no description available)"
  654. print(f" {cmd:<{max_length}} {description}")
  655. def print_commands(self) -> None:
  656. """Print out a help message listing all available commands with a
  657. description of each. The list is divided into "standard commands"
  658. (listed in distutils.command.__all__) and "extra commands"
  659. (mentioned in self.cmdclass, but not a standard command). The
  660. descriptions come from the command class attribute
  661. 'description'.
  662. """
  663. import distutils.command
  664. std_commands = distutils.command.__all__
  665. is_std = set(std_commands)
  666. extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
  667. max_length = 0
  668. for cmd in std_commands + extra_commands:
  669. if len(cmd) > max_length:
  670. max_length = len(cmd)
  671. self.print_command_list(std_commands, "Standard commands", max_length)
  672. if extra_commands:
  673. print()
  674. self.print_command_list(extra_commands, "Extra commands", max_length)
  675. def get_command_list(self):
  676. """Get a list of (command, description) tuples.
  677. The list is divided into "standard commands" (listed in
  678. distutils.command.__all__) and "extra commands" (mentioned in
  679. self.cmdclass, but not a standard command). The descriptions come
  680. from the command class attribute 'description'.
  681. """
  682. # Currently this is only used on Mac OS, for the Mac-only GUI
  683. # Distutils interface (by Jack Jansen)
  684. import distutils.command
  685. std_commands = distutils.command.__all__
  686. is_std = set(std_commands)
  687. extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std]
  688. rv = []
  689. for cmd in std_commands + extra_commands:
  690. klass = self.cmdclass.get(cmd)
  691. if not klass:
  692. klass = self.get_command_class(cmd)
  693. try:
  694. description = klass.description
  695. except AttributeError:
  696. description = "(no description available)"
  697. rv.append((cmd, description))
  698. return rv
  699. # -- Command class/object methods ----------------------------------
  700. def get_command_packages(self):
  701. """Return a list of packages from which commands are loaded."""
  702. pkgs = self.command_packages
  703. if not isinstance(pkgs, list):
  704. if pkgs is None:
  705. pkgs = ''
  706. pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
  707. if "distutils.command" not in pkgs:
  708. pkgs.insert(0, "distutils.command")
  709. self.command_packages = pkgs
  710. return pkgs
  711. def get_command_class(self, command: str) -> type[Command]:
  712. """Return the class that implements the Distutils command named by
  713. 'command'. First we check the 'cmdclass' dictionary; if the
  714. command is mentioned there, we fetch the class object from the
  715. dictionary and return it. Otherwise we load the command module
  716. ("distutils.command." + command) and fetch the command class from
  717. the module. The loaded class is also stored in 'cmdclass'
  718. to speed future calls to 'get_command_class()'.
  719. Raises DistutilsModuleError if the expected module could not be
  720. found, or if that module does not define the expected class.
  721. """
  722. klass = self.cmdclass.get(command)
  723. if klass:
  724. return klass
  725. for pkgname in self.get_command_packages():
  726. module_name = f"{pkgname}.{command}"
  727. klass_name = command
  728. try:
  729. __import__(module_name)
  730. module = sys.modules[module_name]
  731. except ImportError:
  732. continue
  733. try:
  734. klass = getattr(module, klass_name)
  735. except AttributeError:
  736. raise DistutilsModuleError(
  737. f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')"
  738. )
  739. self.cmdclass[command] = klass
  740. return klass
  741. raise DistutilsModuleError(f"invalid command '{command}'")
  742. @overload
  743. def get_command_obj(
  744. self, command: str, create: Literal[True] = True
  745. ) -> Command: ...
  746. @overload
  747. def get_command_obj(
  748. self, command: str, create: Literal[False]
  749. ) -> Command | None: ...
  750. def get_command_obj(self, command: str, create: bool = True) -> Command | None:
  751. """Return the command object for 'command'. Normally this object
  752. is cached on a previous call to 'get_command_obj()'; if no command
  753. object for 'command' is in the cache, then we either create and
  754. return it (if 'create' is true) or return None.
  755. """
  756. cmd_obj = self.command_obj.get(command)
  757. if not cmd_obj and create:
  758. if DEBUG:
  759. self.announce(
  760. "Distribution.get_command_obj(): "
  761. f"creating '{command}' command object"
  762. )
  763. klass = self.get_command_class(command)
  764. cmd_obj = self.command_obj[command] = klass(self)
  765. self.have_run[command] = False
  766. # Set any options that were supplied in config files
  767. # or on the command line. (NB. support for error
  768. # reporting is lame here: any errors aren't reported
  769. # until 'finalize_options()' is called, which means
  770. # we won't report the source of the error.)
  771. options = self.command_options.get(command)
  772. if options:
  773. self._set_command_options(cmd_obj, options)
  774. return cmd_obj
  775. def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
  776. """Set the options for 'command_obj' from 'option_dict'. Basically
  777. this means copying elements of a dictionary ('option_dict') to
  778. attributes of an instance ('command').
  779. 'command_obj' must be a Command instance. If 'option_dict' is not
  780. supplied, uses the standard option dictionary for this command
  781. (from 'self.command_options').
  782. """
  783. command_name = command_obj.get_command_name()
  784. if option_dict is None:
  785. option_dict = self.get_option_dict(command_name)
  786. if DEBUG:
  787. self.announce(f" setting options for '{command_name}' command:")
  788. for option, (source, value) in option_dict.items():
  789. if DEBUG:
  790. self.announce(f" {option} = {value} (from {source})")
  791. try:
  792. bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
  793. except AttributeError:
  794. bool_opts = []
  795. try:
  796. neg_opt = command_obj.negative_opt
  797. except AttributeError:
  798. neg_opt = {}
  799. try:
  800. is_string = isinstance(value, str)
  801. if option in neg_opt and is_string:
  802. setattr(command_obj, neg_opt[option], not strtobool(value))
  803. elif option in bool_opts and is_string:
  804. setattr(command_obj, option, strtobool(value))
  805. elif hasattr(command_obj, option):
  806. setattr(command_obj, option, value)
  807. else:
  808. raise DistutilsOptionError(
  809. f"error in {source}: command '{command_name}' has no such option '{option}'"
  810. )
  811. except ValueError as msg:
  812. raise DistutilsOptionError(msg)
  813. @overload
  814. def reinitialize_command(
  815. self, command: str, reinit_subcommands: bool = False
  816. ) -> Command: ...
  817. @overload
  818. def reinitialize_command(
  819. self, command: _CommandT, reinit_subcommands: bool = False
  820. ) -> _CommandT: ...
  821. def reinitialize_command(
  822. self, command: str | Command, reinit_subcommands=False
  823. ) -> Command:
  824. """Reinitializes a command to the state it was in when first
  825. returned by 'get_command_obj()': ie., initialized but not yet
  826. finalized. This provides the opportunity to sneak option
  827. values in programmatically, overriding or supplementing
  828. user-supplied values from the config files and command line.
  829. You'll have to re-finalize the command object (by calling
  830. 'finalize_options()' or 'ensure_finalized()') before using it for
  831. real.
  832. 'command' should be a command name (string) or command object. If
  833. 'reinit_subcommands' is true, also reinitializes the command's
  834. sub-commands, as declared by the 'sub_commands' class attribute (if
  835. it has one). See the "install" command for an example. Only
  836. reinitializes the sub-commands that actually matter, ie. those
  837. whose test predicates return true.
  838. Returns the reinitialized command object.
  839. """
  840. from distutils.cmd import Command
  841. if not isinstance(command, Command):
  842. command_name = command
  843. command = self.get_command_obj(command_name)
  844. else:
  845. command_name = command.get_command_name()
  846. if not command.finalized:
  847. return command
  848. command.initialize_options()
  849. command.finalized = False
  850. self.have_run[command_name] = False
  851. self._set_command_options(command)
  852. if reinit_subcommands:
  853. for sub in command.get_sub_commands():
  854. self.reinitialize_command(sub, reinit_subcommands)
  855. return command
  856. # -- Methods that operate on the Distribution ----------------------
  857. def announce(self, msg, level: int = logging.INFO) -> None:
  858. log.log(level, msg)
  859. def run_commands(self) -> None:
  860. """Run each command that was seen on the setup script command line.
  861. Uses the list of commands found and cache of command objects
  862. created by 'get_command_obj()'.
  863. """
  864. for cmd in self.commands:
  865. self.run_command(cmd)
  866. # -- Methods that operate on its Commands --------------------------
  867. def run_command(self, command: str) -> None:
  868. """Do whatever it takes to run a command (including nothing at all,
  869. if the command has already been run). Specifically: if we have
  870. already created and run the command named by 'command', return
  871. silently without doing anything. If the command named by 'command'
  872. doesn't even have a command object yet, create one. Then invoke
  873. 'run()' on that command object (or an existing one).
  874. """
  875. # Already been here, done that? then return silently.
  876. if self.have_run.get(command):
  877. return
  878. log.info("running %s", command)
  879. cmd_obj = self.get_command_obj(command)
  880. cmd_obj.ensure_finalized()
  881. cmd_obj.run()
  882. self.have_run[command] = True
  883. # -- Distribution query methods ------------------------------------
  884. def has_pure_modules(self) -> bool:
  885. return len(self.packages or self.py_modules or []) > 0
  886. def has_ext_modules(self) -> bool:
  887. return self.ext_modules and len(self.ext_modules) > 0
  888. def has_c_libraries(self) -> bool:
  889. return self.libraries and len(self.libraries) > 0
  890. def has_modules(self) -> bool:
  891. return self.has_pure_modules() or self.has_ext_modules()
  892. def has_headers(self) -> bool:
  893. return self.headers and len(self.headers) > 0
  894. def has_scripts(self) -> bool:
  895. return self.scripts and len(self.scripts) > 0
  896. def has_data_files(self) -> bool:
  897. return self.data_files and len(self.data_files) > 0
  898. def is_pure(self) -> bool:
  899. return (
  900. self.has_pure_modules()
  901. and not self.has_ext_modules()
  902. and not self.has_c_libraries()
  903. )
  904. # -- Metadata query methods ----------------------------------------
  905. # If you're looking for 'get_name()', 'get_version()', and so forth,
  906. # they are defined in a sneaky way: the constructor binds self.get_XXX
  907. # to self.metadata.get_XXX. The actual code is in the
  908. # DistributionMetadata class, below.
  909. if TYPE_CHECKING:
  910. # Unfortunately this means we need to specify them manually or not expose statically
  911. def _(self) -> None:
  912. self.get_name = self.metadata.get_name
  913. self.get_version = self.metadata.get_version
  914. self.get_fullname = self.metadata.get_fullname
  915. self.get_author = self.metadata.get_author
  916. self.get_author_email = self.metadata.get_author_email
  917. self.get_maintainer = self.metadata.get_maintainer
  918. self.get_maintainer_email = self.metadata.get_maintainer_email
  919. self.get_contact = self.metadata.get_contact
  920. self.get_contact_email = self.metadata.get_contact_email
  921. self.get_url = self.metadata.get_url
  922. self.get_license = self.metadata.get_license
  923. self.get_licence = self.metadata.get_licence
  924. self.get_description = self.metadata.get_description
  925. self.get_long_description = self.metadata.get_long_description
  926. self.get_keywords = self.metadata.get_keywords
  927. self.get_platforms = self.metadata.get_platforms
  928. self.get_classifiers = self.metadata.get_classifiers
  929. self.get_download_url = self.metadata.get_download_url
  930. self.get_requires = self.metadata.get_requires
  931. self.get_provides = self.metadata.get_provides
  932. self.get_obsoletes = self.metadata.get_obsoletes
  933. # Default attributes generated in __init__ from self.display_option_names
  934. help_commands: bool
  935. name: str | Literal[False]
  936. version: str | Literal[False]
  937. fullname: str | Literal[False]
  938. author: str | Literal[False]
  939. author_email: str | Literal[False]
  940. maintainer: str | Literal[False]
  941. maintainer_email: str | Literal[False]
  942. contact: str | Literal[False]
  943. contact_email: str | Literal[False]
  944. url: str | Literal[False]
  945. license: str | Literal[False]
  946. licence: str | Literal[False]
  947. description: str | Literal[False]
  948. long_description: str | Literal[False]
  949. platforms: str | list[str] | Literal[False]
  950. classifiers: str | list[str] | Literal[False]
  951. keywords: str | list[str] | Literal[False]
  952. provides: list[str] | Literal[False]
  953. requires: list[str] | Literal[False]
  954. obsoletes: list[str] | Literal[False]
  955. class DistributionMetadata:
  956. """Dummy class to hold the distribution meta-data: name, version,
  957. author, and so forth.
  958. """
  959. _METHOD_BASENAMES = (
  960. "name",
  961. "version",
  962. "author",
  963. "author_email",
  964. "maintainer",
  965. "maintainer_email",
  966. "url",
  967. "license",
  968. "description",
  969. "long_description",
  970. "keywords",
  971. "platforms",
  972. "fullname",
  973. "contact",
  974. "contact_email",
  975. "classifiers",
  976. "download_url",
  977. # PEP 314
  978. "provides",
  979. "requires",
  980. "obsoletes",
  981. )
  982. def __init__(
  983. self, path: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None
  984. ) -> None:
  985. if path is not None:
  986. self.read_pkg_file(open(path))
  987. else:
  988. self.name: str | None = None
  989. self.version: str | None = None
  990. self.author: str | None = None
  991. self.author_email: str | None = None
  992. self.maintainer: str | None = None
  993. self.maintainer_email: str | None = None
  994. self.url: str | None = None
  995. self.license: str | None = None
  996. self.description: str | None = None
  997. self.long_description: str | None = None
  998. self.keywords: str | list[str] | None = None
  999. self.platforms: str | list[str] | None = None
  1000. self.classifiers: str | list[str] | None = None
  1001. self.download_url: str | None = None
  1002. # PEP 314
  1003. self.provides: str | list[str] | None = None
  1004. self.requires: str | list[str] | None = None
  1005. self.obsoletes: str | list[str] | None = None
  1006. def read_pkg_file(self, file: IO[str]) -> None:
  1007. """Reads the metadata values from a file object."""
  1008. msg = message_from_file(file)
  1009. def _read_field(name: str) -> str | None:
  1010. value = msg[name]
  1011. if value and value != "UNKNOWN":
  1012. return value
  1013. return None
  1014. def _read_list(name):
  1015. values = msg.get_all(name, None)
  1016. if values == []:
  1017. return None
  1018. return values
  1019. metadata_version = msg['metadata-version']
  1020. self.name = _read_field('name')
  1021. self.version = _read_field('version')
  1022. self.description = _read_field('summary')
  1023. # we are filling author only.
  1024. self.author = _read_field('author')
  1025. self.maintainer = None
  1026. self.author_email = _read_field('author-email')
  1027. self.maintainer_email = None
  1028. self.url = _read_field('home-page')
  1029. self.license = _read_field('license')
  1030. if 'download-url' in msg:
  1031. self.download_url = _read_field('download-url')
  1032. else:
  1033. self.download_url = None
  1034. self.long_description = _read_field('description')
  1035. self.description = _read_field('summary')
  1036. if 'keywords' in msg:
  1037. self.keywords = _read_field('keywords').split(',')
  1038. self.platforms = _read_list('platform')
  1039. self.classifiers = _read_list('classifier')
  1040. # PEP 314 - these fields only exist in 1.1
  1041. if metadata_version == '1.1':
  1042. self.requires = _read_list('requires')
  1043. self.provides = _read_list('provides')
  1044. self.obsoletes = _read_list('obsoletes')
  1045. else:
  1046. self.requires = None
  1047. self.provides = None
  1048. self.obsoletes = None
  1049. def write_pkg_info(self, base_dir: str | os.PathLike[str]) -> None:
  1050. """Write the PKG-INFO file into the release tree."""
  1051. with open(
  1052. os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'
  1053. ) as pkg_info:
  1054. self.write_pkg_file(pkg_info)
  1055. def write_pkg_file(self, file: SupportsWrite[str]) -> None:
  1056. """Write the PKG-INFO format data to a file object."""
  1057. version = '1.0'
  1058. if (
  1059. self.provides
  1060. or self.requires
  1061. or self.obsoletes
  1062. or self.classifiers
  1063. or self.download_url
  1064. ):
  1065. version = '1.1'
  1066. # required fields
  1067. file.write(f'Metadata-Version: {version}\n')
  1068. file.write(f'Name: {self.get_name()}\n')
  1069. file.write(f'Version: {self.get_version()}\n')
  1070. def maybe_write(header, val):
  1071. if val:
  1072. file.write(f"{header}: {val}\n")
  1073. # optional fields
  1074. maybe_write("Summary", self.get_description())
  1075. maybe_write("Home-page", self.get_url())
  1076. maybe_write("Author", self.get_contact())
  1077. maybe_write("Author-email", self.get_contact_email())
  1078. maybe_write("License", self.get_license())
  1079. maybe_write("Download-URL", self.download_url)
  1080. maybe_write("Description", rfc822_escape(self.get_long_description() or ""))
  1081. maybe_write("Keywords", ",".join(self.get_keywords()))
  1082. self._write_list(file, 'Platform', self.get_platforms())
  1083. self._write_list(file, 'Classifier', self.get_classifiers())
  1084. # PEP 314
  1085. self._write_list(file, 'Requires', self.get_requires())
  1086. self._write_list(file, 'Provides', self.get_provides())
  1087. self._write_list(file, 'Obsoletes', self.get_obsoletes())
  1088. def _write_list(self, file, name, values):
  1089. values = values or []
  1090. for value in values:
  1091. file.write(f'{name}: {value}\n')
  1092. # -- Metadata query methods ----------------------------------------
  1093. def get_name(self) -> str:
  1094. return self.name or "UNKNOWN"
  1095. def get_version(self) -> str:
  1096. return self.version or "0.0.0"
  1097. def get_fullname(self) -> str:
  1098. return self._fullname(self.get_name(), self.get_version())
  1099. @staticmethod
  1100. def _fullname(name: str, version: str) -> str:
  1101. """
  1102. >>> DistributionMetadata._fullname('setup.tools', '1.0-2')
  1103. 'setup_tools-1.0.post2'
  1104. >>> DistributionMetadata._fullname('setup-tools', '1.2post2')
  1105. 'setup_tools-1.2.post2'
  1106. >>> DistributionMetadata._fullname('setup-tools', '1.0-r2')
  1107. 'setup_tools-1.0.post2'
  1108. >>> DistributionMetadata._fullname('setup.tools', '1.0.post')
  1109. 'setup_tools-1.0.post0'
  1110. >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1')
  1111. 'setup_tools-1.0+ubuntu.1'
  1112. """
  1113. return "{}-{}".format(
  1114. canonicalize_name(name).replace('-', '_'),
  1115. canonicalize_version(version, strip_trailing_zero=False),
  1116. )
  1117. def get_author(self) -> str | None:
  1118. return self.author
  1119. def get_author_email(self) -> str | None:
  1120. return self.author_email
  1121. def get_maintainer(self) -> str | None:
  1122. return self.maintainer
  1123. def get_maintainer_email(self) -> str | None:
  1124. return self.maintainer_email
  1125. def get_contact(self) -> str | None:
  1126. return self.maintainer or self.author
  1127. def get_contact_email(self) -> str | None:
  1128. return self.maintainer_email or self.author_email
  1129. def get_url(self) -> str | None:
  1130. return self.url
  1131. def get_license(self) -> str | None:
  1132. return self.license
  1133. get_licence = get_license
  1134. def get_description(self) -> str | None:
  1135. return self.description
  1136. def get_long_description(self) -> str | None:
  1137. return self.long_description
  1138. def get_keywords(self) -> str | list[str]:
  1139. return self.keywords or []
  1140. def set_keywords(self, value: str | Iterable[str]) -> None:
  1141. self.keywords = _ensure_list(value, 'keywords')
  1142. def get_platforms(self) -> str | list[str] | None:
  1143. return self.platforms
  1144. def set_platforms(self, value: str | Iterable[str]) -> None:
  1145. self.platforms = _ensure_list(value, 'platforms')
  1146. def get_classifiers(self) -> str | list[str]:
  1147. return self.classifiers or []
  1148. def set_classifiers(self, value: str | Iterable[str]) -> None:
  1149. self.classifiers = _ensure_list(value, 'classifiers')
  1150. def get_download_url(self) -> str | None:
  1151. return self.download_url
  1152. # PEP 314
  1153. def get_requires(self) -> str | list[str]:
  1154. return self.requires or []
  1155. def set_requires(self, value: Iterable[str]) -> None:
  1156. import distutils.versionpredicate
  1157. for v in value:
  1158. distutils.versionpredicate.VersionPredicate(v)
  1159. self.requires = list(value)
  1160. def get_provides(self) -> str | list[str]:
  1161. return self.provides or []
  1162. def set_provides(self, value: Iterable[str]) -> None:
  1163. value = [v.strip() for v in value]
  1164. for v in value:
  1165. import distutils.versionpredicate
  1166. distutils.versionpredicate.split_provision(v)
  1167. self.provides = value
  1168. def get_obsoletes(self) -> str | list[str]:
  1169. return self.obsoletes or []
  1170. def set_obsoletes(self, value: Iterable[str]) -> None:
  1171. import distutils.versionpredicate
  1172. for v in value:
  1173. distutils.versionpredicate.VersionPredicate(v)
  1174. self.obsoletes = list(value)
  1175. def fix_help_options(options):
  1176. """Convert a 4-tuple 'help_options' list as found in various command
  1177. classes to the 3-tuple form required by FancyGetopt.
  1178. """
  1179. return [opt[0:3] for opt in options]