1
0

dist.py 49 KB

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