dist.py 54 KB

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