Skip to content

Commit

Permalink
Run Flynt to convert str.format to f-strings (#464)
Browse files Browse the repository at this point in the history
* chore: Convert old style str.format to f strings

Ran `flynt`: https://github.com/ikamensh/flynt against nox
to automatically convert `"{}".format` style strings to the
newer `f"{}"` style strings.

* Fix Lint failure by running black

* Improve readibility of some converted strings

* Run Flynt string conversion against tests/

* Change remaining str.format calls to f-strings
  • Loading branch information
FollowTheProcess committed Sep 9, 2021
1 parent 2821216 commit 9c696e2
Show file tree
Hide file tree
Showing 16 changed files with 75 additions and 105 deletions.
2 changes: 1 addition & 1 deletion nox/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def copy(self, name: Optional[str] = None) -> "Func":
class Call(Func):
def __init__(self, func: Func, param_spec: "Param") -> None:
call_spec = param_spec.call_spec
session_signature = "({})".format(param_spec)
session_signature = f"({param_spec})"

# Determine the Python interpreter for the session using either @session
# or @parametrize. For backwards compatibility, we only use a "python"
Expand Down
14 changes: 6 additions & 8 deletions nox/_option_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def __init__(
default: Union[Any, Callable[[], Any]] = None,
hidden: bool = False,
completer: Optional[Callable[..., List[str]]] = None,
**kwargs: Any
**kwargs: Any,
) -> None:
self.name = name
self.flags = flags
Expand Down Expand Up @@ -156,27 +156,25 @@ def make_flag_pair(
name: str,
enable_flags: Union[Tuple[str, str], Tuple[str]],
disable_flags: Tuple[str],
**kwargs: Any
**kwargs: Any,
) -> Tuple[Option, Option]:
"""Returns two options - one to enable a behavior and another to disable it.
The positive option is considered to be available to the noxfile, as
there isn't much point in doing flag pairs without it.
"""
disable_name = "no_{}".format(name)
disable_name = f"no_{name}"

kwargs["action"] = "store_true"
enable_option = Option(
name,
*enable_flags,
noxfile=True,
merge_func=functools.partial(flag_pair_merge_func, name, disable_name),
**kwargs
**kwargs,
)

kwargs["help"] = "Disables {} if it is enabled in the Noxfile.".format(
enable_flags[-1]
)
kwargs["help"] = f"Disables {enable_flags[-1]} if it is enabled in the Noxfile."
disable_option = Option(disable_name, *disable_flags, **kwargs)

return enable_option, disable_option
Expand Down Expand Up @@ -285,7 +283,7 @@ def namespace(self, **kwargs: Any) -> argparse.Namespace:
# used in tests.
for key, value in kwargs.items():
if key not in args:
raise KeyError("{} is not an option.".format(key))
raise KeyError(f"{key} is not an option.")
args[key] = value

return argparse.Namespace(**args)
Expand Down
4 changes: 2 additions & 2 deletions nox/_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,14 @@ def _posargs_finalizer(
if "--" not in posargs:
unexpected_posargs = posargs
raise _option_set.ArgumentError(
None, "Unknown argument(s) '{}'.".format(" ".join(unexpected_posargs))
None, f"Unknown argument(s) '{' '.join(unexpected_posargs)}'."
)

dash_index = posargs.index("--")
if dash_index != 0:
unexpected_posargs = posargs[0:dash_index]
raise _option_set.ArgumentError(
None, "Unknown argument(s) '{}'.".format(" ".join(unexpected_posargs))
None, f"Unknown argument(s) '{' '.join(unexpected_posargs)}'."
)

return posargs[dash_index + 1 :]
Expand Down
4 changes: 2 additions & 2 deletions nox/_parametrize.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __init__(
self,
*args: Any,
arg_names: Optional[Sequence[str]] = None,
id: Optional[str] = None
id: Optional[str] = None,
) -> None:
self.args = tuple(args)
self.id = id
Expand All @@ -51,7 +51,7 @@ def __str__(self) -> str:
return self.id
else:
call_spec = self.call_spec
args = ["{}={}".format(k, repr(call_spec[k])) for k in call_spec.keys()]
args = [f"{k}={call_spec[k]!r}" for k in call_spec.keys()]
return ", ".join(args)

__repr__ = __str__
Expand Down
27 changes: 11 additions & 16 deletions nox/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def which(program: str, paths: Optional[List[str]]) -> str:
if full_path:
return full_path.strpath

logger.error("Program {} not found.".format(program))
raise CommandFailed("Program {} not found".format(program))
logger.error(f"Program {program} not found.")
raise CommandFailed(f"Program {program} not found")


def _clean_env(env: Optional[dict]) -> Optional[dict]:
Expand All @@ -76,15 +76,15 @@ def run(
success_codes: Optional[Iterable[int]] = None,
log: bool = True,
external: Union[Literal["error"], bool] = False,
**popen_kws: Any
**popen_kws: Any,
) -> Union[str, bool]:
"""Run a command-line program."""

if success_codes is None:
success_codes = [0]

cmd, args = args[0], args[1:]
full_cmd = "{} {}".format(cmd, " ".join(args))
full_cmd = f"{cmd} {' '.join(args)}"

cmd_path = which(cmd, paths)

Expand All @@ -97,18 +97,14 @@ def run(
if is_external_tool:
if external == "error":
logger.error(
"Error: {} is not installed into the virtualenv, it is located at {}. "
"Pass external=True into run() to explicitly allow this.".format(
cmd, cmd_path
)
f"Error: {cmd} is not installed into the virtualenv, it is located at {cmd_path}. "
"Pass external=True into run() to explicitly allow this."
)
raise CommandFailed("External program disallowed.")
elif external is False:
logger.warning(
"Warning: {} is not installed into the virtualenv, it is located at {}. This might cause issues! "
"Pass external=True into run() to silence this message.".format(
cmd, cmd_path
)
f"Warning: {cmd} is not installed into the virtualenv, it is located at {cmd_path}. This might cause issues! "
"Pass external=True into run() to silence this message."
)

env = _clean_env(env)
Expand All @@ -119,16 +115,15 @@ def run(
)

if return_code not in success_codes:
suffix = ":" if silent else ""
logger.error(
"Command {} failed with exit code {}{}".format(
full_cmd, return_code, ":" if silent else ""
)
f"Command {full_cmd} failed with exit code {return_code}{suffix}"
)

if silent:
sys.stderr.write(output)

raise CommandFailed("Returned code {}".format(return_code))
raise CommandFailed(f"Returned code {return_code}")

if output:
logger.output(output)
Expand Down
14 changes: 6 additions & 8 deletions nox/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def filter_by_name(self, specified_sessions: Iterable[str]) -> None:
if _normalize_arg(session_name) not in all_sessions
]
if missing_sessions:
raise KeyError("Sessions not found: {}".format(", ".join(missing_sessions)))
raise KeyError(f"Sessions not found: {', '.join(missing_sessions)}")

def filter_by_python_interpreter(self, specified_pythons: Sequence[str]) -> None:
"""Filter sessions in the queue based on the user-specified
Expand Down Expand Up @@ -247,7 +247,7 @@ def make_session(
if not multi:
long_names.append(name)
if func.python:
long_names.append("{}-{}".format(name, func.python))
long_names.append(f"{name}-{func.python}")

return [SessionRunner(name, long_names, func, self._config, self)]

Expand All @@ -258,13 +258,11 @@ def make_session(
for call in calls:
long_names = []
if not multi:
long_names.append("{}{}".format(name, call.session_signature))
long_names.append(f"{name}{call.session_signature}")
if func.python:
long_names.append(
"{}-{}{}".format(name, func.python, call.session_signature)
)
long_names.append(f"{name}-{func.python}{call.session_signature}")
# Ensure that specifying session-python will run all parameterizations.
long_names.append("{}-{}".format(name, func.python))
long_names.append(f"{name}-{func.python}")

sessions.append(SessionRunner(name, long_names, call, self._config, self))

Expand Down Expand Up @@ -318,7 +316,7 @@ def notify(
return True

# The session was not found in the list of sessions.
raise ValueError("Session {} not found.".format(session))
raise ValueError(f"Session {session} not found.")


class KeywordLocals(collections.abc.Mapping):
Expand Down
38 changes: 16 additions & 22 deletions nox/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def _normalize_path(envdir: str, path: Union[str, bytes]) -> str:
logger.warning("The virtualenv name was hashed to avoid being too long.")
else:
logger.error(
"The virtualenv path {} is too long and will cause issues on "
f"The virtualenv path {full_path} is too long and will cause issues on "
"some environments. Use the --envdir path to modify where "
"nox stores virtualenvs.".format(full_path)
"nox stores virtualenvs."
)

return full_path
Expand All @@ -79,7 +79,7 @@ def _dblquote_pkg_install_arg(pkg_req_str: str) -> str:
# sanity check: we need an even number of double-quotes
if pkg_req_str.count('"') % 2 != 0:
raise ValueError(
"ill-formated argument with odd number of quotes: %s" % pkg_req_str
f"ill-formated argument with odd number of quotes: {pkg_req_str}"
)

if "<" in pkg_req_str or ">" in pkg_req_str:
Expand All @@ -89,10 +89,8 @@ def _dblquote_pkg_install_arg(pkg_req_str: str) -> str:
else:
# need to double-quote string
if '"' in pkg_req_str:
raise ValueError(
"Cannot escape requirement string: %s" % pkg_req_str
)
return '"%s"' % pkg_req_str
raise ValueError(f"Cannot escape requirement string: {pkg_req_str}")
return f'"{pkg_req_str}"'
else:
# no dangerous char: no need to double-quote string
return pkg_req_str
Expand Down Expand Up @@ -193,7 +191,7 @@ def interactive(self) -> bool:

def chdir(self, dir: Union[str, os.PathLike]) -> None:
"""Change the current working directory."""
self.log("cd {}".format(dir))
self.log(f"cd {dir}")
os.chdir(dir)

cd = chdir
Expand All @@ -203,11 +201,11 @@ def _run_func(
self, func: Callable, args: Iterable[Any], kwargs: Mapping[str, Any]
) -> Any:
"""Legacy support for running a function through :func`run`."""
self.log("{}(args={!r}, kwargs={!r})".format(func, args, kwargs))
self.log(f"{func}(args={args!r}, kwargs={kwargs!r})")
try:
return func(*args, **kwargs)
except Exception as e:
logger.exception("Function {!r} raised {!r}.".format(func, e))
logger.exception(f"Function {func!r} raised {e!r}.")
raise nox.command.CommandFailed()

def run(
Expand Down Expand Up @@ -263,7 +261,7 @@ def run(
raise ValueError("At least one argument required to run().")

if self._runner.global_config.install_only:
logger.info("Skipping {} run, as --install-only is set.".format(args[0]))
logger.info(f"Skipping {args[0]} run, as --install-only is set.")
return None

return self._run(*args, env=env, **kwargs)
Expand Down Expand Up @@ -410,7 +408,7 @@ def conda_install(
*prefix_args,
*args,
external="error",
**kwargs
**kwargs,
)

def install(self, *args: str, **kwargs: Any) -> None:
Expand Down Expand Up @@ -534,7 +532,7 @@ def description(self) -> Optional[str]:

def __str__(self) -> str:
sigs = ", ".join(self.signatures)
return "Session(name={}, signatures={})".format(self.name, sigs)
return f"Session(name={self.name}, signatures={sigs})"

@property
def friendly_name(self) -> str:
Expand Down Expand Up @@ -583,15 +581,13 @@ def _create_venv(self) -> None:
)
else:
raise ValueError(
"Expected venv_backend one of ('virtualenv', 'conda', 'venv'), but got '{}'.".format(
backend
)
f"Expected venv_backend one of ('virtualenv', 'conda', 'venv'), but got '{backend}'."
)

self.venv.create()

def execute(self) -> "Result":
logger.warning("Running session {}".format(self.friendly_name))
logger.warning(f"Running session {self.friendly_name}")

try:
# By default, nox should quietly change to the directory where
Expand Down Expand Up @@ -624,13 +620,11 @@ def execute(self) -> "Result":
return Result(self, Status.FAILED)

except KeyboardInterrupt:
logger.error("Session {} interrupted.".format(self.friendly_name))
logger.error(f"Session {self.friendly_name} interrupted.")
raise

except Exception as exc:
logger.exception(
"Session {} raised exception {!r}".format(self.friendly_name, exc)
)
logger.exception(f"Session {self.friendly_name} raised exception {exc!r}")
return Result(self, Status.FAILED)


Expand Down Expand Up @@ -669,7 +663,7 @@ def imperfect(self) -> str:
return "was successful"
status = self.status.name.lower()
if self.reason:
return "{}: {}".format(status, self.reason)
return f"{status}: {self.reason}"
else:
return status

Expand Down
Loading

0 comments on commit 9c696e2

Please sign in to comment.