Skip to content

Commit

Permalink
Apply more ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jelmer committed Nov 26, 2023
1 parent ce10dd1 commit 26246d7
Show file tree
Hide file tree
Showing 26 changed files with 132 additions and 76 deletions.
28 changes: 18 additions & 10 deletions dulwich/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,18 @@ def _win32_peek_avail(handle):


COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
UPLOAD_CAPABILITIES = [CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_SHALLOW, *COMMON_CAPABILITIES]
RECEIVE_CAPABILITIES = [CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, *COMMON_CAPABILITIES]
UPLOAD_CAPABILITIES = [
CAPABILITY_THIN_PACK,
CAPABILITY_MULTI_ACK,
CAPABILITY_MULTI_ACK_DETAILED,
CAPABILITY_SHALLOW,
*COMMON_CAPABILITIES,
]
RECEIVE_CAPABILITIES = [
CAPABILITY_REPORT_STATUS,
CAPABILITY_DELETE_REFS,
*COMMON_CAPABILITIES,
]


class ReportStatusParser:
Expand Down Expand Up @@ -888,9 +898,7 @@ def _negotiate_receive_pack_capabilities(self, server_capabilities):
k, v = parse_capability(capability)
if k == CAPABILITY_AGENT:
agent = v
unknown_capabilities = ( # noqa: F841
extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES
)
(extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
# TODO(jelmer): warn about unknown capabilities
return negotiated_capabilities, agent

Expand Down Expand Up @@ -940,9 +948,7 @@ def progress(x):
return None

def _negotiate_upload_pack_capabilities(self, server_capabilities):
unknown_capabilities = ( # noqa: F841
extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES
)
(extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
# TODO(jelmer): warn about unknown capabilities
symrefs = {}
agent = None
Expand Down Expand Up @@ -1018,7 +1024,7 @@ async def _connect(self, cmd, path):
cmd: The git service name to which we should connect.
path: The path we should pass to the service. (as bytestirng)
"""
raise NotImplementedError()
raise NotImplementedError

def send_pack(self, path, update_refs, generate_pack_data, progress=None):
"""Upload a pack to a remote repository.
Expand Down Expand Up @@ -1618,6 +1624,7 @@ def run_command(

if ssh_command:
import shlex

args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
else:
args = ["ssh", "-x"]
Expand Down Expand Up @@ -1659,6 +1666,7 @@ def run_command(
):
if ssh_command:
import shlex

args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
elif sys.platform == "win32":
args = ["plink.exe", "-ssh"]
Expand Down Expand Up @@ -2268,7 +2276,7 @@ def _http_request(self, url, headers=None, data=None):
raise GitProtocolError(str(e)) from e

if resp.status == 404:
raise NotGitRepository()
raise NotGitRepository
if resp.status == 401:
raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
if resp.status == 407:
Expand Down
6 changes: 2 additions & 4 deletions dulwich/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,11 +364,9 @@ def sections(self) -> Iterator[Section]:

def _format_string(value: bytes) -> bytes:
if (
value.startswith(b" ")
or value.startswith(b"\t")
or value.endswith(b" ")
value.startswith((b" ", b"\t"))
or value.endswith((b" ", b"\t"))
or b"#" in value
or value.endswith(b"\t")
):
return b'"' + _escape_value(value) + b'"'
else:
Expand Down
2 changes: 1 addition & 1 deletion dulwich/contrib/requests_vendor.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def _http_request(self, url, headers=None, data=None, allow_compression=False):
resp = self.session.get(url, headers=req_headers)

if resp.status_code == 404:
raise NotGitRepository()
raise NotGitRepository
if resp.status_code == 401:
raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
if resp.status_code == 407:
Expand Down
4 changes: 3 additions & 1 deletion dulwich/contrib/swift.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,9 @@ def swift_auth_v2(self):
o_store for o_store in catalogs if o_store["type"] == "object-store"
)
endpoints = object_store["endpoints"]
endpoint = next(endp for endp in endpoints if endp["region"] == self.region_name)
endpoint = next(
endp for endp in endpoints if endp["region"] == self.region_name
)
return endpoint[self.endpoint_type], token

def test_root_exists(self):
Expand Down
4 changes: 3 additions & 1 deletion dulwich/contrib/test_release_robot.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ class GetRecentTagsTest(unittest.TestCase):
test_repo = os.path.join(BASEDIR, "dulwich_test_repo.zip")
committer = b"Mark Mikofski <mark.mikofski@sunpowercorp.com>"
test_tags: ClassVar[List[bytes]] = [b"v0.1a", b"v0.1"]
tag_test_data: ClassVar[Dict[bytes, Tuple[int, bytes, Optional[Tuple[int, bytes]]]]] = {
tag_test_data: ClassVar[
Dict[bytes, Tuple[int, bytes, Optional[Tuple[int, bytes]]]]
] = {
test_tags[0]: (1484788003, b"3" * 40, None),
test_tags[1]: (1484788314, b"1" * 40, (1484788401, b"2" * 40)),
}
Expand Down
6 changes: 3 additions & 3 deletions dulwich/contrib/test_swift.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@
missing_libs = []

try:
import gevent # noqa:F401
import gevent # noqa: F401
except ModuleNotFoundError:
missing_libs.append("gevent")

try:
import geventhttpclient # noqa:F401
import geventhttpclient # noqa: F401
except ModuleNotFoundError:
missing_libs.append("geventhttpclient")

Expand Down Expand Up @@ -170,7 +170,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):
for i in range(length):
_marker = (f"{marker}_{i}").encode()
blob, tree, tag, cmt = create_commit(data, _marker)
data.extend([blob, tree, tag, cmt])
Expand Down
4 changes: 2 additions & 2 deletions dulwich/contrib/test_swift_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@

monkey.patch_all()

from dulwich import client, index, objects, repo, server # noqa:E402
from dulwich.contrib import swift # noqa:E402
from dulwich import client, index, objects, repo, server # noqa: E402
from dulwich.contrib import swift # noqa: E402


class DulwichServer:
Expand Down
2 changes: 0 additions & 2 deletions dulwich/fastexport.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ def blob_handler(self, cmd):

def checkpoint_handler(self, cmd):
"""Process a CheckpointCommand."""
pass

def commit_handler(self, cmd):
"""Process a CommitCommand."""
Expand Down Expand Up @@ -211,7 +210,6 @@ def commit_handler(self, cmd):

def progress_handler(self, cmd):
"""Process a ProgressCommand."""
pass

def _reset_base(self, commit_id):
if self.last_commit == commit_id:
Expand Down
4 changes: 2 additions & 2 deletions dulwich/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ def execute(self, *args):

try:
ret = subprocess.call(
[os.path.relpath(self.filepath, self.cwd), *list(args)],
cwd=self.cwd)
[os.path.relpath(self.filepath, self.cwd), *list(args)], cwd=self.cwd
)
if ret != 0:
if self.post_exec_callback is not None:
self.post_exec_callback(0, *args)
Expand Down
6 changes: 3 additions & 3 deletions dulwich/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,22 +481,22 @@ def get_sha1(self, path: bytes) -> bytes:
"""Return the (git object) SHA1 for the object at a path."""
value = self[path]
if isinstance(value, ConflictedIndexEntry):
raise UnmergedEntries()
raise UnmergedEntries
return value.sha

def get_mode(self, path: bytes) -> int:
"""Return the POSIX file mode for the object at a path."""
value = self[path]
if isinstance(value, ConflictedIndexEntry):
raise UnmergedEntries()
raise UnmergedEntries
return value.mode

def iterobjects(self) -> Iterable[Tuple[bytes, bytes, int]]:
"""Iterate over path, sha, mode tuples for use with commit_tree."""
for path in self:
entry = self[path]
if isinstance(entry, ConflictedIndexEntry):
raise UnmergedEntries()
raise UnmergedEntries
yield path, entry.sha, cleanup_mode(entry.mode)

def has_conflicts(self) -> bool:
Expand Down
4 changes: 3 additions & 1 deletion dulwich/pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -1914,7 +1914,9 @@ def pack_objects_to_data(
return (
count,
deltify_pack_objects(
iter(objects), window_size=delta_window_size, progress=progress # type: ignore
iter(objects), # type: ignore
window_size=delta_window_size,
progress=progress,
),
)
else:
Expand Down
4 changes: 1 addition & 3 deletions dulwich/porcelain.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,9 +624,7 @@ def clean(repo=".", target_dir=None):
raise Error("target_dir must be in the repo's working dir")

config = r.get_config_stack()
require_force = config.get_boolean( # noqa: F841
(b"clean",), b"requireForce", True
)
config.get_boolean((b"clean",), b"requireForce", True)

# TODO(jelmer): if require_force is set, then make sure that -f, -i or
# -n is specified.
Expand Down
27 changes: 23 additions & 4 deletions dulwich/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,29 @@
CAPABILITY_NO_PROGRESS,
]
KNOWN_UPLOAD_CAPABILITIES = set(
[*COMMON_CAPABILITIES, CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK, CAPABILITY_MULTI_ACK_DETAILED, CAPABILITY_INCLUDE_TAG, CAPABILITY_DEEPEN_SINCE, CAPABILITY_SYMREF, CAPABILITY_SHALLOW, CAPABILITY_DEEPEN_NOT, CAPABILITY_DEEPEN_RELATIVE, CAPABILITY_ALLOW_TIP_SHA1_IN_WANT, CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT]
[
*COMMON_CAPABILITIES,
CAPABILITY_THIN_PACK,
CAPABILITY_MULTI_ACK,
CAPABILITY_MULTI_ACK_DETAILED,
CAPABILITY_INCLUDE_TAG,
CAPABILITY_DEEPEN_SINCE,
CAPABILITY_SYMREF,
CAPABILITY_SHALLOW,
CAPABILITY_DEEPEN_NOT,
CAPABILITY_DEEPEN_RELATIVE,
CAPABILITY_ALLOW_TIP_SHA1_IN_WANT,
CAPABILITY_ALLOW_REACHABLE_SHA1_IN_WANT,
]
)
KNOWN_RECEIVE_CAPABILITIES = set(
[*COMMON_CAPABILITIES, CAPABILITY_REPORT_STATUS, CAPABILITY_DELETE_REFS, CAPABILITY_QUIET, CAPABILITY_ATOMIC]
[
*COMMON_CAPABILITIES,
CAPABILITY_REPORT_STATUS,
CAPABILITY_DELETE_REFS,
CAPABILITY_QUIET,
CAPABILITY_ATOMIC,
]
)

DEPTH_INFINITE = 0x7FFFFFFF
Expand Down Expand Up @@ -193,7 +212,7 @@ def read_pkt_line(self):
try:
sizestr = read(4)
if not sizestr:
raise HangupException()
raise HangupException
size = int(sizestr, 16)
if size == 0 or size == 1: # flush-pkt or delim-pkt
if self.report_activity:
Expand All @@ -203,7 +222,7 @@ def read_pkt_line(self):
self.report_activity(size, "read")
pkt_contents = read(size - 4)
except ConnectionResetError as exc:
raise HangupException() from exc
raise HangupException from exc
except OSError as exc:
raise GitProtocolError(str(exc)) from exc
else:
Expand Down
22 changes: 11 additions & 11 deletions dulwich/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,24 +95,24 @@
valid_hexsha,
)
from .pack import generate_unpacked_objects
from .refs import ( # noqa: F401
ANNOTATED_TAG_SUFFIX,
from .refs import (
ANNOTATED_TAG_SUFFIX, # noqa: F401
LOCAL_BRANCH_PREFIX,
LOCAL_TAG_PREFIX,
SYMREF,
LOCAL_TAG_PREFIX, # noqa: F401
SYMREF, # noqa: F401
DictRefsContainer,
DiskRefsContainer,
InfoRefsContainer,
InfoRefsContainer, # noqa: F401
Ref,
RefsContainer,
_set_default_branch,
_set_head,
_set_origin_head,
check_ref_format,
read_packed_refs,
read_packed_refs_with_peeled,
check_ref_format, # noqa: F401
read_packed_refs, # noqa: F401
read_packed_refs_with_peeled, # noqa: F401
serialize_refs,
write_packed_refs,
write_packed_refs, # noqa: F401
)

CONTROLDIR = ".git"
Expand Down Expand Up @@ -1366,7 +1366,7 @@ def open_index(self) -> "Index":
from .index import Index

if not self.has_index():
raise NoIndexPresent()
raise NoIndexPresent
return Index(self.index_path())

def has_index(self):
Expand Down Expand Up @@ -1915,7 +1915,7 @@ def open_index(self):
Raises:
NoIndexPresent: Raised when no index is present
"""
raise NoIndexPresent()
raise NoIndexPresent

def get_config(self):
"""Retrieve the config object.
Expand Down
5 changes: 0 additions & 5 deletions dulwich/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,6 @@ def self_test_suite():


def tutorial_test_suite():
import dulwich.client
import dulwich.config
import dulwich.index
import dulwich.patch # noqa: F401

tutorial = [
"introduction",
"file-format",
Expand Down
4 changes: 2 additions & 2 deletions dulwich/tests/compat/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ def assertDestEqualsSrc(self):
self.assertReposEqual(src, dest)

def _client(self):
raise NotImplementedError()
raise NotImplementedError

def _build_path(self):
raise NotImplementedError()
raise NotImplementedError

def _do_send_pack(self):
c = self._client()
Expand Down
12 changes: 10 additions & 2 deletions dulwich/tests/compat/test_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,11 @@ def test_delta_medium_object(self):
new_blob.data = orig_blob.data + (b"x" * 2**20)
new_blob_2 = Blob()
new_blob_2.data = new_blob.data + b"y"
all_to_pack = [*list(orig_pack.pack_tuples()), (new_blob, None), (new_blob_2, None)]
all_to_pack = [
*list(orig_pack.pack_tuples()),
(new_blob, None),
(new_blob_2, None),
]
pack_path = os.path.join(self._tempdir, "pack_with_deltas")
write_pack(pack_path, all_to_pack, deltify=True)
output = run_git_or_fail(["verify-pack", "-v", pack_path])
Expand Down Expand Up @@ -137,7 +141,11 @@ def test_delta_large_object(self):
new_blob.data = "big blob" + ("x" * 2**25)
new_blob_2 = Blob()
new_blob_2.data = new_blob.data + "y"
all_to_pack = [*list(orig_pack.pack_tuples()), (new_blob, None), (new_blob_2, None)]
all_to_pack = [
*list(orig_pack.pack_tuples()),
(new_blob, None),
(new_blob_2, None),
]
pack_path = os.path.join(self._tempdir, "pack_with_deltas")
write_pack(pack_path, all_to_pack, deltify=True)
output = run_git_or_fail(["verify-pack", "-v", pack_path])
Expand Down
Loading

0 comments on commit 26246d7

Please sign in to comment.