Skip to content

Commit

Permalink
Fix ruff (#1305)
Browse files Browse the repository at this point in the history
  • Loading branch information
jelmer authored May 4, 2024
2 parents c226175 + 6481503 commit 04de218
Show file tree
Hide file tree
Showing 42 changed files with 171 additions and 170 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dulwich/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def tar_stream(store, tree, mtime, prefix=b"", format=""):
Bytestrings
"""
buf = BytesIO()
with closing(tarfile.open(None, "w:%s" % format, buf)) as tar:
with closing(tarfile.open(None, f"w:{format}", buf)) as tar:
if format == "gz":
# Manually correct the gzip header file modification time so that
# archives created from the same Git tree are always identical.
Expand Down
2 changes: 1 addition & 1 deletion dulwich/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def read_bundle(f):
return _read_bundle(f, 2)
if firstline == b"# v3 git bundle\n":
return _read_bundle(f, 3)
raise AssertionError("unsupported bundle format header: %r" % firstline)
raise AssertionError(f"unsupported bundle format header: {firstline!r}")


def write_bundle(f, bundle):
Expand Down
24 changes: 12 additions & 12 deletions dulwich/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,14 @@ def run(self, args):

basename, _ = os.path.splitext(args[0])
x = Pack(basename)
print("Object names checksum: %s" % x.name())
print("Checksum: %s" % sha_to_hex(x.get_stored_checksum()))
print(f"Object names checksum: {x.name()}")
print(f"Checksum: {sha_to_hex(x.get_stored_checksum())}")
if not x.check():
print("CHECKSUM DOES NOT MATCH")
print("Length: %d" % len(x))
for name in x:
try:
print("\t%s" % x[name])
print(f"\t{x[name]}")
except KeyError as k:
print(f"\t{name}: Unable to resolve base {k}")
except ApplyDeltaError as e:
Expand Down Expand Up @@ -284,7 +284,7 @@ def run(self, args):
branch=options.branch,
)
except GitProtocolError as e:
print("%s" % e)
print(f"{e}")


class cmd_commit(Command):
Expand Down Expand Up @@ -465,7 +465,7 @@ class cmd_write_tree(Command):
def run(self, args):
parser = optparse.OptionParser()
options, args = parser.parse_args(args)
sys.stdout.write("%s\n" % porcelain.write_tree("."))
sys.stdout.write("{}\n".format(porcelain.write_tree(".")))


class cmd_receive_pack(Command):
Expand Down Expand Up @@ -510,12 +510,12 @@ def run(self, args):
if status.unstaged:
sys.stdout.write("Changes not staged for commit:\n\n")
for name in status.unstaged:
sys.stdout.write("\t%s\n" % name.decode(sys.getfilesystemencoding()))
sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
sys.stdout.write("\n")
if status.untracked:
sys.stdout.write("Untracked files:\n\n")
for name in status.untracked:
sys.stdout.write("\t%s\n" % name)
sys.stdout.write(f"\t{name}\n")
sys.stdout.write("\n")


Expand Down Expand Up @@ -624,13 +624,13 @@ class SuperCommand(Command):

def run(self, args):
if not args and not self.default_command:
print("Supported subcommands: %s" % ", ".join(self.subcommands.keys()))
print("Supported subcommands: {}".format(", ".join(self.subcommands.keys())))
return False
cmd = args[0]
try:
cmd_kls = self.subcommands[cmd]
except KeyError:
print("No such subcommand: %s" % args[0])
print(f"No such subcommand: {args[0]}")
return False
return cmd_kls().run(args[1:])

Expand Down Expand Up @@ -746,7 +746,7 @@ def run(self, args):
if options.all:
print("Available commands:")
for cmd in sorted(commands):
print(" %s" % cmd)
print(f" {cmd}")
else:
print(
"""\
Expand Down Expand Up @@ -810,14 +810,14 @@ def main(argv=None):
argv = sys.argv[1:]

if len(argv) < 1:
print("Usage: dulwich <%s> [OPTIONS...]" % ("|".join(commands.keys())))
print("Usage: dulwich <{}> [OPTIONS...]".format("|".join(commands.keys())))
return 1

cmd = argv[0]
try:
cmd_kls = commands[cmd]
except KeyError:
print("No such subcommand: %s" % cmd)
print(f"No such subcommand: {cmd}")
return 1
# TODO(jelmer): Return non-0 on errors
return cmd_kls().run(argv[1:])
Expand Down
32 changes: 16 additions & 16 deletions dulwich/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ class InvalidWants(Exception):

def __init__(self, wants) -> None:
Exception.__init__(
self, "requested wants not in server provided refs: %r" % wants
self, f"requested wants not in server provided refs: {wants!r}"
)


Expand Down Expand Up @@ -216,7 +216,7 @@ def check(self):
elif status == b"ok":
yield rest, None
else:
raise GitProtocolError("invalid ref status %r" % status)
raise GitProtocolError(f"invalid ref status {status!r}")

def handle_packet(self, pkt):
"""Handle a packet.
Expand Down Expand Up @@ -416,13 +416,13 @@ def _read_shallow_updates(pkt_seq):
try:
cmd, sha = pkt.split(b" ", 1)
except ValueError:
raise GitProtocolError("unknown command %s" % pkt)
raise GitProtocolError(f"unknown command {pkt}")
if cmd == COMMAND_SHALLOW:
new_shallow.add(sha.strip())
elif cmd == COMMAND_UNSHALLOW:
new_unshallow.add(sha.strip())
else:
raise GitProtocolError("unknown command %s" % pkt)
raise GitProtocolError(f"unknown command {pkt}")
return (new_shallow, new_unshallow)


Expand Down Expand Up @@ -451,7 +451,7 @@ def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):

for refname in new_refs:
if not isinstance(refname, bytes):
raise TypeError("refname is not a bytestring: %r" % refname)
raise TypeError(f"refname is not a bytestring: {refname!r}")
old_sha1 = old_refs.get(refname, ZERO_SHA)
if not isinstance(old_sha1, bytes):
raise TypeError(
Expand Down Expand Up @@ -551,7 +551,7 @@ def _handle_upload_pack_head(proto, capabilities, graph_walker, wants, can_read,
break
else:
raise AssertionError(
"%s not in ('continue', 'ready', 'common)" % parts[2]
f"{parts[2]} not in ('continue', 'ready', 'common)"
)
have = next(graph_walker)
proto.write_pkt_line(COMMAND_DONE + b"\n")
Expand Down Expand Up @@ -1238,7 +1238,7 @@ def archive(
elif pkt.startswith(b"ERR "):
raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
else:
raise AssertionError("invalid response %r" % pkt)
raise AssertionError(f"invalid response {pkt!r}")
ret = proto.read_pkt_line()
if ret is not None:
raise AssertionError("expected pkt tail")
Expand Down Expand Up @@ -1282,7 +1282,7 @@ def _connect(self, cmd, path):
self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
s = None
err = OSError("no address found for %s" % self._host)
err = OSError(f"no address found for {self._host}")
for family, socktype, proto, canonname, sockaddr in sockaddrs:
s = socket.socket(family, socktype, proto)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Expand Down Expand Up @@ -1487,7 +1487,7 @@ def progress(x):
ref_status[refname] = msg
else:
if not target.refs.remove_if_equals(refname, old_sha1):
progress("unable to remove %s" % refname)
progress(f"unable to remove {refname}")
ref_status[refname] = "unable to remove"

return SendPackResult(new_refs, ref_status=ref_status)
Expand Down Expand Up @@ -1814,7 +1814,7 @@ def _connect(self, cmd, path):
def default_user_agent_string():
# Start user agent with "git/", because GitHub requires this. :-( See
# https://github.com/jelmer/dulwich/issues/562 for details.
return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))


def default_urllib3_manager(
Expand Down Expand Up @@ -2008,7 +2008,7 @@ def _discover_references(self, service, base_url):
tail = "info/refs"
headers = {"Accept": "*/*"}
if self.dumb is not True:
tail += "?service=%s" % service.decode("ascii")
tail += "?service={}".format(service.decode("ascii"))
url = urljoin(base_url, tail)
resp, read = self._http_request(url, headers)

Expand All @@ -2035,7 +2035,7 @@ def _discover_references(self, service, base_url):
) from exc
if pkt.rstrip(b"\n") != (b"# service=" + service):
raise GitProtocolError(
"unexpected first line %r from smart server" % pkt
f"unexpected first line {pkt!r} from smart server"
)
return (*read_pkt_refs(proto.read_pkt_seq()), base_url)
else:
Expand All @@ -2051,17 +2051,17 @@ def _smart_request(self, service, url, data):
"""
assert url[-1] == "/"
url = urljoin(url, service)
result_content_type = "application/x-%s-result" % service
result_content_type = f"application/x-{service}-result"
headers = {
"Content-Type": "application/x-%s-request" % service,
"Content-Type": f"application/x-{service}-request",
"Accept": result_content_type,
}
if isinstance(data, bytes):
headers["Content-Length"] = str(len(data))
resp, read = self._http_request(url, headers, data)
if resp.content_type.split(";")[0] != result_content_type:
raise GitProtocolError(
"Invalid content-type from server: %s" % resp.content_type
f"Invalid content-type from server: {resp.content_type}"
)
return resp, read

Expand Down Expand Up @@ -2398,7 +2398,7 @@ def _get_transport_and_path_from_url(url, config, operation, **kwargs):
parsed.path,
)

raise ValueError("unknown scheme '%s'" % parsed.scheme)
raise ValueError(f"unknown scheme '{parsed.scheme}'")


def parse_rsync_url(location: str) -> Tuple[Optional[str], str, str]:
Expand Down
12 changes: 6 additions & 6 deletions dulwich/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def get_boolean(
return True
elif value.lower() == b"false":
return False
raise ValueError("not a valid boolean string: %r" % value)
raise ValueError(f"not a valid boolean string: {value!r}")

def set(
self, section: SectionLike, name: NameLike, value: Union[ValueLike, bool]
Expand Down Expand Up @@ -492,15 +492,15 @@ def _parse_section_header_line(line: bytes) -> Tuple[Section, bytes]:
section: Section
if len(pts) == 2:
if pts[1][:1] != b'"' or pts[1][-1:] != b'"':
raise ValueError("Invalid subsection %r" % pts[1])
raise ValueError(f"Invalid subsection {pts[1]!r}")
else:
pts[1] = pts[1][1:-1]
if not _check_section_name(pts[0]):
raise ValueError("invalid section name %r" % pts[0])
raise ValueError(f"invalid section name {pts[0]!r}")
section = (pts[0], pts[1])
else:
if not _check_section_name(pts[0]):
raise ValueError("invalid section name %r" % pts[0])
raise ValueError(f"invalid section name {pts[0]!r}")
pts = pts[0].split(b".", 1)
if len(pts) == 2:
section = (pts[0], pts[1])
Expand Down Expand Up @@ -540,15 +540,15 @@ def from_file(cls, f: BinaryIO) -> "ConfigFile":
if _strip_comments(line).strip() == b"":
continue
if section is None:
raise ValueError("setting %r without section" % line)
raise ValueError(f"setting {line!r} without section")
try:
setting, value = line.split(b"=", 1)
except ValueError:
setting = line
value = b"true"
setting = setting.strip()
if not _check_variable_name(setting):
raise ValueError("invalid variable name %r" % setting)
raise ValueError(f"invalid variable name {setting!r}")
if value.endswith(b"\\\n"):
continuation = value[:-2]
elif value.endswith(b"\\\r\n"):
Expand Down
Loading

0 comments on commit 04de218

Please sign in to comment.