setopt.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from distutils.util import convert_path
  2. from distutils import log
  3. from distutils.errors import DistutilsOptionError
  4. import distutils
  5. import os
  6. import configparser
  7. from setuptools import Command
  8. __all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
  9. def config_file(kind="local"):
  10. """Get the filename of the distutils, local, global, or per-user config
  11. `kind` must be one of "local", "global", or "user"
  12. """
  13. if kind == 'local':
  14. return 'setup.cfg'
  15. if kind == 'global':
  16. return os.path.join(os.path.dirname(distutils.__file__), 'distutils.cfg')
  17. if kind == 'user':
  18. dot = os.name == 'posix' and '.' or ''
  19. return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot))
  20. raise ValueError("config_file() type must be 'local', 'global', or 'user'", kind)
  21. def edit_config(filename, settings, dry_run=False):
  22. """Edit a configuration file to include `settings`
  23. `settings` is a dictionary of dictionaries or ``None`` values, keyed by
  24. command/section name. A ``None`` value means to delete the entire section,
  25. while a dictionary lists settings to be changed or deleted in that section.
  26. A setting of ``None`` means to delete that setting.
  27. """
  28. log.debug("Reading configuration from %s", filename)
  29. opts = configparser.RawConfigParser()
  30. opts.optionxform = lambda x: x
  31. opts.read([filename])
  32. for section, options in settings.items():
  33. if options is None:
  34. log.info("Deleting section [%s] from %s", section, filename)
  35. opts.remove_section(section)
  36. else:
  37. if not opts.has_section(section):
  38. log.debug("Adding new section [%s] to %s", section, filename)
  39. opts.add_section(section)
  40. for option, value in options.items():
  41. if value is None:
  42. log.debug("Deleting %s.%s from %s", section, option, filename)
  43. opts.remove_option(section, option)
  44. if not opts.options(section):
  45. log.info(
  46. "Deleting empty [%s] section from %s", section, filename
  47. )
  48. opts.remove_section(section)
  49. else:
  50. log.debug(
  51. "Setting %s.%s to %r in %s", section, option, value, filename
  52. )
  53. opts.set(section, option, value)
  54. log.info("Writing %s", filename)
  55. if not dry_run:
  56. with open(filename, 'w') as f:
  57. opts.write(f)
  58. class option_base(Command):
  59. """Abstract base class for commands that mess with config files"""
  60. user_options = [
  61. ('global-config', 'g', "save options to the site-wide distutils.cfg file"),
  62. ('user-config', 'u', "save options to the current user's pydistutils.cfg file"),
  63. ('filename=', 'f', "configuration file to use (default=setup.cfg)"),
  64. ]
  65. boolean_options = [
  66. 'global-config',
  67. 'user-config',
  68. ]
  69. def initialize_options(self):
  70. self.global_config = None
  71. self.user_config = None
  72. self.filename = None
  73. def finalize_options(self):
  74. filenames = []
  75. if self.global_config:
  76. filenames.append(config_file('global'))
  77. if self.user_config:
  78. filenames.append(config_file('user'))
  79. if self.filename is not None:
  80. filenames.append(self.filename)
  81. if not filenames:
  82. filenames.append(config_file('local'))
  83. if len(filenames) > 1:
  84. raise DistutilsOptionError(
  85. "Must specify only one configuration file option", filenames
  86. )
  87. (self.filename,) = filenames
  88. class setopt(option_base):
  89. """Save command-line options to a file"""
  90. description = "set an option in setup.cfg or another config file"
  91. user_options = [
  92. ('command=', 'c', 'command to set an option for'),
  93. ('option=', 'o', 'option to set'),
  94. ('set-value=', 's', 'value of the option'),
  95. ('remove', 'r', 'remove (unset) the value'),
  96. ] + option_base.user_options
  97. boolean_options = option_base.boolean_options + ['remove']
  98. def initialize_options(self):
  99. option_base.initialize_options(self)
  100. self.command = None
  101. self.option = None
  102. self.set_value = None
  103. self.remove = None
  104. def finalize_options(self):
  105. option_base.finalize_options(self)
  106. if self.command is None or self.option is None:
  107. raise DistutilsOptionError("Must specify --command *and* --option")
  108. if self.set_value is None and not self.remove:
  109. raise DistutilsOptionError("Must specify --set-value or --remove")
  110. def run(self):
  111. edit_config(
  112. self.filename,
  113. {self.command: {self.option.replace('-', '_'): self.set_value}},
  114. self.dry_run,
  115. )