Aluode/PerceptionLabPortable
0
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, dry_run=False):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 if not dry_run:68 with open(filename, 'w', encoding="utf-8") as f:69 opts.write(f)70 71 72class option_base(Command):73 """Abstract base class for commands that mess with config files"""74 75 user_options = [76 ('global-config', 'g', "save options to the site-wide distutils.cfg file"),77 ('user-config', 'u', "save options to the current user's pydistutils.cfg file"),78 ('filename=', 'f', "configuration file to use (default=setup.cfg)"),79 ]80 81 boolean_options = [82 'global-config',83 'user-config',84 ]85 86 def initialize_options(self):87 self.global_config = None88 self.user_config = None89 self.filename = None90 91 def finalize_options(self):92 filenames = []93 if self.global_config:94 filenames.append(config_file('global'))95 if self.user_config:96 filenames.append(config_file('user'))97 if self.filename is not None:98 filenames.append(self.filename)99 if not filenames:100 filenames.append(config_file('local'))101 if len(filenames) > 1:102 raise DistutilsOptionError(103 "Must specify only one configuration file option", filenames104 )105 (self.filename,) = filenames106 107 108class setopt(option_base):109 """Save command-line options to a file"""110 111 description = "set an option in setup.cfg or another config file"112 113 user_options = [114 ('command=', 'c', 'command to set an option for'),115 ('option=', 'o', 'option to set'),116 ('set-value=', 's', 'value of the option'),117 ('remove', 'r', 'remove (unset) the value'),118 ] + option_base.user_options119 120 boolean_options = option_base.boolean_options + ['remove']121 122 def initialize_options(self):123 option_base.initialize_options(self)124 self.command = None125 self.option = None126 self.set_value = None127 self.remove = None128 129 def finalize_options(self) -> None:130 option_base.finalize_options(self)131 if self.command is None or self.option is None:132 raise DistutilsOptionError("Must specify --command *and* --option")133 if self.set_value is None and not self.remove:134 raise DistutilsOptionError("Must specify --set-value or --remove")135 136 def run(self) -> None:137 edit_config(138 self.filename,139 {self.command: {self.option.replace('-', '_'): self.set_value}},140 self.dry_run,141 )142 