Skip to content

Commit a34a2f6

Browse files
committed
refactor!: dir to pathlib, BaseRepo.path -> BaseRepo.dir
1 parent 6daa714 commit a34a2f6

File tree

7 files changed

+40
-37
lines changed

7 files changed

+40
-37
lines changed

libvcs/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def fn(
163163
remote_repos_path=remote_repos_path,
164164
remote_repo_name=remote_repo_name
165165
if remote_repo_name is not None
166-
else faker.word(),
166+
else faker.slug(),
167167
remote_repo_post_init=remote_repo_post_init,
168168
)
169169

libvcs/states/base.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""Base class for Repository objects."""
22
import logging
3-
import os
3+
import pathlib
44
from typing import NamedTuple
55
from urllib import parse as urlparse
66

7+
from libvcs.types import StrOrPath
78
from libvcs.util import CmdLoggingAdapter, mkdir_p, run
89

910
logger = logging.getLogger(__name__)
@@ -40,7 +41,7 @@ class BaseRepo:
4041
#: vcs app name, e.g. 'git'
4142
bin_name = ""
4243

43-
def __init__(self, url, dir, progress_callback=None, *args, **kwargs):
44+
def __init__(self, url, dir: StrOrPath, progress_callback=None, *args, **kwargs):
4445
r"""
4546
Parameters
4647
----------
@@ -58,7 +59,7 @@ def __init__(self, url, dir, progress_callback=None, *args, **kwargs):
5859
... def obtain(self, *args, **kwargs):
5960
... self.ensure_dir()
6061
... self.run(
61-
... ['clone', '--progress', self.url, self.path],
62+
... ['clone', '--progress', self.url, self.dir],
6263
... log_in_real_time=True
6364
... )
6465
>>> r = Repo(
@@ -72,22 +73,26 @@ def __init__(self, url, dir, progress_callback=None, *args, **kwargs):
7273
remote: Counting objects: 100% (...), done...
7374
remote: Total ... (delta 0), reused 0 (delta 0), pack-reused 0...
7475
Receiving objects: 100% (...), done...
75-
>>> assert os.path.exists(r.path)
76-
>>> assert os.path.exists(r.path + '/.git')
76+
>>> assert r.dir.exists()
77+
>>> assert pathlib.Path(r.dir / '.git').exists()
7778
"""
7879
self.url = url
7980

8081
#: Callback for run updates
8182
self.progress_callback = progress_callback
8283

83-
#: Parent directory
84-
self.parent_dir = os.path.dirname(dir)
84+
#: Directory to check out
85+
self.dir: pathlib.Path
86+
if isinstance(dir, pathlib.Path):
87+
self.dir = dir
88+
else:
89+
self.dir = pathlib.Path(dir)
8590

86-
#: Checkout path
87-
self.path = dir
91+
#: Parent directory
92+
self.parent_dir = self.dir.parent
8893

8994
#: Base name of checkout
90-
self.repo_name = os.path.basename(os.path.normpath(dir))
95+
self.repo_name = self.dir.stem
9196

9297
if "rev" in kwargs:
9398
self.rev = kwargs["rev"]
@@ -124,12 +129,12 @@ def run(
124129
"""Return combined stderr/stdout from a command.
125130
126131
This method will also prefix the VCS command bin_name. By default runs
127-
using the cwd `libvcs.base.BaseRepo.path` of the repo.
132+
using the cwd `libvcs.base.BaseRepo.dir` of the repo.
128133
129134
Parameters
130135
----------
131136
cwd : str
132-
dir command is run from, defaults to `libvcs.base.BaseRepo.path`.
137+
dir command is run from, defaults to `libvcs.base.BaseRepo.dir`.
133138
134139
check_returncode : bool
135140
Indicate whether a :exc:`~exc.CommandError` should be raised if return code
@@ -142,7 +147,7 @@ def run(
142147
"""
143148

144149
if cwd is None:
145-
cwd = getattr(self, "path", None)
150+
cwd = getattr(self, "dir", None)
146151

147152
cmd = [self.bin_name] + cmd
148153

@@ -158,18 +163,17 @@ def run(
158163

159164
def ensure_dir(self, *args, **kwargs):
160165
"""Assure destination path exists. If not, create directories."""
161-
if os.path.exists(self.path):
166+
if self.dir.exists():
162167
return True
163168

164-
if not os.path.exists(self.parent_dir):
169+
if not self.parent_dir.exists():
165170
mkdir_p(self.parent_dir)
166171

167-
if not os.path.exists(self.path):
172+
if not self.dir.exists():
168173
self.log.debug(
169-
"Repo directory for %s does not exist @ %s"
170-
% (self.repo_name, self.path)
174+
"Repo directory for %s does not exist @ %s" % (self.repo_name, self.dir)
171175
)
172-
mkdir_p(self.path)
176+
mkdir_p(self.dir)
173177

174178
return True
175179

libvcs/states/git.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- [`GitRepo.get_git_version`](libvcs.git.GitRepo.get_git_version)
1616
""" # NOQA: E501
1717
import logging
18-
import os
18+
import pathlib
1919
import re
2020
from typing import Dict, NamedTuple, Optional, TypedDict, Union
2121
from urllib import parse as urlparse
@@ -160,7 +160,7 @@ def __init__(
160160
import os
161161
from libvcs.git import GitRepo
162162
163-
checkout = os.path.dirname(os.path.abspath(__name__)) + '/' + 'my_libvcs'
163+
checkout = pathlib.Path(__name__) + '/' + 'my_libvcs'
164164
165165
repo = GitRepo(
166166
url="https://github.com/vcs-python/libvcs",
@@ -175,7 +175,7 @@ def __init__(
175175
import os
176176
from libvcs.git import GitRepo
177177
178-
checkout = os.path.dirname(os.path.abspath(__name__)) + '/' + 'my_libvcs'
178+
checkout = pathlib.Path(__name__) + '/' + 'my_libvcs'
179179
180180
repo = GitRepo(
181181
url="https://github.com/vcs-python/libvcs",
@@ -295,7 +295,7 @@ def obtain(self, *args, **kwargs):
295295
cmd.extend(["--depth", "1"])
296296
if self.tls_verify:
297297
cmd.extend(["-c", "http.sslVerify=false"])
298-
cmd.extend([url, self.path])
298+
cmd.extend([url, self.dir])
299299

300300
self.log.info("Cloning.")
301301
self.run(cmd, log_in_real_time=True)
@@ -310,7 +310,7 @@ def obtain(self, *args, **kwargs):
310310
def update_repo(self, set_remotes: bool = False, *args, **kwargs):
311311
self.ensure_dir()
312312

313-
if not os.path.isdir(os.path.join(self.path, ".git")):
313+
if not pathlib.Path(self.dir / ".git").is_dir():
314314
self.obtain()
315315
self.update_repo(set_remotes=set_remotes)
316316
return
@@ -433,7 +433,7 @@ def update_repo(self, set_remotes: bool = False, *args, **kwargs):
433433

434434
self.log.error(
435435
"\nFailed to rebase in: '%s'.\n"
436-
"You will have to resolve the conflicts manually" % self.path
436+
"You will have to resolve the conflicts manually" % self.dir
437437
)
438438
return
439439

@@ -452,7 +452,7 @@ def update_repo(self, set_remotes: bool = False, *args, **kwargs):
452452
self.log.error(
453453
"\nFailed to rebase in: '%s'.\n"
454454
"You will have to resolve the "
455-
"conflicts manually" % self.path
455+
"conflicts manually" % self.dir
456456
)
457457
return
458458

libvcs/states/hg.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
- [`MercurialRepo.get_revision`](libvcs.hg.MercurialRepo.get_revision)
1010
""" # NOQA E5
1111
import logging
12-
import os
12+
import pathlib
1313

1414
from .base import BaseRepo
1515

@@ -28,15 +28,15 @@ def obtain(self, *args, **kwargs):
2828

2929
# Double hyphens between [OPTION]... -- SOURCE [DEST] prevent command injections
3030
# via aliases
31-
self.run(["clone", "--noupdate", "-q", "--", self.url, self.path])
31+
self.run(["clone", "--noupdate", "-q", "--", self.url, self.dir])
3232
self.run(["update", "-q"])
3333

3434
def get_revision(self):
3535
return self.run(["parents", "--template={rev}"])
3636

3737
def update_repo(self, *args, **kwargs):
3838
self.ensure_dir()
39-
if not os.path.isdir(os.path.join(self.path, ".hg")):
39+
if not pathlib.Path(self.dir / ".hg").exists():
4040
self.obtain()
4141
self.update_repo()
4242
else:

libvcs/states/svn.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
""" # NOQA: E5
1515
import logging
1616
import os
17+
import pathlib
1718
import re
1819
from urllib import parse as urlparse
1920

@@ -74,7 +75,7 @@ def obtain(self, quiet=None):
7475
cmd.append("--trust-server-cert")
7576
cmd.extend(self._user_pw_args())
7677
cmd.extend(get_rev_options(url, rev))
77-
cmd.append(self.path)
78+
cmd.append(self.dir)
7879

7980
self.run(cmd)
8081

@@ -122,8 +123,8 @@ def get_revision(self, location=None):
122123

123124
def update_repo(self, dest=None, *args, **kwargs):
124125
self.ensure_dir()
125-
if os.path.isdir(os.path.join(self.path, ".svn")):
126-
dest = self.path if not dest else dest
126+
if pathlib.Path(self.dir / ".svn").exists():
127+
dest = self.dir if not dest else dest
127128

128129
url, rev = self.url, self.rev
129130

tests/states/test_base.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,7 @@ class Repo(BaseRepo):
5656

5757
def obtain(self, *args, **kwargs):
5858
self.ensure_dir()
59-
self.run(
60-
["clone", "--progress", self.url, self.path], log_in_real_time=True
61-
)
59+
self.run(["clone", "--progress", self.url, self.dir], log_in_real_time=True)
6260

6361
r = Repo(
6462
url=f"file://{str(git_remote_repo)}",

tests/states/test_git.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,7 @@ def test_get_current_remote_name(git_repo: GitRepo):
589589

590590
new_remote_name = "new_remote_name"
591591
git_repo.set_remote(
592-
name=new_remote_name, url=f"file://{git_repo.path}", overwrite=True
592+
name=new_remote_name, url=f"file://{git_repo.dir}", overwrite=True
593593
)
594594
git_repo.run(["fetch", new_remote_name])
595595
git_repo.run(["branch", "--set-upstream-to", f"{new_remote_name}/{new_branch}"])

0 commit comments

Comments
 (0)