25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

142 lines
5.0 KiB

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