Skip to content

Commit

Permalink
cleanup: Update codebase to expect Python 3.6
Browse files Browse the repository at this point in the history
- Bump minimum version to Python 3.6.
- Use f-strings in a lot of places.

Change-Id: I2aa70197230fcec2eff8e7c8eb754f20c08075bb
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/389034
Tested-by: Jason R. Coombs <[email protected]>
Reviewed-by: Mike Frysinger <[email protected]>
Commit-Queue: Jason R. Coombs <[email protected]>
  • Loading branch information
jaraco authored and LUCI committed Oct 31, 2023
1 parent b99272c commit b32ccbb
Show file tree
Hide file tree
Showing 33 changed files with 169 additions and 225 deletions.
2 changes: 1 addition & 1 deletion color.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def _parse(self, opt, fg, bg, attr):
if not opt:
return _Color(fg, bg, attr)

v = self._config.GetString("%s.%s" % (self._section, opt))
v = self._config.GetString(f"{self._section}.{opt}")
if v is None:
return _Color(fg, bg, attr)

Expand Down
4 changes: 1 addition & 3 deletions editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,7 @@ def EditString(cls, data):
try:
rc = subprocess.Popen(args, shell=shell).wait()
except OSError as e:
raise EditorError(
"editor failed, %s: %s %s" % (str(e), editor, path)
)
raise EditorError(f"editor failed, {str(e)}: {editor} {path}")
if rc != 0:
raise EditorError(
"editor failed with exit status %d: %s %s"
Expand Down
14 changes: 6 additions & 8 deletions git_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,10 @@ def repo(self):
def git(self):
"""The UA when running git."""
if self._git_ua is None:
self._git_ua = "git/%s (%s) git-repo/%s" % (
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


Expand All @@ -216,7 +214,7 @@ def git_require(min_version, fail=False, msg=""):
need = ".".join(map(str, min_version))
if msg:
msg = " for " + msg
error_msg = "fatal: git %s or later required%s" % (need, msg)
error_msg = f"fatal: git {need} or later required{msg}"
logger.error(error_msg)
raise GitRequireError(error_msg)
return False
Expand All @@ -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=%s'" % (env["http_proxy"],)
s = f"'http.proxy={env['http_proxy']}'"
p = env.get("GIT_CONFIG_PARAMETERS")
if p is not None:
s = p + " " + s
Expand Down Expand Up @@ -468,7 +466,7 @@ def _RunCommand(
)
except Exception as e:
raise GitPopenCommandError(
message="%s: %s" % (command[1], e),
message=f"{command[1]}: {e}",
project=self.project.name if self.project else None,
command_args=self.cmdv,
)
Expand Down
20 changes: 9 additions & 11 deletions git_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def _do(self, *args):
if p.Wait() == 0:
return p.stdout
else:
raise GitError("git config %s: %s" % (str(args), p.stderr))
raise GitError(f"git config {str(args)}: {p.stderr}")


class RepoConfig(GitConfig):
Expand Down Expand Up @@ -651,13 +651,11 @@ def ReviewUrl(self, userEmail, validate_certs):
userEmail, host, port
)
except urllib.error.HTTPError as e:
raise UploadError("%s: %s" % (self.review, str(e)))
raise UploadError(f"{self.review}: {str(e)}")
except urllib.error.URLError as e:
raise UploadError("%s: %s" % (self.review, str(e)))
raise UploadError(f"{self.review}: {str(e)}")
except http.client.HTTPException as e:
raise UploadError(
"%s: %s" % (self.review, e.__class__.__name__)
)
raise UploadError(f"{self.review}: {e.__class__.__name__}")

REVIEW_CACHE[u] = self._review_url
return self._review_url + self.projectname
Expand All @@ -666,7 +664,7 @@ def _SshReviewUrl(self, userEmail, host, port):
username = self._config.GetString("review.%s.username" % self.review)
if username is None:
username = userEmail.split("@")[0]
return "ssh://%s@%s:%s/" % (username, host, port)
return f"ssh://{username}@{host}:{port}/"

def ToLocal(self, rev):
"""Convert a remote revision string to something we have locally."""
Expand Down Expand Up @@ -715,11 +713,11 @@ def Save(self):
self._Set("fetch", list(map(str, self.fetch)))

def _Set(self, key, value):
key = "remote.%s.%s" % (self.name, key)
key = f"remote.{self.name}.{key}"
return self._config.SetString(key, value)

def _Get(self, key, all_keys=False):
key = "remote.%s.%s" % (self.name, key)
key = f"remote.{self.name}.{key}"
return self._config.GetString(key, all_keys=all_keys)


Expand Down Expand Up @@ -762,11 +760,11 @@ def Save(self):
fd.write("\tmerge = %s\n" % self.merge)

def _Set(self, key, value):
key = "branch.%s.%s" % (self.name, key)
key = f"branch.{self.name}.{key}"
return self._config.SetString(key, value)

def _Get(self, key, all_keys=False):
key = "branch.%s.%s" % (self.name, key)
key = f"branch.{self.name}.{key}"
return self._config.GetString(key, all_keys=all_keys)


Expand Down
5 changes: 2 additions & 3 deletions git_trace2_event_log_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,8 @@ def __init__(
# 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-%s-P%08x" % (
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:
Expand Down
11 changes: 5 additions & 6 deletions hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def _CheckForHookApprovalHelper(
abort_if_user_denies was passed to the consturctor.
"""
hooks_config = self._hooks_project.config
git_approval_key = "repo.hooks.%s.%s" % (self._hook_type, subkey)
git_approval_key = f"repo.hooks.{self._hook_type}.{subkey}"

# Get the last value that the user approved for this hook; may be None.
old_val = hooks_config.GetString(git_approval_key)
Expand All @@ -193,7 +193,7 @@ def _CheckForHookApprovalHelper(
else:
# Give the user a reason why we're prompting, since they last
# told us to "never ask again".
prompt = "WARNING: %s\n\n" % (changed_prompt,)
prompt = f"WARNING: {changed_prompt}\n\n"
else:
prompt = ""

Expand Down Expand Up @@ -241,9 +241,8 @@ def _CheckForHookApprovalManifest(self):
return self._CheckForHookApprovalHelper(
"approvedmanifest",
self._manifest_url,
"Run hook scripts from %s" % (self._manifest_url,),
"Manifest URL has changed since %s was allowed."
% (self._hook_type,),
f"Run hook scripts from {self._manifest_url}",
f"Manifest URL has changed since {self._hook_type} was allowed.",
)

def _CheckForHookApprovalHash(self):
Expand All @@ -262,7 +261,7 @@ def _CheckForHookApprovalHash(self):
"approvedhash",
self._GetHash(),
prompt % (self._GetMustVerb(), self._script_fullpath),
"Scripts have changed since %s was allowed." % (self._hook_type,),
f"Scripts have changed since {self._hook_type} was allowed.",
)

@staticmethod
Expand Down
7 changes: 3 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,8 @@ def _PrintHelp(self, short: bool = False, all_commands: bool = False):
if short:
commands = " ".join(sorted(self.commands))
wrapped_commands = textwrap.wrap(commands, width=77)
print(
"Available commands:\n %s" % ("\n ".join(wrapped_commands),)
)
help_commands = "".join(f"\n {x}" for x in wrapped_commands)
print(f"Available commands:{help_commands}")
print("\nRun `repo help <command>` for command-specific details.")
print("Bug reports:", Wrapper().BUG_URL)
else:
Expand Down Expand Up @@ -236,7 +235,7 @@ def _ExpandAlias(self, name):
if name in self.commands:
return name, []

key = "alias.%s" % (name,)
key = f"alias.{name}"
alias = RepoConfig.ForRepository(self.repodir).GetString(key)
if alias is None:
alias = RepoConfig.ForUser().GetString(key)
Expand Down
36 changes: 16 additions & 20 deletions manifest_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ def XmlInt(node, attr, default=None):
try:
return int(value)
except ValueError:
raise ManifestParseError(
'manifest: invalid %s="%s" integer' % (attr, value)
)
raise ManifestParseError(f'manifest: invalid {attr}="{value}" integer')


class _Default:
Expand Down Expand Up @@ -810,7 +808,7 @@ def append_children(ret, node):
ret.setdefault(child.nodeName, []).append(element)
else:
raise ManifestParseError(
'Unhandled element "%s"' % (child.nodeName,)
f'Unhandled element "{child.nodeName}"'
)

append_children(element, child)
Expand Down Expand Up @@ -1258,12 +1256,10 @@ def _ParseManifestXml(
try:
root = xml.dom.minidom.parse(path)
except (OSError, xml.parsers.expat.ExpatError) as e:
raise ManifestParseError(
"error parsing manifest %s: %s" % (path, e)
)
raise ManifestParseError(f"error parsing manifest {path}: {e}")

if not root or not root.childNodes:
raise ManifestParseError("no root node in %s" % (path,))
raise ManifestParseError(f"no root node in {path}")

for manifest in root.childNodes:
if (
Expand All @@ -1272,7 +1268,7 @@ def _ParseManifestXml(
):
break
else:
raise ManifestParseError("no <manifest> in %s" % (path,))
raise ManifestParseError(f"no <manifest> in {path}")

nodes = []
for node in manifest.childNodes:
Expand All @@ -1282,7 +1278,7 @@ def _ParseManifestXml(
msg = self._CheckLocalPath(name)
if msg:
raise ManifestInvalidPathError(
'<include> invalid "name": %s: %s' % (name, msg)
f'<include> invalid "name": {name}: {msg}'
)
include_groups = ""
if parent_groups:
Expand Down Expand Up @@ -1314,7 +1310,7 @@ def _ParseManifestXml(
raise
except Exception as e:
raise ManifestParseError(
"failed parsing included manifest %s: %s" % (name, e)
f"failed parsing included manifest {name}: {e}"
)
else:
if parent_groups and node.nodeName == "project":
Expand Down Expand Up @@ -1765,13 +1761,13 @@ def _ParseSubmanifest(self, node):
msg = self._CheckLocalPath(name)
if msg:
raise ManifestInvalidPathError(
'<submanifest> invalid "name": %s: %s' % (name, msg)
f'<submanifest> invalid "name": {name}: {msg}'
)
else:
msg = self._CheckLocalPath(path)
if msg:
raise ManifestInvalidPathError(
'<submanifest> invalid "path": %s: %s' % (path, msg)
f'<submanifest> invalid "path": {path}: {msg}'
)

submanifest = _XmlSubmanifest(
Expand Down Expand Up @@ -1806,7 +1802,7 @@ def _ParseProject(self, node, parent=None, **extra_proj_attrs):
msg = self._CheckLocalPath(name, dir_ok=True)
if msg:
raise ManifestInvalidPathError(
'<project> invalid "name": %s: %s' % (name, msg)
f'<project> invalid "name": {name}: {msg}'
)
if parent:
name = self._JoinName(parent.name, name)
Expand All @@ -1816,7 +1812,7 @@ def _ParseProject(self, node, parent=None, **extra_proj_attrs):
remote = self._default.remote
if remote is None:
raise ManifestParseError(
"no remote for project %s within %s" % (name, self.manifestFile)
f"no remote for project {name} within {self.manifestFile}"
)

revisionExpr = node.getAttribute("revision") or remote.revision
Expand All @@ -1837,7 +1833,7 @@ def _ParseProject(self, node, parent=None, **extra_proj_attrs):
msg = self._CheckLocalPath(path, dir_ok=True, cwd_dot_ok=True)
if msg:
raise ManifestInvalidPathError(
'<project> invalid "path": %s: %s' % (path, msg)
f'<project> invalid "path": {path}: {msg}'
)

rebase = XmlBool(node, "rebase", True)
Expand Down Expand Up @@ -2094,7 +2090,7 @@ def _CheckLocalPath(path, dir_ok=False, cwd_dot_ok=False):
if not cwd_dot_ok or parts != ["."]:
for part in set(parts):
if part in {".", "..", ".git"} or part.startswith(".repo"):
return "bad component: %s" % (part,)
return f"bad component: {part}"

if not dir_ok and resep.match(path[-1]):
return "dirs not allowed"
Expand Down Expand Up @@ -2130,7 +2126,7 @@ def _ValidateFilePaths(cls, element, src, dest):
msg = cls._CheckLocalPath(dest)
if msg:
raise ManifestInvalidPathError(
'<%s> invalid "dest": %s: %s' % (element, dest, msg)
f'<{element}> invalid "dest": {dest}: {msg}'
)

# |src| is the file we read from or path we point to for symlinks.
Expand All @@ -2141,7 +2137,7 @@ def _ValidateFilePaths(cls, element, src, dest):
)
if msg:
raise ManifestInvalidPathError(
'<%s> invalid "src": %s: %s' % (element, src, msg)
f'<{element}> invalid "src": {src}: {msg}'
)

def _ParseCopyFile(self, project, node):
Expand Down Expand Up @@ -2185,7 +2181,7 @@ def _get_remote(self, node):
v = self._remotes.get(name)
if not v:
raise ManifestParseError(
"remote %s not defined in %s" % (name, self.manifestFile)
f"remote {name} not defined in {self.manifestFile}"
)
return v

Expand Down
4 changes: 2 additions & 2 deletions platform_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)


Expand Down
12 changes: 5 additions & 7 deletions platform_utils_win32.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,7 @@ def _create_symlink(source, link_name, dwFlags):
error_desc = FormatError(code).strip()
if code == ERROR_PRIVILEGE_NOT_HELD:
raise OSError(errno.EPERM, error_desc, link_name)
_raise_winerror(
code, 'Error creating symbolic link "{}"'.format(link_name)
)
_raise_winerror(code, f'Error creating symbolic link "{link_name}"')


def islink(path):
Expand All @@ -210,7 +208,7 @@ def readlink(path):
)
if reparse_point_handle == INVALID_HANDLE_VALUE:
_raise_winerror(
get_last_error(), 'Error opening symbolic link "{}"'.format(path)
get_last_error(), f'Error opening symbolic link "{path}"'
)
target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
n_bytes_returned = DWORD()
Expand All @@ -227,7 +225,7 @@ def readlink(path):
CloseHandle(reparse_point_handle)
if not io_result:
_raise_winerror(
get_last_error(), 'Error reading symbolic link "{}"'.format(path)
get_last_error(), f'Error reading symbolic link "{path}"'
)
rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
Expand All @@ -236,11 +234,11 @@ def readlink(path):
return rdb.MountPointReparseBuffer.PrintName
# Unsupported reparse point type.
_raise_winerror(
ERROR_NOT_SUPPORTED, 'Error reading symbolic link "{}"'.format(path)
ERROR_NOT_SUPPORTED, f'Error reading symbolic link "{path}"'
)


def _raise_winerror(code, error_desc):
win_error_desc = FormatError(code).strip()
error_desc = "{0}: {1}".format(error_desc, win_error_desc)
error_desc = f"{error_desc}: {win_error_desc}"
raise WinError(code, error_desc)
Loading

0 comments on commit b32ccbb

Please sign in to comment.