cleanup: Replaced use of .format with f-strings or .format_map

Change-Id: I2df5b0ff8159218e284311e00ff4a63d720a0af2
This commit is contained in:
Jason R. Coombs 2023-10-16 13:52:44 -04:00
parent d3bda81f9e
commit 59e68434e7
13 changed files with 38 additions and 77 deletions

View File

@ -196,12 +196,10 @@ class UserAgent:
def git(self): def git(self):
"""The UA when running git.""" """The UA when running git."""
if self._git_ua is None: if self._git_ua is None:
self._git_ua = "git/{} ({}) git-repo/{}".format( self._git_ua = (
git.version_tuple().full, f"git/{git.version_tuple().full} ({self.os}) "
self.os, f"git-repo/{RepoSourceVersion()}"
RepoSourceVersion(),
) )
return self._git_ua return self._git_ua
@ -243,7 +241,7 @@ def _build_env(
env["GIT_SSH"] = ssh_proxy.proxy env["GIT_SSH"] = ssh_proxy.proxy
env["GIT_SSH_VARIANT"] = "ssh" env["GIT_SSH_VARIANT"] = "ssh"
if "http_proxy" in env and "darwin" == sys.platform: if "http_proxy" in env and "darwin" == sys.platform:
s = "'http.proxy={}'".format(env["http_proxy"]) s = f"'http.proxy={env['http_proxy']}'"
p = env.get("GIT_CONFIG_PARAMETERS") p = env.get("GIT_CONFIG_PARAMETERS")
if p is not None: if p is not None:
s = p + " " + s s = p + " " + s

View File

@ -76,9 +76,8 @@ class BaseEventLog:
# Save both our sid component and the complete sid. # Save both our sid component and the complete sid.
# We use our sid component (self._sid) as the unique filename prefix and # We use our sid component (self._sid) as the unique filename prefix and
# the full sid (self._full_sid) in the log itself. # the full sid (self._full_sid) in the log itself.
self._sid = "repo-{}-P{:08x}".format( self._sid = (
self.start.strftime("%Y%m%dT%H%M%SZ"), f"repo-{self.start.strftime('%Y%m%dT%H%M%SZ')}-P{os.getpid():08x}"
os.getpid(),
) )
if add_init_count: if add_init_count:

View File

@ -265,9 +265,7 @@ class RepoHook:
"approvedhash", "approvedhash",
self._GetHash(), self._GetHash(),
prompt % (self._GetMustVerb(), self._script_fullpath), prompt % (self._GetMustVerb(), self._script_fullpath),
"Scripts have changed since {} was allowed.".format( f"Scripts have changed since {self._hook_type} was allowed.",
self._hook_type
),
) )
@staticmethod @staticmethod
@ -314,20 +312,16 @@ class RepoHook:
HookError: When the hooks failed for any reason. HookError: When the hooks failed for any reason.
""" """
# This logic needs to be kept in sync with _ExecuteHookViaImport below. # This logic needs to be kept in sync with _ExecuteHookViaImport below.
script = """ script = f"""
import json, os, sys import json, os, sys
path = '''{path}''' path = '''{self._script_fullpath}'''
kwargs = json.loads('''{kwargs}''') kwargs = json.loads('''{json.dumps(kwargs)}''')
context = json.loads('''{context}''') context = json.loads('''{json.dumps(context)}''')
sys.path.insert(0, os.path.dirname(path)) sys.path.insert(0, os.path.dirname(path))
data = open(path).read() data = open(path).read()
exec(compile(data, path, 'exec'), context) exec(compile(data, path, 'exec'), context)
context['main'](**kwargs) context['main'](**kwargs)
""".format( """
path=self._script_fullpath,
kwargs=json.dumps(kwargs),
context=json.dumps(context),
)
# We pass the script via stdin to avoid OS argv limits. It also makes # We pass the script via stdin to avoid OS argv limits. It also makes
# unhandled exception tracebacks less verbose/confusing for users. # unhandled exception tracebacks less verbose/confusing for users.

View File

@ -206,11 +206,8 @@ class _Repo:
if short: if short:
commands = " ".join(sorted(self.commands)) commands = " ".join(sorted(self.commands))
wrapped_commands = textwrap.wrap(commands, width=77) wrapped_commands = textwrap.wrap(commands, width=77)
print( sep = "\n "
"Available commands:\n {}".format( print(f"Available commands:\n {sep.join(wrapped_commands)}")
"\n ".join(wrapped_commands)
)
)
print("\nRun `repo help <command>` for command-specific details.") print("\nRun `repo help <command>` for command-specific details.")
print("Bug reports:", Wrapper().BUG_URL) print("Bug reports:", Wrapper().BUG_URL)
else: else:

View File

@ -1307,9 +1307,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
raise raise
except Exception as e: except Exception as e:
raise ManifestParseError( raise ManifestParseError(
"failed parsing included manifest {}: {}".format( f"failed parsing included manifest {name}: {e}"
name, e
)
) )
else: else:
if parent_groups and node.nodeName == "project": if parent_groups and node.nodeName == "project":
@ -1811,9 +1809,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
remote = self._default.remote remote = self._default.remote
if remote is None: if remote is None:
raise ManifestParseError( raise ManifestParseError(
"no remote for project {} within {}".format( f"no remote for project {name} within {self.manifestFile}"
name, self.manifestFile
)
) )
revisionExpr = node.getAttribute("revision") or remote.revision revisionExpr = node.getAttribute("revision") or remote.revision

View File

@ -57,8 +57,8 @@ def _validate_winpath(path):
if _winpath_is_valid(path): if _winpath_is_valid(path):
return path return path
raise ValueError( raise ValueError(
'Path "{}" must be a relative path or an absolute ' f'Path "{path}" must be a relative path or an absolute '
"path starting with a drive letter".format(path) "path starting with a drive letter"
) )

View File

@ -957,12 +957,8 @@ class Project:
f_status = "-" f_status = "-"
if i and i.src_path: if i and i.src_path:
line = " {}{}\t{} => {} ({}%)".format( line = (
i_status, f" {i_status}{f_status}\t{i.src_path} => {p} ({i.level}%)"
f_status,
i.src_path,
p,
i.level,
) )
else: else:
line = f" {i_status}{f_status}\t{p}" line = f" {i_status}{f_status}\t{p}"
@ -1182,9 +1178,7 @@ class Project:
GitCommand(self, cmd, bare=True, verify_command=True).Wait() GitCommand(self, cmd, bare=True, verify_command=True).Wait()
if not dryrun: if not dryrun:
msg = "posted to {} for {}".format( msg = f"posted to {branch.remote.review} for {dest_branch}"
branch.remote.review, dest_branch
)
self.bare_git.UpdateRef( self.bare_git.UpdateRef(
R_PUB + branch.name, R_HEADS + branch.name, message=msg R_PUB + branch.name, R_HEADS + branch.name, message=msg
) )
@ -1446,9 +1440,7 @@ class Project:
return self.bare_git.rev_list(self.revisionExpr, "-1")[0] return self.bare_git.rev_list(self.revisionExpr, "-1")[0]
except GitError: except GitError:
raise ManifestInvalidRevisionError( raise ManifestInvalidRevisionError(
"revision {} in {} not found".format( f"revision {self.revisionExpr} in {self.name} not found"
self.revisionExpr, self.name
)
) )
def GetRevisionId(self, all_refs=None): def GetRevisionId(self, all_refs=None):
@ -1465,9 +1457,7 @@ class Project:
return self.bare_git.rev_parse("--verify", "%s^0" % rev) return self.bare_git.rev_parse("--verify", "%s^0" % rev)
except GitError: except GitError:
raise ManifestInvalidRevisionError( raise ManifestInvalidRevisionError(
"revision {} in {} not found".format( f"revision {self.revisionExpr} in {self.name} not found"
self.revisionExpr, self.name
)
) )
def SetRevisionId(self, revisionId): def SetRevisionId(self, revisionId):
@ -1779,11 +1769,7 @@ class Project:
raise DeleteDirtyWorktreeError(msg, project=self) raise DeleteDirtyWorktreeError(msg, project=self)
if not quiet: if not quiet:
print( print(f"{self.RelPath(local=False)}: Deleting obsolete checkout.")
"{}: Deleting obsolete checkout.".format(
self.RelPath(local=False)
)
)
# Unlock and delink from the main worktree. We don't use git's worktree # Unlock and delink from the main worktree. We don't use git's worktree
# remove because it will recursively delete projects -- we handle that # remove because it will recursively delete projects -- we handle that
@ -3163,8 +3149,8 @@ class Project:
"--force-sync not enabled; cannot overwrite a local " "--force-sync not enabled; cannot overwrite a local "
"work tree. If you're comfortable with the " "work tree. If you're comfortable with the "
"possibility of losing the work tree's git metadata," "possibility of losing the work tree's git metadata,"
" use `repo sync --force-sync {}` to " f" use `repo sync --force-sync {self.RelPath(local=False)}` to "
"proceed.".format(self.RelPath(local=False)), "proceed.",
project=self.name, project=self.name,
) )
@ -3678,9 +3664,7 @@ class Project:
config = kwargs.pop("config", None) config = kwargs.pop("config", None)
for k in kwargs: for k in kwargs:
raise TypeError( raise TypeError(
"{}() got an unexpected keyword argument {!r}".format( f"{name}() got an unexpected keyword argument {k!r}"
name, k
)
) )
if config is not None: if config is not None:
for k, v in config.items(): for k, v in config.items():

View File

@ -152,4 +152,4 @@ It is equivalent to "git branch -D <branchname>".
_RelPath(p) for p in success[br] _RelPath(p) for p in success[br]
) )
) )
print("{}{}| {}\n".format(br, " " * (width - len(br)), result)) print(f"{br}{' ' * (width - len(br))}| {result}\n")

View File

@ -174,7 +174,7 @@ is shown, then the branch appears in all projects.
if _RelPath(p) not in have: if _RelPath(p) not in have:
paths.append(_RelPath(p)) paths.append(_RelPath(p))
s = " {} {}".format(in_type, ", ".join(paths)) s = f" {in_type} {', '.join(paths)}"
if not i.IsSplitCurrent and (width + 7 + len(s) < 80): if not i.IsSplitCurrent and (width + 7 + len(s) < 80):
fmt = out.current if i.IsCurrent else fmt fmt = out.current if i.IsCurrent else fmt
fmt(s) fmt(s)

View File

@ -248,7 +248,7 @@ class Info(PagedCommand):
for commit in commits: for commit in commits:
split = commit.split() split = commit.split()
self.text("{:38}{} ".format("", "-")) self.text(f"{'':38}{'-'} ")
self.sha(split[0] + " ") self.sha(split[0] + " ")
self.text(" ".join(split[1:])) self.text(" ".join(split[1:]))
self.out.nl() self.out.nl()

View File

@ -83,11 +83,7 @@ class Prune(PagedCommand):
) )
if not branch.base_exists: if not branch.base_exists:
print( print(f"(ignoring: tracking branch is gone: {branch.base})")
"(ignoring: tracking branch is gone: {})".format(
branch.base
)
)
else: else:
commits = branch.commits commits = branch.commits
date = branch.date date = branch.date

View File

@ -1416,9 +1416,10 @@ later is required to fix a server side protocol bug.
"TARGET_PRODUCT" in os.environ "TARGET_PRODUCT" in os.environ
and "TARGET_BUILD_VARIANT" in os.environ and "TARGET_BUILD_VARIANT" in os.environ
): ):
target = "{}-{}".format( target = (
os.environ["TARGET_PRODUCT"], "{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}".format_map(
os.environ["TARGET_BUILD_VARIANT"], os.environ
)
) )
[success, manifest_str] = server.GetApprovedManifest( [success, manifest_str] = server.GetApprovedManifest(
branch, target branch, target

View File

@ -63,11 +63,7 @@ class Version(Command, MirrorSafeCommand):
# Python 3 returns a named tuple, but Python 2 is simpler. # Python 3 returns a named tuple, but Python 2 is simpler.
print(uname) print(uname)
else: else:
print( print("OS {system} {release} ({version})".format_map(vars(uname)))
"OS {} {} ({})".format(
uname.system, uname.release, uname.version
)
)
print( print(
"CPU %s (%s)" "CPU %s (%s)"
% ( % (