dist.py 49 KB

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