Jelmer Vernooij преди 1 година
родител
ревизия
26246d71f3

+ 18 - 10
dulwich/client.py

@@ -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:
@@ -888,9 +898,7 @@ class GitClient:
             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
 
@@ -940,9 +948,7 @@ class GitClient:
         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
@@ -1018,7 +1024,7 @@ class TraditionalGitClient(GitClient):
           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.
@@ -1618,6 +1624,7 @@ class SubprocessSSHVendor(SSHVendor):
 
         if ssh_command:
             import shlex
+
             args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
         else:
             args = ["ssh", "-x"]
@@ -1659,6 +1666,7 @@ class PLinkSSHVendor(SSHVendor):
     ):
         if ssh_command:
             import shlex
+
             args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
         elif sys.platform == "win32":
             args = ["plink.exe", "-ssh"]
@@ -2268,7 +2276,7 @@ class Urllib3HttpGitClient(AbstractHttpGitClient):
             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:

+ 2 - 4
dulwich/config.py

@@ -364,11 +364,9 @@ class ConfigDict(Config, MutableMapping[Section, MutableMapping[Name, Value]]):
 
 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:

+ 1 - 1
dulwich/contrib/requests_vendor.py

@@ -72,7 +72,7 @@ class RequestsHttpGitClient(AbstractHttpGitClient):
             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:

+ 3 - 1
dulwich/contrib/swift.py

@@ -305,7 +305,9 @@ class SwiftConnector:
             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):

+ 3 - 1
dulwich/contrib/test_release_robot.py

@@ -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)),
     }

+ 3 - 3
dulwich/contrib/test_swift.py

@@ -36,12 +36,12 @@ from ..tests.test_object_store import ObjectStoreTests
 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")
 
@@ -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])

+ 2 - 2
dulwich/contrib/test_swift_smoke.py

@@ -43,8 +43,8 @@ from gevent import monkey
 
 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:

+ 0 - 2
dulwich/fastexport.py

@@ -148,7 +148,6 @@ class GitImportProcessor(processor.ImportProcessor):
 
     def checkpoint_handler(self, cmd):
         """Process a CheckpointCommand."""
-        pass
 
     def commit_handler(self, cmd):
         """Process a CommitCommand."""
@@ -211,7 +210,6 @@ class GitImportProcessor(processor.ImportProcessor):
 
     def progress_handler(self, cmd):
         """Process a ProgressCommand."""
-        pass
 
     def _reset_base(self, commit_id):
         if self.last_commit == commit_id:

+ 2 - 2
dulwich/hooks.py

@@ -98,8 +98,8 @@ class ShellHook(Hook):
 
         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)

+ 3 - 3
dulwich/index.py

@@ -481,14 +481,14 @@ class Index:
         """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]]:
@@ -496,7 +496,7 @@ class Index:
         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:

+ 3 - 1
dulwich/pack.py

@@ -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:

+ 1 - 3
dulwich/porcelain.py

@@ -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.

+ 23 - 4
dulwich/protocol.py

@@ -77,10 +77,29 @@ COMMON_CAPABILITIES = [
     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
@@ -193,7 +212,7 @@ class Protocol:
         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:
@@ -203,7 +222,7 @@ class Protocol:
                 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:

+ 11 - 11
dulwich/repo.py

@@ -95,24 +95,24 @@ from .objects import (
     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"
@@ -1366,7 +1366,7 @@ class Repo(BaseRepo):
         from .index import Index
 
         if not self.has_index():
-            raise NoIndexPresent()
+            raise NoIndexPresent
         return Index(self.index_path())
 
     def has_index(self):
@@ -1915,7 +1915,7 @@ class MemoryRepo(BaseRepo):
         Raises:
           NoIndexPresent: Raised when no index is present
         """
-        raise NoIndexPresent()
+        raise NoIndexPresent
 
     def get_config(self):
         """Retrieve the config object.

+ 0 - 5
dulwich/tests/__init__.py

@@ -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",

+ 2 - 2
dulwich/tests/compat/test_client.py

@@ -73,10 +73,10 @@ class DulwichClientTestBase:
                 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()

+ 10 - 2
dulwich/tests/compat/test_pack.py

@@ -101,7 +101,11 @@ class TestPack(PackTests):
             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])
@@ -137,7 +141,11 @@ class TestPack(PackTests):
             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])

+ 22 - 6
dulwich/tests/test_client.py

@@ -726,10 +726,10 @@ class TestSSHVendor:
         class Subprocess:
             pass
 
-        setattr(Subprocess, "read", lambda: None)
-        setattr(Subprocess, "write", lambda: None)
-        setattr(Subprocess, "close", lambda: None)
-        setattr(Subprocess, "can_read", lambda: None)
+        Subprocess.read = lambda: None
+        Subprocess.write = lambda: None
+        Subprocess.close = lambda: None
+        Subprocess.can_read = lambda: None
         return Subprocess()
 
 
@@ -1571,7 +1571,15 @@ class PLinkSSHVendorTests(TestCase):
             binary = ["plink.exe", "-ssh"]
         else:
             binary = ["plink", "-ssh"]
-        expected = [*binary, "-pw", "12345", "-i", "/tmp/id_rsa", "host", "git-clone-url"]
+        expected = [
+            *binary,
+            "-pw",
+            "12345",
+            "-i",
+            "/tmp/id_rsa",
+            "host",
+            "git-clone-url",
+        ]
         self.assertListEqual(expected, args[0])
 
     def test_run_command_password(self):
@@ -1612,7 +1620,15 @@ class PLinkSSHVendorTests(TestCase):
             binary = ["plink.exe", "-ssh"]
         else:
             binary = ["plink", "-ssh"]
-        expected = [*binary, "-P", "2200", "-i", "/tmp/id_rsa", "user@host", "git-clone-url"]
+        expected = [
+            *binary,
+            "-P",
+            "2200",
+            "-i",
+            "/tmp/id_rsa",
+            "user@host",
+            "git-clone-url",
+        ]
 
         vendor = PLinkSSHVendor()
         command = vendor.run_command(

+ 1 - 1
dulwich/tests/test_greenthreads.py

@@ -56,7 +56,7 @@ def create_commit(marker=None):
 
 def init_store(store, count=1):
     ret = []
-    for i in range(0, count):
+    for i in range(count):
         objs = create_commit(marker=("%d" % i).encode("ascii"))
         for obj in objs:
             ret.append(obj)

+ 9 - 5
dulwich/tests/test_porcelain.py

@@ -2088,11 +2088,15 @@ class PushTests(PorcelainTestCase):
 
             # Get the change in the target repo corresponding to the add
             # this will be in the foo branch.
-            change = next(iter(tree_changes(
-                    self.repo,
-                    self.repo[b"HEAD"].tree,
-                    self.repo[b"refs/heads/foo"].tree,
-                )))
+            change = next(
+                iter(
+                    tree_changes(
+                        self.repo,
+                        self.repo[b"HEAD"].tree,
+                        self.repo[b"refs/heads/foo"].tree,
+                    )
+                )
+            )
             self.assertEqual(
                 os.path.basename(fullpath), change.new.path.decode("ascii")
             )

+ 2 - 1
dulwich/tests/test_repository.py

@@ -736,7 +736,8 @@ r = Repo('.')
 r.stage(['foo'])
 """.format(
             executable=sys.executable,
-            path=[os.path.join(os.path.dirname(__file__), "..", ".."), *sys.path])
+            path=[os.path.join(os.path.dirname(__file__), "..", ".."), *sys.path],
+        )
 
         repo_dir = os.path.join(self.mkdtemp())
         self.addCleanup(shutil.rmtree, repo_dir)

+ 1 - 1
dulwich/tests/test_server.py

@@ -82,7 +82,7 @@ class TestProto:
                 # flush-pkt ('0000').
                 return None
         else:
-            raise HangupException()
+            raise HangupException
 
     def write_sideband(self, band, data):
         self._received[band].append(data)

+ 1 - 1
dulwich/tests/test_web.py

@@ -160,7 +160,7 @@ class DumbHandlersTestCase(WebTestCase):
                 self._exc_class = exc_class
 
             def read(self, size=-1):
-                raise self._exc_class()
+                raise self._exc_class
 
             def close(self):
                 self.closed = True

+ 1 - 3
dulwich/tests/utils.py

@@ -29,7 +29,7 @@ import time
 import types
 import warnings
 
-from dulwich.tests import SkipTest, skipIf  # noqa: F401
+from dulwich.tests import SkipTest
 
 from ..index import commit_tree
 from ..objects import Commit, FixedSha, Tag, object_class
@@ -100,8 +100,6 @@ def make_object(cls, **attrs):
         with a __dict__ instead of __slots__.
         """
 
-        pass
-
     TestObject.__name__ = "TestObject_" + cls.__name__
 
     obj = TestObject()

+ 6 - 1
dulwich/web.py

@@ -393,7 +393,12 @@ class HTTPGitApplication:
       backend: the Backend object backing this application
     """
 
-    services: ClassVar[Dict[Tuple[str, re.Pattern], Callable[[HTTPGitRequest, Backend, re.Match], Iterator[bytes]]]] = {
+    services: ClassVar[
+        Dict[
+            Tuple[str, re.Pattern],
+            Callable[[HTTPGitRequest, Backend, re.Match], Iterator[bytes]],
+        ]
+    ] = {
         ("GET", re.compile("/HEAD$")): get_text_file,
         ("GET", re.compile("/info/refs$")): get_info_refs,
         ("GET", re.compile("/objects/info/alternates$")): get_text_file,

+ 2 - 0
pyproject.toml

@@ -74,7 +74,9 @@ select = [
     "E",
     "F",
     "I",
+    "PIE",
     "UP",
+    "RSE",
     "RUF",
 ]
 ignore = [