Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 23, 2024
1 parent b7c4655 commit fc725f3
Show file tree
Hide file tree
Showing 31 changed files with 280 additions and 143 deletions.
4 changes: 3 additions & 1 deletion src/scmrepo/asyn.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ def get_loop() -> asyncio.AbstractEventLoop:

class BaseAsyncObject:
def __init__(
self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any
self,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any,
) -> None:
self._loop: asyncio.AbstractEventLoop = loop or get_loop()
self._pid = os.getpid()
Expand Down
6 changes: 2 additions & 4 deletions src/scmrepo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,15 @@ def root_dir(self) -> str:
return self._root_dir

def __repr__(self):
return "{class_name}: '{directory}'".format(
class_name=type(self).__name__, directory=self.dir
)
return f"{type(self).__name__}: '{self.dir}'"

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

@property
def dir(self):
"""Path to a directory with SCM specific information."""
return None
return

@staticmethod
def is_repo(root_dir): # pylint: disable=unused-argument
Expand Down
13 changes: 10 additions & 3 deletions src/scmrepo/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ def _open(
raise FileNotFoundError(errno.ENOENT, msg, path) from exc
except IsADirectoryError as exc:
raise IsADirectoryError(
errno.EISDIR, os.strerror(errno.EISDIR), path
errno.EISDIR,
os.strerror(errno.EISDIR),
path,
) from exc

def info(self, path: str, **kwargs: Any) -> Dict[str, Any]:
Expand Down Expand Up @@ -242,7 +244,12 @@ def ls(self, path, detail=True, **kwargs):
return [self.info(_path) for _path in paths]

def get_file(
self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs
self,
rpath,
lpath,
callback=_DEFAULT_CALLBACK,
outfile=None,
**kwargs,
):
# NOTE: temporary workaround while waiting for
# https://github.com/fsspec/filesystem_spec/pull/1191
Expand All @@ -251,7 +258,7 @@ def get_file(
outfile = lpath
elif self.isdir(rpath):
os.makedirs(lpath, exist_ok=True)
return None
return

with self.open(rpath, "rb", **kwargs) as f1:
if outfile is None:
Expand Down
6 changes: 4 additions & 2 deletions src/scmrepo/git/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def _get_gitignore(self, path):

if not os.path.realpath(gitignore).startswith(self.root_dir + os.sep):
raise FileNotInRepoError(
f"'{path}' is outside of git repository '{self.root_dir}'"
f"'{path}' is outside of git repository '{self.root_dir}'",
)

return entry, gitignore
Expand Down Expand Up @@ -333,7 +333,9 @@ def add_commit(
self.commit(msg=message)

_fetch_refspecs = partialmethod(
_backend_func, "fetch_refspecs", backends=["pygit2", "dulwich"]
_backend_func,
"fetch_refspecs",
backends=["pygit2", "dulwich"],
)

def fetch_refspecs(
Expand Down
13 changes: 12 additions & 1 deletion src/scmrepo/git/backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ def push_refspecs(
"""Push refspec to a remote Git repo.
Args:
----
url: Git remote name or absolute Git URL.
refspecs: Iterable containing refspecs to push.
Note that this will not match subkeys.
Expand All @@ -259,6 +260,7 @@ def fetch_refspecs(
"""Fetch refspecs from a remote Git repo.
Args:
----
url: Git remote name or absolute Git URL.
refspecs: Iterable containing refspecs to fetch.
Note that this will not match subkeys.
Expand All @@ -270,6 +272,7 @@ def fetch_refspecs(
on_diverged(local_refname, remote_sha)
Returns:
-------
Mapping of local_refname to sync status.
"""

Expand Down Expand Up @@ -348,7 +351,9 @@ def checkout_index(

@abstractmethod
def status(
self, ignored: bool = False, untracked_files: str = "all"
self,
ignored: bool = False,
untracked_files: str = "all",
) -> Tuple[Mapping[str, Iterable[str]], Iterable[str], Iterable[str]]:
"""Return tuple of (staged_files, unstaged_files, untracked_files).
Expand Down Expand Up @@ -382,6 +387,7 @@ def merge(
"""Merge specified commit into the current (working copy) branch.
Args:
----
rev: Git revision to merge.
commit: If True, merge will be committed using `msg` as the commit
message. If False, the merge changes will be staged but not
Expand Down Expand Up @@ -415,9 +421,11 @@ def get_tag(self, name: str) -> Optional[Union[str, "GitTag"]]:
"""Return the specified tag object.
Args:
----
name: Tag name (without 'refs/tags/' prefix).
Returns:
-------
None if the specified tag does not exist.
String SHA for the target object if the tag is a lightweight tag.
GitTag object if the tag is an annotated tag.
Expand All @@ -428,6 +436,7 @@ def get_config(self, path: Optional[str] = None) -> "Config":
"""Return a Git config object.
Args:
----
path: If set, a config object for the specified config file will be
returned. By default, the standard Git system/global/repo config
stack object will be returned.
Expand All @@ -443,11 +452,13 @@ def check_attr(
"""Return the value of the specified attribute for a pathname.
Args:
----
path: Pathname to check.
attr: Attribute to check.
source: Optional tree-ish source to check.
Returns:
-------
None when the attribute is not defined for the path (unspecified).
True when the attribute is defined as true (set).
False when the attribute is defined as false (unset).
Expand Down
34 changes: 22 additions & 12 deletions src/scmrepo/git/backend/dulwich/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def mode(self) -> int:

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

@cached_property
Expand Down Expand Up @@ -126,7 +126,7 @@ def _get_ssh_vendor() -> "SSHVendor":
if sys.platform == "win32" and os.environ.get("MSYSTEM") and shutil.which("ssh"):
# see https://github.com/iterative/dvc/issues/7702
logger.debug(
"dulwich: native win32 Python inside MSYS2/git-bash, using MSYS2 OpenSSH"
"dulwich: native win32 Python inside MSYS2/git-bash, using MSYS2 OpenSSH",
)
return SubprocessSSHVendor()

Expand Down Expand Up @@ -188,7 +188,9 @@ class DulwichBackend(BaseGitBackend): # pylint:disable=abstract-method
BAR_FMT_NOTOTAL = "{desc}{bar:b}|{postfix[info]} [{elapsed}]"

def __init__( # pylint:disable=W0231
self, root_dir=os.curdir, search_parent_directories=True
self,
root_dir=os.curdir,
search_parent_directories=True,
):
from dulwich.errors import NotGitRepository
from dulwich.repo import Repo
Expand Down Expand Up @@ -291,7 +293,8 @@ def _set_default_tracking_branch(repo: "Repo"):

@staticmethod
def _set_mirror(
repo: "Repo", progress: Callable[["GitProgressEvent"], None] = None
repo: "Repo",
progress: Callable[["GitProgressEvent"], None] = None,
):
from dulwich.porcelain import NoneStream, fetch

Expand Down Expand Up @@ -343,7 +346,7 @@ def add(
# NOTE: we need git/unix separator to compare against index
# paths but repo.stage() expects to be called with OS paths
self.repo.stage(
[fname for fname in files if fname.replace(b"\\", b"/") in index]
[fname for fname in files if fname.replace(b"\\", b"/") in index],
)
else:
self.repo.stage([fname for fname in files if fname in index])
Expand Down Expand Up @@ -539,7 +542,10 @@ def set_ref(
if symbolic:
return self.repo.refs.set_symbolic_ref(name_b, new_ref_b, message=message_b)
if not self.repo.refs.set_if_equals(
name_b, old_ref_b, new_ref_b, message=message_b
name_b,
old_ref_b,
new_ref_b,
message=message_b,
):
raise SCMError(f"Failed to set '{name}'")

Expand Down Expand Up @@ -637,7 +643,7 @@ def update_refs(refs):
from dulwich.objects import ZERO_SHA

selected_refs.extend(
parse_reftuples(self.repo.refs, refs, refspecs, force=force)
parse_reftuples(self.repo.refs, refs, refspecs, force=force),
)
new_refs = {}
for lh, rh, _ in selected_refs:
Expand Down Expand Up @@ -689,7 +695,7 @@ def update_refs(refs):
f"{os.fsdecode(ref)}: {reason}"
for ref, reason in result.ref_status.items()
if reason is not None
)
),
)
raise SCMError(f"Git failed to push some refs to '{url}' ({reasons})")
return change_result
Expand Down Expand Up @@ -723,7 +729,7 @@ def determine_wants(
if isinstance(refspecs, str)
else [os.fsencode(refspec) for refspec in refspecs],
force=force,
)
),
)
return [
remote_refs[lh]
Expand Down Expand Up @@ -881,14 +887,18 @@ def checkout_index(
raise NotImplementedError

def status(
self, ignored: bool = False, untracked_files: str = "all"
self,
ignored: bool = False,
untracked_files: str = "all",
) -> Tuple[Mapping[str, Iterable[str]], Iterable[str], Iterable[str]]:
from dulwich.porcelain import Error
from dulwich.porcelain import status as git_status

with reraise(Error, SCMError("Git status failed")):
staged, unstaged, untracked = git_status(
self.root_dir, ignored=ignored, untracked_files=untracked_files
self.root_dir,
ignored=ignored,
untracked_files=untracked_files,
)

return (
Expand Down Expand Up @@ -923,7 +933,7 @@ def validate_git_remote(self, url: str, **kwargs):
except Exception as exc:
raise InvalidRemote(url) from exc
if isinstance(client, LocalGitClient) and not os.path.exists(
os.path.join("", path)
os.path.join("", path),
):
raise InvalidRemote(url)

Expand Down
9 changes: 7 additions & 2 deletions src/scmrepo/git/backend/dulwich/asyncssh_vendor.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ async def _read_private_key_interactive(self, path: "FilePath") -> "SSHKey":
loop = asyncio.get_running_loop()
for _ in range(3):
passphrase = await loop.run_in_executor(
None, getpass, f"Enter passphrase for key '{path}': "
None,
getpass,
f"Enter passphrase for key '{path}': ",
)
if passphrase:
try:
Expand Down Expand Up @@ -250,7 +252,9 @@ def _getpass(prompt: str) -> str:
loop = asyncio.get_running_loop()
return [
await loop.run_in_executor(
None, _getpass, f"({name}) {prompt}" if name else prompt
None,
_getpass,
f"({name}) {prompt}" if name else prompt,
)
for prompt, _ in prompts
]
Expand All @@ -276,6 +280,7 @@ async def _run_command(
with the remote command.
Args:
----
host: Host name
command: Command to run (as argv array)
username: Optional ame of user to log in as
Expand Down
8 changes: 6 additions & 2 deletions src/scmrepo/git/backend/dulwich/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def _cached_data() -> Iterator[bytes]:

try:
result = super()._http_request(
url, headers=headers, data=None if data is None else _cached_data()
url,
headers=headers,
data=None if data is None else _cached_data(),
)
except HTTPUnauthorized:
auth_header = self._get_auth()
Expand All @@ -58,7 +60,9 @@ def _cached_data() -> Iterator[bytes]:
else:
headers = auth_header
result = super()._http_request(
url, headers=headers, data=None if data is None else _cached_data()
url,
headers=headers,
data=None if data is None else _cached_data(),
)
if self._store_credentials is not None:
self._store_credentials.approve()
Expand Down
22 changes: 16 additions & 6 deletions src/scmrepo/git/backend/gitpython.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,17 @@ class GitPythonBackend(BaseGitBackend): # pylint:disable=abstract-method

@requires_git
def __init__( # pylint:disable=W0231
self, root_dir=os.curdir, search_parent_directories=True
self,
root_dir=os.curdir,
search_parent_directories=True,
):
import git
from git.exc import InvalidGitRepositoryError

try:
self.repo = git.Repo(
root_dir, search_parent_directories=search_parent_directories
root_dir,
search_parent_directories=search_parent_directories,
)
except InvalidGitRepositoryError:
msg = "{} is not a git repository"
Expand Down Expand Up @@ -374,7 +377,10 @@ def list_all_commits(self):
return [
c.hexsha
for c in self.repo.iter_commits(
rev=head, branches=True, tags=True, remotes=True
rev=head,
branches=True,
tags=True,
remotes=True,
)
]

Expand Down Expand Up @@ -536,7 +542,9 @@ def get_refs_containing(self, rev: str, pattern: Optional[str] = None):
else:
args = []
for line in self.git.for_each_ref(
*args, contains=rev, format=r"%(refname)"
*args,
contains=rev,
format=r"%(refname)",
).splitlines():
line = line.strip()
if line:
Expand Down Expand Up @@ -619,7 +627,7 @@ def _stash_apply(
out = str(exc)
if "CONFLICT" in out or "already exists" in out:
raise MergeConflictError(
"Stash apply resulted in merge conflicts"
"Stash apply resulted in merge conflicts",
) from exc
raise SCMError("Could not apply stash") from exc

Expand Down Expand Up @@ -698,7 +706,9 @@ def checkout_index(
self.repo.index.checkout(paths=paths_list, force=force)

def status(
self, ignored: bool = False, untracked_files: str = "all"
self,
ignored: bool = False,
untracked_files: str = "all",
) -> Tuple[Mapping[str, Iterable[str]], Iterable[str], Iterable[str]]:
raise NotImplementedError

Expand Down
Loading

0 comments on commit fc725f3

Please sign in to comment.