Skip to content

Commit

Permalink
Upgrade to >= python 3.7
Browse files Browse the repository at this point in the history
  • Loading branch information
jelmer committed Jun 3, 2023
1 parent 3eea76c commit 2fab330
Show file tree
Hide file tree
Showing 38 changed files with 113 additions and 115 deletions.
14 changes: 7 additions & 7 deletions dulwich/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,15 @@ def run(self, args):
refs = client.fetch(path, r, progress=sys.stdout.write)
print("Remote refs:")
for item in refs.items():
print("%s -> %s" % item)
print("{} -> {}".format(*item))


class cmd_fsck(Command):
def run(self, args):
opts, args = getopt(args, "", [])
opts = dict(opts)
for (obj, msg) in porcelain.fsck("."):
print("{}: {}".format(obj, msg))
print(f"{obj}: {msg}")


class cmd_log(Command):
Expand Down Expand Up @@ -203,9 +203,9 @@ def run(self, args):
try:
print("\t%s" % x[name])
except KeyError as k:
print("\t{}: Unable to resolve base {}".format(name, k))
print(f"\t{name}: Unable to resolve base {k}")
except ApplyDeltaError as e:
print("\t{}: Unable to apply delta: {!r}".format(name, e))
print(f"\t{name}: Unable to apply delta: {e!r}")


class cmd_dump_index(Command):
Expand Down Expand Up @@ -488,7 +488,7 @@ def run(self, args):
for kind, names in status.staged.items():
for name in names:
sys.stdout.write(
"\t{}: {}\n".format(kind, name.decode(sys.getfilesystemencoding()))
f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
)
sys.stdout.write("\n")
if status.unstaged:
Expand All @@ -511,7 +511,7 @@ def run(self, args):
sys.exit(1)
refs = porcelain.ls_remote(args[0])
for ref in sorted(refs):
sys.stdout.write("{}\t{}\n".format(ref, refs[ref]))
sys.stdout.write(f"{ref}\t{refs[ref]}\n")


class cmd_ls_tree(Command):
Expand Down Expand Up @@ -635,7 +635,7 @@ def run(self, argv):
parser = argparse.ArgumentParser()
parser.parse_args(argv)
for path, sha in porcelain.submodule_list("."):
sys.stdout.write(' {} {}\n'.format(sha, path))
sys.stdout.write(f' {sha} {path}\n')


class cmd_submodule_init(Command):
Expand Down
35 changes: 9 additions & 26 deletions dulwich/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
Expand Down Expand Up @@ -407,7 +406,7 @@ def __getattribute__(self, name):
return super().__getattribute__(name)

def __repr__(self) -> str:
return "{}({!r}, {!r})".format(self.__class__.__name__, self.refs, self.agent)
return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})"


def _read_shallow_updates(pkt_seq):
Expand Down Expand Up @@ -454,12 +453,12 @@ def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):
old_sha1 = old_refs.get(refname, ZERO_SHA)
if not isinstance(old_sha1, bytes):
raise TypeError(
"old sha1 for {!r} is not a bytestring: {!r}".format(refname, old_sha1)
f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}"
)
new_sha1 = new_refs.get(refname, ZERO_SHA)
if not isinstance(new_sha1, bytes):
raise TypeError(
"old sha1 for {!r} is not a bytestring {!r}".format(refname, new_sha1)
f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}"
)

if old_sha1 != new_sha1:
Expand Down Expand Up @@ -510,9 +509,6 @@ def _handle_upload_pack_head(
can_read: function that returns a boolean that indicates
whether there is extra graph data to read on proto
depth: Depth for request
Returns:
"""
assert isinstance(wants, list) and isinstance(wants[0], bytes)
proto.write_pkt_line(
Expand Down Expand Up @@ -582,9 +578,6 @@ def _handle_upload_pack_tail(
pack_data: Function to call with pack data
progress: Optional progress reporting function
rbufsize: Read buffer size
Returns:
"""
pkt = proto.read_pkt_line()
while pkt:
Expand Down Expand Up @@ -866,9 +859,6 @@ def get_refs(self, path):
Args:
path: Path to the repo to fetch from. (as bytestring)
Returns:
"""
raise NotImplementedError(self.get_refs)

Expand Down Expand Up @@ -975,9 +965,6 @@ def check_wants(wants, refs):
Args:
wants: Set of object SHAs to fetch
refs: Refs dictionary to check against
Returns:
"""
missing = set(wants) - {
v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
Expand Down Expand Up @@ -1269,7 +1256,7 @@ def _connect(self, cmd, path):
self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
s = None
err = socket.error("no address found for %s" % self._host)
err = OSError("no address found for %s" % 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 @@ -1465,7 +1452,7 @@ def progress(x):
old_sha1 = old_refs.get(refname, ZERO_SHA)
if new_sha1 != ZERO_SHA:
if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
msg = "unable to set {} to {}".format(refname, new_sha1)
msg = f"unable to set {refname} to {new_sha1}"
progress(msg)
ref_status[refname] = msg
else:
Expand Down Expand Up @@ -1577,9 +1564,6 @@ def run_command(
password: Optional ssh password for login or private key
key_filename: Optional path to private keyfile
ssh_command: Optional SSH command
Returns:
"""
raise NotImplementedError(self.run_command)

Expand Down Expand Up @@ -1624,7 +1608,7 @@ def run_command(
args.extend(["-i", str(key_filename)])

if username:
host = "{}@{}".format(username, host)
host = f"{username}@{host}"
if host.startswith("-"):
raise StrangeHostname(hostname=host)
args.append(host)
Expand Down Expand Up @@ -1678,7 +1662,7 @@ def run_command(
args.extend(["-i", str(key_filename)])

if username:
host = "{}@{}".format(username, host)
host = f"{username}@{host}"
if host.startswith("-"):
raise StrangeHostname(hostname=host)
args.append(host)
Expand Down Expand Up @@ -1981,8 +1965,7 @@ def _discover_references(self, service, base_url):
# Something changed (redirect!), so let's update the base URL
if not resp.redirect_location.endswith(tail):
raise GitProtocolError(
"Redirected from URL %s to URL %s without %s"
% (url, resp.redirect_location, tail)
f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
)
base_url = urljoin(url, resp.redirect_location[: -len(tail)])

Expand Down Expand Up @@ -2374,7 +2357,7 @@ def get_transport_and_path(
location: str,
config: Optional[Config] = None,
operation: Optional[str] = None,
**kwargs: Any
**kwargs
) -> Tuple[GitClient, str]:
"""Obtain a git client from a URL.
Expand Down
8 changes: 4 additions & 4 deletions dulwich/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
import sys
from contextlib import suppress
from typing import (
Any,
BinaryIO,
Dict,
Iterable,
Iterator,
KeysView,
Expand All @@ -40,8 +42,6 @@
Tuple,
Union,
overload,
Any,
Dict,
)

from .file import GitFile
Expand Down Expand Up @@ -268,7 +268,7 @@ def __init__(
self._values = CaseInsensitiveOrderedMultiDict.make(values)

def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, self._values)
return f"{self.__class__.__name__}({self._values!r})"

def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__) and other._values == self._values
Expand Down Expand Up @@ -688,7 +688,7 @@ def __init__(
self.writable = writable

def __repr__(self) -> str:
return "<{} for {!r}>".format(self.__class__.__name__, self.backends)
return f"<{self.__class__.__name__} for {self.backends!r}>"

@classmethod
def default(cls) -> "StackedConfig":
Expand Down
8 changes: 3 additions & 5 deletions dulwich/contrib/swift.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,7 @@ def swift_auth_v1(self):
if ret.status_code < 200 or ret.status_code >= 300:
raise SwiftException(
"AUTH v1.0 request failed on "
+ "%s with error code %s (%s)"
% (
+ "{} with error code {} ({})".format(
str(auth_httpclient.get_base_url()) + path,
ret.status_code,
str(ret.items()),
Expand Down Expand Up @@ -294,8 +293,7 @@ def swift_auth_v2(self):
if ret.status_code < 200 or ret.status_code >= 300:
raise SwiftException(
"AUTH v2.0 request failed on "
+ "%s with error code %s (%s)"
% (
+ "{} with error code {} ({})".format(
str(auth_httpclient.get_base_url()) + path,
ret.status_code,
str(ret.items()),
Expand Down Expand Up @@ -495,7 +493,7 @@ def _read(self, more=False):
self.buff_length = self.buff_length * 2
offset = self.base_offset
r = min(self.base_offset + self.buff_length, self.pack_length)
ret = self.scon.get_object(self.filename, range="{}-{}".format(offset, r))
ret = self.scon.get_object(self.filename, range=f"{offset}-{r}")
self.buff = ret

def read(self, length):
Expand Down
2 changes: 1 addition & 1 deletion dulwich/contrib/test_swift.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def create_commit(data, marker=b"Default", blob=None):
def create_commits(length=1, marker=b"Default"):
data = []
for i in range(0, length):
_marker = ("{}_{}".format(marker, i)).encode()
_marker = (f"{marker}_{i}").encode()
blob, tree, tag, cmt = create_commit(data, _marker)
data.extend([blob, tree, tag, cmt])
return data
Expand Down
6 changes: 3 additions & 3 deletions dulwich/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ def __init__(self, expected, got, extra=None) -> None:
if self.extra is None:
Exception.__init__(
self,
"Checksum mismatch: Expected {}, got {}".format(expected, got),
f"Checksum mismatch: Expected {expected}, got {got}",
)
else:
Exception.__init__(
self,
"Checksum mismatch: Expected {}, got {}; {}".format(expected, got, extra),
f"Checksum mismatch: Expected {expected}, got {got}; {extra}",
)


Expand All @@ -64,7 +64,7 @@ class WrongObjectException(Exception):
type_name: str

def __init__(self, sha, *args, **kwargs) -> None:
Exception.__init__(self, "{} is not a {}".format(sha, self.type_name))
Exception.__init__(self, f"{sha} is not a {self.type_name}")


class NotCommitError(WrongObjectException):
Expand Down
6 changes: 3 additions & 3 deletions dulwich/greenthreads.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@

"""Utility module for querying an ObjectStore with gevent."""

from typing import FrozenSet, Optional, Set, Tuple

import gevent
from gevent import pool

from typing import Set, Tuple, Optional, FrozenSet

from .object_store import (
MissingObjectFinder,
_collect_ancestors,
_collect_filetree_revs,
)
from .objects import Commit, Tag, ObjectID
from .objects import Commit, ObjectID, Tag


def _split_commits_and_tags(obj_store, lst, *, ignore_unknown=False, pool=None):
Expand Down
2 changes: 1 addition & 1 deletion dulwich/ignore.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def from_path(cls, path, ignorecase: bool = False) -> "IgnoreFilter":
def __repr__(self) -> str:
path = getattr(self, "_path", None)
if path is not None:
return "{}.from_path({!r})".format(type(self).__name__, path)
return f"{type(self).__name__}.from_path({path!r})"
else:
return "<%s>" % (type(self).__name__)

Expand Down
2 changes: 1 addition & 1 deletion dulwich/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ def path(self):
return self._filename

def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, self._filename)
return f"{self.__class__.__name__}({self._filename!r})"

def write(self) -> None:
"""Write current contents of index to disk."""
Expand Down
12 changes: 6 additions & 6 deletions dulwich/line_ending.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
# License, Version 2.0.
#
"""All line-ending related functions, from conversions to config processing.
r"""All line-ending related functions, from conversions to config processing.
Line-ending normalization is a complex beast. Here is some notes and details
about how it seems to work.
Expand Down Expand Up @@ -61,23 +61,23 @@
First, a repository can contains a ``.gitattributes`` file (or more than one...)
that can further customize the operation on some file patterns, for example:
\\*.txt text
\*.txt text
Force all ``.txt`` files to be treated as text files and to have their lines
endings normalized.
\\*.jpg -text
\*.jpg -text
Force all ``.jpg`` files to be treated as binary files and to not have their
lines endings converted.
\\*.vcproj text eol=crlf
\*.vcproj text eol=crlf
Force all ``.vcproj`` files to be treated as text files and to have their lines
endings converted into ``CRLF`` in working directory no matter the native EOL of
the platform.
\\*.sh text eol=lf
\*.sh text eol=lf
Force all ``.sh`` files to be treated as text files and to have their lines
endings converted into ``LF`` in working directory no matter the native EOL of
Expand All @@ -86,7 +86,7 @@
If the ``eol`` attribute is not defined, Git uses the ``core.eol`` configuration
value described later.
\\* text=auto
\* text=auto
Force all files to be scanned by the text file heuristic detection and to have
their line endings normalized in case they are detected as text files.
Expand Down
Loading

0 comments on commit 2fab330

Please sign in to comment.