Skip to content

Commit

Permalink
Ran pyupgrade for Python 3.8+ followed by ruff format.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Mar 2, 2024
1 parent d5e758c commit 826d6fd
Show file tree
Hide file tree
Showing 30 changed files with 67 additions and 101 deletions.
6 changes: 2 additions & 4 deletions distutils/bcppcompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def link( # noqa: C901
def_file = os.path.join(temp_dir, '%s.def' % modname)
contents = ['EXPORTS']
for sym in export_symbols or []:
contents.append(' {}=_{}'.format(sym, sym))
contents.append(f' {sym}=_{sym}')
self.execute(write_file, (def_file, contents), "writing %s" % def_file)

# Borland C++ has problems with '/' in paths
Expand Down Expand Up @@ -348,9 +348,7 @@ def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext(os.path.normcase(src_name))
if ext not in (self.src_extensions + ['.rc', '.res']):
raise UnknownFileError(
"unknown file type '{}' (from '{}')".format(ext, src_name)
)
raise UnknownFileError(f"unknown file type '{ext}' (from '{src_name}')")
if strip_dir:
base = os.path.basename(base)
if ext == '.res':
Expand Down
4 changes: 1 addition & 3 deletions distutils/ccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -973,9 +973,7 @@ def _make_out_path(self, output_dir, strip_dir, src_name):
try:
new_ext = self.out_extensions[ext]
except LookupError:
raise UnknownFileError(
"unknown file type '{}' (from '{}')".format(ext, src_name)
)
raise UnknownFileError(f"unknown file type '{ext}' (from '{src_name}')")
if strip_dir:
base = os.path.basename(base)
return os.path.join(output_dir, base + new_ext)
Expand Down
8 changes: 3 additions & 5 deletions distutils/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def dump_options(self, header=None, indent=""):
if option[-1] == "=":
option = option[:-1]
value = getattr(self, option)
self.announce(indent + "{} = {}".format(option, value), level=logging.INFO)
self.announce(indent + f"{option} = {value}", level=logging.INFO)

def run(self):
"""A command's raison d'etre: carry out the action it exists to
Expand Down Expand Up @@ -213,9 +213,7 @@ def _ensure_stringlike(self, option, what, default=None):
setattr(self, option, default)
return default
elif not isinstance(val, str):
raise DistutilsOptionError(
"'{}' must be a {} (got `{}`)".format(option, what, val)
)
raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
return val

def ensure_string(self, option, default=None):
Expand All @@ -242,7 +240,7 @@ def ensure_string_list(self, option):
ok = False
if not ok:
raise DistutilsOptionError(
"'{}' must be a list of strings (got {!r})".format(option, val)
f"'{option}' must be a list of strings (got {val!r})"
)

def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/_framework_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import sysconfig


@functools.lru_cache()
@functools.lru_cache
def enabled():
"""
Only enabled for Python 3.9 framework homebrew builds
Expand Down Expand Up @@ -37,7 +37,7 @@ def enabled():
)


@functools.lru_cache()
@functools.lru_cache
def vars():
if not enabled():
return {}
Expand Down
4 changes: 2 additions & 2 deletions distutils/command/bdist_rpm.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ def _make_spec_file(self): # noqa: C901
if isinstance(val, list):
spec_file.append('{}: {}'.format(field, ' '.join(val)))
elif val is not None:
spec_file.append('{}: {}'.format(field, val))
spec_file.append(f'{field}: {val}')

if self.distribution.get_url():
spec_file.append('Url: ' + self.distribution.get_url())
Expand Down Expand Up @@ -522,7 +522,7 @@ def _make_spec_file(self): # noqa: C901

# rpm scripts
# figure out default build script
def_setup_call = "{} {}".format(self.python, os.path.basename(sys.argv[0]))
def_setup_call = f"{self.python} {os.path.basename(sys.argv[0])}"
def_build = "%s build" % def_setup_call
if self.use_rpm_opt_flags:
def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def finalize_options(self): # noqa: C901
"using './configure --help' on your platform)"
)

plat_specifier = ".{}-{}".format(self.plat_name, sys.implementation.cache_tag)
plat_specifier = f".{self.plat_name}-{sys.implementation.cache_tag}"

# Make it so Python 2.x and Python 2.x with --with-pydebug don't
# share the same build directories. Doing so confuses the build
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/build_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ def _filter_build_errors(self, ext):
except (CCompilerError, DistutilsError, CompileError) as e:
if not ext.optional:
raise
self.warn('building extension "{}" failed: {}'.format(ext.name, e))
self.warn(f'building extension "{ext.name}" failed: {e}')

def build_extension(self, ext):
sources = ext.sources
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def check_restructuredtext(self):
if line is None:
warning = warning[1]
else:
warning = '{} (line {})'.format(warning[1], line)
warning = f'{warning[1]} (line {line})'
self.warn(warning)

def _check_rst_data(self, data):
Expand Down
2 changes: 1 addition & 1 deletion distutils/command/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def send_metadata(self): # noqa: C901
auth.add_password(self.realm, host, username, password)
# send the info to the server and report the result
code, result = self.post_to_server(self.build_post_data('submit'), auth)
self.announce('Server response ({}): {}'.format(code, result), logging.INFO)
self.announce(f'Server response ({code}): {result}', logging.INFO)

# possibly save the login
if code == 200:
Expand Down
8 changes: 3 additions & 5 deletions distutils/command/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def upload_file(self, command, pyversion, filename): # noqa: C901
body.write(end_boundary)
body = body.getvalue()

msg = "Submitting {} to {}".format(filename, self.repository)
msg = f"Submitting {filename} to {self.repository}"
self.announce(msg, logging.INFO)

# build the Request
Expand All @@ -193,14 +193,12 @@ def upload_file(self, command, pyversion, filename): # noqa: C901
raise

if status == 200:
self.announce(
'Server response ({}): {}'.format(status, reason), logging.INFO
)
self.announce(f'Server response ({status}): {reason}', logging.INFO)
if self.show_response:
text = self._read_pypi_response(result)
msg = '\n'.join(('-' * 75, text, '-' * 75))
self.announce(msg, logging.INFO)
else:
msg = 'Upload failed ({}): {}'.format(status, reason)
msg = f'Upload failed ({status}): {reason}'
self.announce(msg, logging.ERROR)
raise DistutilsError(msg)
6 changes: 3 additions & 3 deletions distutils/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,10 @@ def run_commands(dist):
raise SystemExit("interrupted")
except OSError as exc:
if DEBUG:
sys.stderr.write("error: {}\n".format(exc))
sys.stderr.write(f"error: {exc}\n")
raise
else:
raise SystemExit("error: {}".format(exc))
raise SystemExit(f"error: {exc}")

except (DistutilsError, CCompilerError) as msg:
if DEBUG:
Expand Down Expand Up @@ -249,7 +249,7 @@ def run_setup(script_name, script_args=None, stop_after="run"):
used to drive the Distutils.
"""
if stop_after not in ('init', 'config', 'commandline', 'run'):
raise ValueError("invalid value for 'stop_after': {!r}".format(stop_after))
raise ValueError(f"invalid value for 'stop_after': {stop_after!r}")

global _setup_stop_after, _setup_distribution
_setup_stop_after = stop_after
Expand Down
10 changes: 4 additions & 6 deletions distutils/cygwinccompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,7 @@ def __init__(self, verbose=0, dry_run=0, force=0):
super().__init__(verbose, dry_run, force)

status, details = check_config_h()
self.debug_print(
"Python's GCC status: {} (details: {})".format(status, details)
)
self.debug_print(f"Python's GCC status: {status} (details: {details})")
if status is not CONFIG_H_OK:
self.warn(
"Python's pyconfig.h doesn't seem to support your compiler. "
Expand All @@ -108,7 +106,7 @@ def __init__(self, verbose=0, dry_run=0, force=0):
compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
linker_exe='%s -mcygwin' % self.cc,
linker_so=('{} -mcygwin {}'.format(self.linker_dll, shared_option)),
linker_so=(f'{self.linker_dll} -mcygwin {shared_option}'),
)

# Include the appropriate MSVC runtime library if Python was built
Expand Down Expand Up @@ -280,7 +278,7 @@ def __init__(self, verbose=0, dry_run=0, force=0):
compiler_so='%s -mdll -O -Wall' % self.cc,
compiler_cxx='%s -O -Wall' % self.cxx,
linker_exe='%s' % self.cc,
linker_so='{} {}'.format(self.linker_dll, shared_option),
linker_so=f'{self.linker_dll} {shared_option}',
)

def runtime_library_dir_option(self, dir):
Expand Down Expand Up @@ -340,7 +338,7 @@ def check_config_h():
finally:
config_h.close()
except OSError as exc:
return (CONFIG_H_UNCERTAIN, "couldn't read '{}': {}".format(fn, exc.strerror))
return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}")


def is_cygwincc(cc):
Expand Down
10 changes: 3 additions & 7 deletions distutils/dir_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901

# Detect a common bug -- name is None
if not isinstance(name, str):
raise DistutilsInternalError(
"mkpath: 'name' must be a string (got {!r})".format(name)
)
raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")

# XXX what's the better way to handle verbosity? print as we create
# each directory in the path (the current behaviour), or only announce
Expand Down Expand Up @@ -76,7 +74,7 @@ def mkpath(name, mode=0o777, verbose=1, dry_run=0): # noqa: C901
except OSError as exc:
if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
raise DistutilsFileError(
"could not create '{}': {}".format(head, exc.args[-1])
f"could not create '{head}': {exc.args[-1]}"
)
created_dirs.append(head)

Expand Down Expand Up @@ -143,9 +141,7 @@ def copy_tree( # noqa: C901
if dry_run:
names = []
else:
raise DistutilsFileError(
"error listing files in '{}': {}".format(src, e.strerror)
)
raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")

if not dry_run:
mkpath(dst, verbose=verbose)
Expand Down
8 changes: 4 additions & 4 deletions distutils/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,7 @@ def get_command_class(self, command):
return klass

for pkgname in self.get_command_packages():
module_name = "{}.{}".format(pkgname, command)
module_name = f"{pkgname}.{command}"
klass_name = command

try:
Expand Down Expand Up @@ -889,7 +889,7 @@ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
self.announce(" setting options for '%s' command:" % command_name)
for option, (source, value) in option_dict.items():
if DEBUG:
self.announce(" {} = {} (from {})".format(option, value, source))
self.announce(f" {option} = {value} (from {source})")
try:
bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
except AttributeError:
Expand Down Expand Up @@ -1178,7 +1178,7 @@ def maybe_write(header, val):
def _write_list(self, file, name, values):
values = values or []
for value in values:
file.write('{}: {}\n'.format(name, value))
file.write(f'{name}: {value}\n')

# -- Metadata query methods ----------------------------------------

Expand All @@ -1189,7 +1189,7 @@ def get_version(self):
return self.version or "0.0.0"

def get_fullname(self):
return "{}-{}".format(self.get_name(), self.get_version())
return f"{self.get_name()}-{self.get_version()}"

def get_author(self):
return self.author
Expand Down
6 changes: 3 additions & 3 deletions distutils/fancy_getopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
longopt_re = re.compile(r'^%s$' % longopt_pat)

# For recognizing "negative alias" options, eg. "quiet=!verbose"
neg_alias_re = re.compile("^({})=!({})$".format(longopt_pat, longopt_pat))
neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")

# This is used to translate long options to legitimate Python identifiers
# (for use as attributes of some object).
Expand Down Expand Up @@ -157,7 +157,7 @@ def _grok_option_table(self): # noqa: C901
else:
# the option table is part of the code, so simply
# assert that it is correct
raise ValueError("invalid option tuple: {!r}".format(option))
raise ValueError(f"invalid option tuple: {option!r}")

# Type- and value-check the option names
if not isinstance(long, str) or len(long) < 2:
Expand Down Expand Up @@ -359,7 +359,7 @@ def generate_help(self, header=None): # noqa: C901
# Case 2: we have a short option, so we have to include it
# just after the long option
else:
opt_names = "{} (-{})".format(long, short)
opt_names = f"{long} (-{short})"
if text:
lines.append(" --%-*s %s" % (max_opt, opt_names, text[0]))
else:
Expand Down
26 changes: 8 additions & 18 deletions distutils/file_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,40 +26,32 @@ def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901
try:
fsrc = open(src, 'rb')
except OSError as e:
raise DistutilsFileError("could not open '{}': {}".format(src, e.strerror))
raise DistutilsFileError(f"could not open '{src}': {e.strerror}")

if os.path.exists(dst):
try:
os.unlink(dst)
except OSError as e:
raise DistutilsFileError(
"could not delete '{}': {}".format(dst, e.strerror)
)
raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}")

try:
fdst = open(dst, 'wb')
except OSError as e:
raise DistutilsFileError(
"could not create '{}': {}".format(dst, e.strerror)
)
raise DistutilsFileError(f"could not create '{dst}': {e.strerror}")

while True:
try:
buf = fsrc.read(buffer_size)
except OSError as e:
raise DistutilsFileError(
"could not read from '{}': {}".format(src, e.strerror)
)
raise DistutilsFileError(f"could not read from '{src}': {e.strerror}")

if not buf:
break

try:
fdst.write(buf)
except OSError as e:
raise DistutilsFileError(
"could not write to '{}': {}".format(dst, e.strerror)
)
raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}")
finally:
if fdst:
fdst.close()
Expand Down Expand Up @@ -199,12 +191,12 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901
dst = os.path.join(dst, basename(src))
elif exists(dst):
raise DistutilsFileError(
"can't move '{}': destination '{}' already exists".format(src, dst)
f"can't move '{src}': destination '{dst}' already exists"
)

if not isdir(dirname(dst)):
raise DistutilsFileError(
"can't move '{}': destination '{}' not a valid path".format(src, dst)
f"can't move '{src}': destination '{dst}' not a valid path"
)

copy_it = False
Expand All @@ -215,9 +207,7 @@ def move_file(src, dst, verbose=1, dry_run=0): # noqa: C901
if num == errno.EXDEV:
copy_it = True
else:
raise DistutilsFileError(
"couldn't move '{}' to '{}': {}".format(src, dst, msg)
)
raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}")

if copy_it:
copy_file(src, dst, verbose=verbose)
Expand Down
4 changes: 2 additions & 2 deletions distutils/filelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,9 @@ def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
if os.sep == '\\':
sep = r'\\'
pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]
pattern_re = r'{}\A{}{}.*{}{}'.format(start, prefix_re, sep, pattern_re, end)
pattern_re = rf'{start}\A{prefix_re}{sep}.*{pattern_re}{end}'
else: # no prefix -- respect anchor flag
if anchor:
pattern_re = r'{}\A{}'.format(start, pattern_re[len(start) :])
pattern_re = rf'{start}\A{pattern_re[len(start) :]}'

return re.compile(pattern_re)

0 comments on commit 826d6fd

Please sign in to comment.