Skip to content

Commit 6e44250

Browse files
committed
ruff: apply dvc/scmrepo rules
1 parent b8e3a7c commit 6e44250

26 files changed

+217
-162
lines changed

pyproject.toml

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,52 @@ ignore = [
135135
"SIM108", # if-else-block-instead-of-if-exp
136136
"D203", # one blank line before class
137137
"D213", # multi-line-summary-second-line
138+
"RET501", # unnecessary-return-none
139+
"RET502", # implicit-return-value
140+
"RET503", # implicit-return
141+
"SIM117", # multiple-with-statements
142+
"N818", # error-suffix-on-exception-name
143+
]
144+
select = [
145+
"A", # flake8-buitlins
146+
"ASYNC", # flake8-async
147+
"B", # flake8-bugbear
148+
"BLE", # flake8-blind-except
149+
"C4", # flake8-comprehensions
150+
"C90", # mccabe
151+
"DTZ", # flake8-datetimez
152+
"E", # pycodestyle - Error
153+
"EXE", # flake8-executable
154+
"F", # pyflakes
155+
"FLY", # flynt-rules
156+
"G", # flake8-logging-format
157+
"I", # isort
158+
"ICN", # flake8-import-conventions
159+
"INP", # flake8-no-pep420
160+
"ISC", # flake8-implicit-str-concat
161+
"N", # pep8-naming
162+
"PERF101", # perflint
163+
"PGH", # pygrep-hooks
164+
"PIE", # flake8-pie
165+
"PL", # pylint
166+
"PT", # flake8-pytest-style
167+
"PYI", # flake8-pyi
168+
"Q", # flae8-quotes
169+
"RET", # flake8-return
170+
"RSE", # flake8-raise
171+
"RUF", # ruff
172+
"S", # flake8-bandit
173+
"SIM", # flake8-simplify
174+
"SLOT", # flake8-slots
175+
"T10", # flake8-debugger
176+
"T20", # flake8-print
177+
"TCH", # flake8-type-checking
178+
"TCH", # flake8-type-checking
179+
"TID", # flake8-tidy-imports
180+
"UP", # pyupgrade
181+
"W", # pycodestyle - Warning
182+
"YTT", # flake8-2020
138183
]
139-
select = ["ALL"]
140184
show-source = true
141185
show-fixes = true
142186

@@ -145,8 +189,16 @@ show-fixes = true
145189
"tests/**" = ["S", "ARG001", "ARG002", "ANN"]
146190
"docs/**" = ["INP"]
147191

192+
[tool.ruff.lint.flake8-pytest-style]
193+
fixture-parentheses = false
194+
mark-parentheses = false
195+
parametrize-names-type = "csv"
196+
148197
[tool.ruff.lint.flake8-type-checking]
149198
strict = true
150199

151200
[tool.ruff.lint.isort]
152201
known-first-party = ["scmrepo"]
202+
203+
[tool.ruff.pylint]
204+
max-args = 10

src/scmrepo/base.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ def root_dir(self) -> str:
1515
return self._root_dir
1616

1717
def __repr__(self):
18-
return "{class_name}: '{directory}'".format(
19-
class_name=type(self).__name__, directory=self.dir
20-
)
18+
return f"{type(self).__name__}: '{self.dir}'"
2119

2220
def __exit__(self, exc_type, exc_value, traceback):
2321
self.close()

src/scmrepo/fs.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,11 @@ class GitFileSystem(AbstractFileSystem):
3131

3232
def __init__(
3333
self,
34-
path: str = None,
35-
rev: str = None,
34+
path: Optional[str] = None,
35+
rev: Optional[str] = None,
3636
scm: "Git" = None,
3737
trie: "GitTrie" = None,
38-
rev_resolver: Callable[["Git", str], str] = None,
38+
rev_resolver: Optional[Callable[["Git", str], str]] = None,
3939
**kwargs,
4040
):
4141
from scmrepo.git import Git
@@ -213,8 +213,10 @@ def info(self, path: str, **kwargs: Any) -> Dict[str, Any]:
213213
ret = self.trie.info(key)
214214
ret["name"] = path
215215
return ret
216-
except KeyError:
217-
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)
216+
except KeyError as exc:
217+
raise FileNotFoundError(
218+
errno.ENOENT, os.strerror(errno.ENOENT), path
219+
) from exc
218220

219221
def exists(self, path: str, **kwargs: Any) -> bool:
220222
key = self._get_key(path)
@@ -255,7 +257,7 @@ def get_file(
255257

256258
with self.open(rpath, "rb", **kwargs) as f1:
257259
if outfile is None:
258-
outfile = open(lpath, "wb")
260+
outfile = open(lpath, "wb") # noqa: SIM115
259261

260262
try:
261263
callback.set_size(getattr(f1, "size", None))

src/scmrepo/git/__init__.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,17 @@
88
from collections.abc import Mapping
99
from contextlib import contextmanager
1010
from functools import partialmethod
11-
from typing import TYPE_CHECKING, Callable, Dict, Iterable, Optional, Tuple, Type, Union
11+
from typing import (
12+
TYPE_CHECKING,
13+
Callable,
14+
ClassVar,
15+
Dict,
16+
Iterable,
17+
Optional,
18+
Tuple,
19+
Type,
20+
Union,
21+
)
1222

1323
from funcy import cached_property, first
1424
from pathspec.patterns import GitWildMatchPattern
@@ -41,7 +51,7 @@
4151

4252

4353
class GitBackends(Mapping):
44-
DEFAULT: Dict[str, BackendCls] = {
54+
DEFAULT: ClassVar[Dict[str, BackendCls]] = {
4555
"dulwich": DulwichBackend,
4656
"pygit2": Pygit2Backend,
4757
"gitpython": GitPythonBackend,
@@ -312,7 +322,9 @@ def get_fs(self, rev: str):
312322
return GitFileSystem(scm=self, rev=rev)
313323

314324
@classmethod
315-
def init(cls, path: str, bare: bool = False, _backend: str = None) -> "Git":
325+
def init(
326+
cls, path: str, bare: bool = False, _backend: Optional[str] = None
327+
) -> "Git":
316328
for name, backend in GitBackends.DEFAULT.items():
317329
if _backend and name != _backend:
318330
continue

src/scmrepo/git/backend/base.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,13 @@
44
from typing import TYPE_CHECKING, Callable, Iterable, Mapping, Optional, Tuple, Union
55

66
from scmrepo.exceptions import SCMError
7-
8-
from ..objects import GitObject
7+
from scmrepo.git.objects import GitObject
98

109
if TYPE_CHECKING:
10+
from scmrepo.git.config import Config
11+
from scmrepo.git.objects import GitCommit, GitTag
1112
from scmrepo.progress import GitProgressEvent
1213

13-
from ..config import Config
14-
from ..objects import GitCommit, GitTag
15-
1614

1715
class NoGitBackendError(SCMError):
1816
def __init__(self, func):
@@ -50,7 +48,7 @@ def clone(
5048
url: str,
5149
to_path: str,
5250
shallow_branch: Optional[str] = None,
53-
progress: Callable[["GitProgressEvent"], None] = None,
51+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
5452
bare: bool = False,
5553
mirror: bool = False,
5654
):
@@ -229,7 +227,7 @@ def push_refspecs(
229227
refspecs: Union[str, Iterable[str]],
230228
force: bool = False,
231229
on_diverged: Optional[Callable[[str, str], bool]] = None,
232-
progress: Callable[["GitProgressEvent"], None] = None,
230+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
233231
**kwargs,
234232
) -> Mapping[str, SyncStatus]:
235233
"""Push refspec to a remote Git repo.
@@ -253,7 +251,7 @@ def fetch_refspecs(
253251
refspecs: Union[str, Iterable[str]],
254252
force: bool = False,
255253
on_diverged: Optional[Callable[[str, str], bool]] = None,
256-
progress: Callable[["GitProgressEvent"], None] = None,
254+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
257255
**kwargs,
258256
) -> Mapping[str, SyncStatus]:
259257
"""Fetch refspecs from a remote Git repo.
@@ -333,7 +331,7 @@ def diff(self, rev_a: str, rev_b: str, binary=False) -> str:
333331
"""Return the git diff for two commits."""
334332

335333
@abstractmethod
336-
def reset(self, hard: bool = False, paths: Iterable[str] = None):
334+
def reset(self, hard: bool = False, paths: Optional[Iterable[str]] = None):
337335
"""Reset current git HEAD."""
338336

339337
@abstractmethod

src/scmrepo/git/backend/dulwich/__init__.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,20 @@
2424
from funcy import cached_property, reraise
2525

2626
from scmrepo.exceptions import AuthError, CloneError, InvalidRemote, RevError, SCMError
27+
from scmrepo.git.backend.base import BaseGitBackend, SyncStatus
28+
from scmrepo.git.config import Config
29+
from scmrepo.git.objects import GitObject, GitTag
2730
from scmrepo.progress import GitProgressReporter
2831
from scmrepo.utils import relpath
2932

30-
from ...config import Config
31-
from ...objects import GitObject, GitTag
32-
from ..base import BaseGitBackend, SyncStatus
33-
3433
if TYPE_CHECKING:
3534
from dulwich.client import SSHVendor
3635
from dulwich.config import ConfigFile, StackedConfig
3736
from dulwich.repo import Repo
3837

38+
from scmrepo.git.objects import GitCommit
3939
from scmrepo.progress import GitProgressEvent
4040

41-
from ...objects import GitCommit
42-
4341

4442
logger = logging.getLogger(__name__)
4543

@@ -82,7 +80,7 @@ def mode(self) -> int:
8280

8381
def scandir(self) -> Iterable["DulwichObject"]:
8482
tree = self.repo[self._sha]
85-
for entry in tree.iteritems(): # noqa: B301
83+
for entry in tree.iteritems():
8684
yield DulwichObject(self.repo, entry.path.decode(), entry.mode, entry.sha)
8785

8886
@cached_property
@@ -232,7 +230,7 @@ def clone(
232230
url: str,
233231
to_path: str,
234232
shallow_branch: Optional[str] = None,
235-
progress: Callable[["GitProgressEvent"], None] = None,
233+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
236234
bare: bool = False,
237235
mirror: bool = False,
238236
):
@@ -271,7 +269,7 @@ def clone(
271269
cls._set_mirror(repo, progress=progress)
272270
else:
273271
cls._set_default_tracking_branch(repo)
274-
except Exception as exc:
272+
except Exception as exc: # noqa: BLE001
275273
raise CloneError(url, to_path) from exc
276274

277275
@staticmethod
@@ -291,7 +289,7 @@ def _set_default_tracking_branch(repo: "Repo"):
291289

292290
@staticmethod
293291
def _set_mirror(
294-
repo: "Repo", progress: Callable[["GitProgressEvent"], None] = None
292+
repo: "Repo", progress: Optional[Callable[["GitProgressEvent"], None]] = None
295293
):
296294
from dulwich.porcelain import NoneStream, fetch
297295

@@ -458,10 +456,7 @@ def untracked_files(self) -> Iterable[str]:
458456
def is_tracked(self, path: str) -> bool:
459457
rel = relpath(path, self.root_dir).replace(os.path.sep, "/").encode()
460458
rel_dir = rel + b"/"
461-
for p in self.repo.open_index():
462-
if p == rel or p.startswith(rel_dir):
463-
return True
464-
return False
459+
return any(p == rel or p.startswith(rel_dir) for p in self.repo.open_index())
465460

466461
def is_dirty(self, untracked_files: bool = False) -> bool:
467462
kwargs: Dict[str, Any] = {} if untracked_files else {"untracked_files": "no"}
@@ -590,7 +585,7 @@ def iter_remote_refs(self, url: str, base: Optional[str] = None, **kwargs):
590585
try:
591586
_remote, location = get_remote_repo(self.repo, url)
592587
client, path = get_transport_and_path(location, **kwargs)
593-
except Exception as exc:
588+
except Exception as exc: # noqa: BLE001
594589
raise InvalidRemote(url) from exc
595590

596591
try:
@@ -616,7 +611,7 @@ def push_refspecs( # noqa: C901
616611
refspecs: Union[str, Iterable[str]],
617612
force: bool = False,
618613
on_diverged: Optional[Callable[[str, str], bool]] = None,
619-
progress: Callable[["GitProgressEvent"], None] = None,
614+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
620615
**kwargs,
621616
) -> Mapping[str, SyncStatus]:
622617
from dulwich.client import HTTPUnauthorized, get_transport_and_path
@@ -627,7 +622,7 @@ def push_refspecs( # noqa: C901
627622
try:
628623
_remote, location = get_remote_repo(self.repo, url)
629624
client, path = get_transport_and_path(location, **kwargs)
630-
except Exception as exc:
625+
except Exception as exc: # noqa: BLE001
631626
raise SCMError(f"'{url}' is not a valid Git remote or URL") from exc
632627

633628
change_result = {}
@@ -700,7 +695,7 @@ def fetch_refspecs(
700695
refspecs: Union[str, Iterable[str]],
701696
force: bool = False,
702697
on_diverged: Optional[Callable[[str, str], bool]] = None,
703-
progress: Callable[["GitProgressEvent"], None] = None,
698+
progress: Optional[Callable[["GitProgressEvent"], None]] = None,
704699
**kwargs,
705700
) -> Mapping[str, SyncStatus]:
706701
from dulwich.client import get_transport_and_path
@@ -868,7 +863,7 @@ def diff(self, rev_a: str, rev_b: str, binary=False) -> str:
868863
write_tree_diff(buf, self.repo.object_store, commit_a.tree, commit_b.tree)
869864
return buf.getvalue().decode("utf-8")
870865

871-
def reset(self, hard: bool = False, paths: Iterable[str] = None):
866+
def reset(self, hard: bool = False, paths: Optional[Iterable[str]] = None):
872867
raise NotImplementedError
873868

874869
def checkout_index(
@@ -920,7 +915,7 @@ def validate_git_remote(self, url: str, **kwargs):
920915
try:
921916
_, location = get_remote_repo(self.repo, url)
922917
client, path = get_transport_and_path(location, **kwargs)
923-
except Exception as exc:
918+
except Exception as exc: # noqa: BLE001
924919
raise InvalidRemote(url) from exc
925920
if isinstance(client, LocalGitClient) and not os.path.exists(
926921
os.path.join("", path)

src/scmrepo/git/backend/dulwich/asyncssh_vendor.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def _process_public_key_ok_gh(self, _pkttype, _pktid, packet):
129129
b"rsa-sha2-512",
130130
)
131131
)
132-
or (algorithm != b"ssh-rsa" and algorithm != self._keypair.algorithm)
132+
or (algorithm not in (b"ssh-rsa", self._keypair.algorithm))
133133
or key_data != self._keypair.public_data
134134
):
135135
raise ProtocolError("Key mismatch")
@@ -141,7 +141,11 @@ def _process_public_key_ok_gh(self, _pkttype, _pktid, packet):
141141
class InteractiveSSHClient(SSHClient):
142142
_conn: Optional["SSHClientConnection"] = None
143143
_keys_to_try: Optional[List["FilePath"]] = None
144-
_passphrases: Dict[str, str] = {}
144+
_passphrases: Dict[str, str]
145+
146+
def __init__(self, *args, **kwargs):
147+
super(*args, **kwargs)
148+
_passphrases: Dict[str, str] = {}
145149

146150
def connection_made(self, conn: "SSHClientConnection") -> None:
147151
self._conn = conn
@@ -150,7 +154,7 @@ def connection_made(self, conn: "SSHClientConnection") -> None:
150154
def connection_lost(self, exc: Optional[Exception]) -> None:
151155
self._conn = None
152156

153-
async def public_key_auth_requested( # pylint: disable=invalid-overridden-method
157+
async def public_key_auth_requested( # noqa: C901, PLR0912
154158
self,
155159
) -> Optional["KeyPairListArg"]:
156160
from asyncssh.public_key import (
@@ -246,7 +250,7 @@ def _getpass(prompt: str) -> str:
246250
return getpass(prompt=prompt).rstrip()
247251

248252
if instructions:
249-
print(instructions)
253+
pass
250254
loop = asyncio.get_running_loop()
251255
return [
252256
await loop.run_in_executor(

0 commit comments

Comments
 (0)