From 59e68434e7a3561b8cb327fe76055fe25b14c7dd Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Mon, 16 Oct 2023 13:52:44 -0400 Subject: [PATCH] cleanup: Replaced use of .format with f-strings or .format_map Change-Id: I2df5b0ff8159218e284311e00ff4a63d720a0af2 --- git_command.py | 10 ++++------ git_trace2_event_log_base.py | 5 ++--- hooks.py | 18 ++++++----------- main.py | 7 ++----- manifest_xml.py | 8 ++------ platform_utils.py | 4 ++-- project.py | 38 +++++++++++------------------------- subcmds/abandon.py | 2 +- subcmds/branches.py | 2 +- subcmds/info.py | 2 +- subcmds/prune.py | 6 +----- subcmds/sync.py | 7 ++++--- subcmds/version.py | 6 +----- 13 files changed, 38 insertions(+), 77 deletions(-) diff --git a/git_command.py b/git_command.py index c2a45174..3c3869a2 100644 --- a/git_command.py +++ b/git_command.py @@ -196,12 +196,10 @@ class UserAgent: def git(self): """The UA when running git.""" if self._git_ua is None: - self._git_ua = "git/{} ({}) git-repo/{}".format( - git.version_tuple().full, - self.os, - RepoSourceVersion(), + self._git_ua = ( + f"git/{git.version_tuple().full} ({self.os}) " + f"git-repo/{RepoSourceVersion()}" ) - return self._git_ua @@ -243,7 +241,7 @@ def _build_env( env["GIT_SSH"] = ssh_proxy.proxy env["GIT_SSH_VARIANT"] = "ssh" 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") if p is not None: s = p + " " + s diff --git a/git_trace2_event_log_base.py b/git_trace2_event_log_base.py index 8f2fa79e..f5424249 100644 --- a/git_trace2_event_log_base.py +++ b/git_trace2_event_log_base.py @@ -76,9 +76,8 @@ class BaseEventLog: # Save both our sid component and the complete sid. # We use our sid component (self._sid) as the unique filename prefix and # the full sid (self._full_sid) in the log itself. - self._sid = "repo-{}-P{:08x}".format( - self.start.strftime("%Y%m%dT%H%M%SZ"), - os.getpid(), + self._sid = ( + f"repo-{self.start.strftime('%Y%m%dT%H%M%SZ')}-P{os.getpid():08x}" ) if add_init_count: diff --git a/hooks.py b/hooks.py index 49ed10d1..5912dee0 100644 --- a/hooks.py +++ b/hooks.py @@ -265,9 +265,7 @@ class RepoHook: "approvedhash", self._GetHash(), prompt % (self._GetMustVerb(), self._script_fullpath), - "Scripts have changed since {} was allowed.".format( - self._hook_type - ), + f"Scripts have changed since {self._hook_type} was allowed.", ) @staticmethod @@ -314,20 +312,16 @@ class RepoHook: HookError: When the hooks failed for any reason. """ # This logic needs to be kept in sync with _ExecuteHookViaImport below. - script = """ + script = f""" import json, os, sys -path = '''{path}''' -kwargs = json.loads('''{kwargs}''') -context = json.loads('''{context}''') +path = '''{self._script_fullpath}''' +kwargs = json.loads('''{json.dumps(kwargs)}''') +context = json.loads('''{json.dumps(context)}''') sys.path.insert(0, os.path.dirname(path)) data = open(path).read() exec(compile(data, path, 'exec'), context) 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 # unhandled exception tracebacks less verbose/confusing for users. diff --git a/main.py b/main.py index 3df4c944..efe4f47b 100755 --- a/main.py +++ b/main.py @@ -206,11 +206,8 @@ class _Repo: if short: commands = " ".join(sorted(self.commands)) wrapped_commands = textwrap.wrap(commands, width=77) - print( - "Available commands:\n {}".format( - "\n ".join(wrapped_commands) - ) - ) + sep = "\n " + print(f"Available commands:\n {sep.join(wrapped_commands)}") print("\nRun `repo help ` for command-specific details.") print("Bug reports:", Wrapper().BUG_URL) else: diff --git a/manifest_xml.py b/manifest_xml.py index 77b3b8c8..4a8bda13 100644 --- a/manifest_xml.py +++ b/manifest_xml.py @@ -1307,9 +1307,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md raise except Exception as e: raise ManifestParseError( - "failed parsing included manifest {}: {}".format( - name, e - ) + f"failed parsing included manifest {name}: {e}" ) else: 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 if remote is None: raise ManifestParseError( - "no remote for project {} within {}".format( - name, self.manifestFile - ) + f"no remote for project {name} within {self.manifestFile}" ) revisionExpr = node.getAttribute("revision") or remote.revision diff --git a/platform_utils.py b/platform_utils.py index d720a07e..4cf994bc 100644 --- a/platform_utils.py +++ b/platform_utils.py @@ -57,8 +57,8 @@ def _validate_winpath(path): if _winpath_is_valid(path): return path raise ValueError( - 'Path "{}" must be a relative path or an absolute ' - "path starting with a drive letter".format(path) + f'Path "{path}" must be a relative path or an absolute ' + "path starting with a drive letter" ) diff --git a/project.py b/project.py index d6695fc2..0abe464b 100644 --- a/project.py +++ b/project.py @@ -957,12 +957,8 @@ class Project: f_status = "-" if i and i.src_path: - line = " {}{}\t{} => {} ({}%)".format( - i_status, - f_status, - i.src_path, - p, - i.level, + line = ( + f" {i_status}{f_status}\t{i.src_path} => {p} ({i.level}%)" ) else: line = f" {i_status}{f_status}\t{p}" @@ -1182,9 +1178,7 @@ class Project: GitCommand(self, cmd, bare=True, verify_command=True).Wait() if not dryrun: - msg = "posted to {} for {}".format( - branch.remote.review, dest_branch - ) + msg = f"posted to {branch.remote.review} for {dest_branch}" self.bare_git.UpdateRef( 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] except GitError: raise ManifestInvalidRevisionError( - "revision {} in {} not found".format( - self.revisionExpr, self.name - ) + f"revision {self.revisionExpr} in {self.name} not found" ) def GetRevisionId(self, all_refs=None): @@ -1465,9 +1457,7 @@ class Project: return self.bare_git.rev_parse("--verify", "%s^0" % rev) except GitError: raise ManifestInvalidRevisionError( - "revision {} in {} not found".format( - self.revisionExpr, self.name - ) + f"revision {self.revisionExpr} in {self.name} not found" ) def SetRevisionId(self, revisionId): @@ -1779,11 +1769,7 @@ class Project: raise DeleteDirtyWorktreeError(msg, project=self) if not quiet: - print( - "{}: Deleting obsolete checkout.".format( - self.RelPath(local=False) - ) - ) + print(f"{self.RelPath(local=False)}: Deleting obsolete checkout.") # Unlock and delink from the main worktree. We don't use git's worktree # remove because it will recursively delete projects -- we handle that @@ -2298,8 +2284,8 @@ class Project: name = self.remote.name # The output will look like (NB: tabs are separators): - # ref: refs/heads/master HEAD - # 5f6803b100bb3cd0f534e96e88c91373e8ed1c44 HEAD + # ref: refs/heads/master HEAD + # 5f6803b100bb3cd0f534e96e88c91373e8ed1c44 HEAD output = self.bare_git.ls_remote( "-q", "--symref", "--exit-code", name, "HEAD" ) @@ -3163,8 +3149,8 @@ class Project: "--force-sync not enabled; cannot overwrite a local " "work tree. If you're comfortable with the " "possibility of losing the work tree's git metadata," - " use `repo sync --force-sync {}` to " - "proceed.".format(self.RelPath(local=False)), + f" use `repo sync --force-sync {self.RelPath(local=False)}` to " + "proceed.", project=self.name, ) @@ -3678,9 +3664,7 @@ class Project: config = kwargs.pop("config", None) for k in kwargs: raise TypeError( - "{}() got an unexpected keyword argument {!r}".format( - name, k - ) + f"{name}() got an unexpected keyword argument {k!r}" ) if config is not None: for k, v in config.items(): diff --git a/subcmds/abandon.py b/subcmds/abandon.py index acba8523..e280d69e 100644 --- a/subcmds/abandon.py +++ b/subcmds/abandon.py @@ -152,4 +152,4 @@ It is equivalent to "git branch -D ". _RelPath(p) for p in success[br] ) ) - print("{}{}| {}\n".format(br, " " * (width - len(br)), result)) + print(f"{br}{' ' * (width - len(br))}| {result}\n") diff --git a/subcmds/branches.py b/subcmds/branches.py index 404f738f..59b5cb28 100644 --- a/subcmds/branches.py +++ b/subcmds/branches.py @@ -174,7 +174,7 @@ is shown, then the branch appears in all projects. if _RelPath(p) not in have: 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): fmt = out.current if i.IsCurrent else fmt fmt(s) diff --git a/subcmds/info.py b/subcmds/info.py index e24d0a8b..f637600e 100644 --- a/subcmds/info.py +++ b/subcmds/info.py @@ -248,7 +248,7 @@ class Info(PagedCommand): for commit in commits: split = commit.split() - self.text("{:38}{} ".format("", "-")) + self.text(f"{'':38}{'-'} ") self.sha(split[0] + " ") self.text(" ".join(split[1:])) self.out.nl() diff --git a/subcmds/prune.py b/subcmds/prune.py index b4ea40e8..f99082a4 100644 --- a/subcmds/prune.py +++ b/subcmds/prune.py @@ -83,11 +83,7 @@ class Prune(PagedCommand): ) if not branch.base_exists: - print( - "(ignoring: tracking branch is gone: {})".format( - branch.base - ) - ) + print(f"(ignoring: tracking branch is gone: {branch.base})") else: commits = branch.commits date = branch.date diff --git a/subcmds/sync.py b/subcmds/sync.py index 0338b433..fca05865 100644 --- a/subcmds/sync.py +++ b/subcmds/sync.py @@ -1416,9 +1416,10 @@ later is required to fix a server side protocol bug. "TARGET_PRODUCT" in os.environ and "TARGET_BUILD_VARIANT" in os.environ ): - target = "{}-{}".format( - os.environ["TARGET_PRODUCT"], - os.environ["TARGET_BUILD_VARIANT"], + target = ( + "{TARGET_PRODUCT}-{TARGET_BUILD_VARIANT}".format_map( + os.environ + ) ) [success, manifest_str] = server.GetApprovedManifest( branch, target diff --git a/subcmds/version.py b/subcmds/version.py index cf108f75..04470684 100644 --- a/subcmds/version.py +++ b/subcmds/version.py @@ -63,11 +63,7 @@ class Version(Command, MirrorSafeCommand): # Python 3 returns a named tuple, but Python 2 is simpler. print(uname) else: - print( - "OS {} {} ({})".format( - uname.system, uname.release, uname.version - ) - ) + print("OS {system} {release} ({version})".format_map(vars(uname))) print( "CPU %s (%s)" % (