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