Skip to content

Commit 2c30f5c

Browse files
committed
chore(ruff): Manual fixes (27 errors)
scripts/generate_gitlab.py:45:8: PTH113 `os.path.isfile()` should be replaced by `Path.is_file()` scripts/generate_gitlab.py:60:19: SIM115 Use context handler for opening files scripts/generate_gitlab.py:60:19: PTH123 `open()` should be replaced by `Path.open()` scripts/generate_gitlab.py:75:15: PTH109 `os.getcwd()` should be replaced by `Path.cwd()` scripts/generate_gitlab.py:93:15: TRY002 Create your own exception scripts/generate_gitlab.py:93:15: TRY003 Avoid specifying long messages outside the exception class src/vcspull/_internal/config_reader.py:105:19: SIM115 Use context handler for opening files src/vcspull/_internal/config_reader.py:105:19: PTH123 `open()` should be replaced by `Path.open()` src/vcspull/cli/sync.py:95:9: PERF203 `try`-`except` within a loop incurs performance overhead src/vcspull/cli/sync.py:107:21: B904 Within an `except` clause, raise exceptions with `raise ... from err` or `raise ... from None` to distinguish them from errors in exception handling src/vcspull/cli/sync.py:107:21: TRY200 Use `raise from` to specify exception cause src/vcspull/cli/sync.py:147:19: TRY002 Create your own exception src/vcspull/cli/sync.py:147:19: TRY003 Avoid specifying long messages outside the exception class src/vcspull/config.py:31:45: B008 Do not perform function call `pathlib.Path.cwd` in argument defaults src/vcspull/config.py:47:25: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/config.py:55:50: B008 Do not perform function call `pathlib.Path.cwd` in argument defaults src/vcspull/config.py:145:32: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/config.py:147:32: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/config.py:214:29: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/config.py:230:52: B008 Do not perform function call `pathlib.Path.cwd` in argument defaults src/vcspull/config.py:336:13: PERF401 Use a list comprehension to create a transformed list src/vcspull/util.py:12:21: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/util.py:34:22: PTH118 `os.path.join()` should be replaced by `Path` with `/` operator src/vcspull/util.py:41:16: PTH111 `os.path.expanduser()` should be replaced by `Path.expanduser()` src/vcspull/util.py:42:12: PTH112 `os.path.isdir()` should be replaced by `Path.is_dir()` tests/test_config_file.py:96:13: PERF401 Use a list comprehension to create a transformed list tests/test_config_file.py:393:10: B017 `pytest.raises(Exception)` should be considered evil Found 27 errors.
1 parent 9628ac6 commit 2c30f5c

File tree

6 files changed

+59
-45
lines changed

6 files changed

+59
-45
lines changed

scripts/generate_gitlab.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
import argparse
44
import os
5+
import pathlib
56
import sys
67

78
import requests
89
import yaml
910
from libvcs.sync.git import GitRemote
1011

11-
from vcspull.cli.sync import guess_vcs
12+
from vcspull.cli.sync import CouldNotGuessVCSFromURL, guess_vcs
1213
from vcspull.types import RawConfig
1314

1415
try:
@@ -39,10 +40,10 @@
3940
args = vars(parser.parse_args())
4041
gitlab_host = args["gitlab_host"]
4142
gitlab_namespace = args["gitlab_namespace"]
42-
config_filename = args["config_file_name"]
43+
config_filename = pathlib.Path(args["config_file_name"])
4344

4445
try:
45-
if os.path.isfile(config_filename):
46+
if config_filename.is_file():
4647
result = input(
4748
"The target config file (%s) already exists, \
4849
do you want to overwrite it? [y/N] "
@@ -57,9 +58,9 @@
5758
)
5859
sys.exit(0)
5960

60-
config_file = open(config_filename, "w")
61+
config_file = config_filename.open(mode="w")
6162
except OSError:
62-
print("File %s not accesible" % (config_filename))
63+
print(f"File {config_filename} not accesible")
6364
sys.exit(1)
6465

6566
response = requests.get(
@@ -72,9 +73,10 @@
7273
print("Error: ", response)
7374
sys.exit(1)
7475

75-
path_prefix = os.getcwd()
76+
path_prefix = pathlib.Path().cwd()
7677
config: RawConfig = {}
7778

79+
7880
for group in response.json():
7981
url_to_repo = group["ssh_url_to_repo"].replace(":", "/")
8082
namespace_path = group["namespace"]["full_path"]
@@ -90,7 +92,7 @@
9092

9193
vcs = guess_vcs(url_to_repo)
9294
if vcs is None:
93-
raise Exception(f"Could not guess VCS for URL: {url_to_repo}")
95+
raise CouldNotGuessVCSFromURL(url_to_repo)
9496

9597
config[path][reponame] = {
9698
"name": reponame,

src/vcspull/_internal/config_reader.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def _from_file(cls, path: pathlib.Path) -> dict[str, t.Any]:
102102
{'session_name': 'my session'}
103103
"""
104104
assert isinstance(path, pathlib.Path)
105-
content = open(path).read()
105+
content = path.open().read()
106106

107107
if path.suffix in [".yaml", ".yml"]:
108108
format: "FormatLiteral" = "yaml"

src/vcspull/cli/sync.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ def sync(
9292
for repo in found_repos:
9393
try:
9494
update_repo(repo)
95-
except Exception:
96-
print(
95+
except Exception as e: # noqa: PERF203
96+
log.info(
9797
f'Failed syncing {repo.get("name")}',
9898
)
9999
if log.isEnabledFor(logging.DEBUG):
@@ -103,8 +103,7 @@ def sync(
103103
if exit_on_error:
104104
if parser is not None:
105105
parser.exit(status=1, message=EXIT_ON_ERROR_MSG)
106-
else:
107-
raise SystemExit(EXIT_ON_ERROR_MSG)
106+
raise SystemExit(EXIT_ON_ERROR_MSG) from e
108107

109108

110109
def progress_cb(output: str, timestamp: datetime) -> None:
@@ -144,9 +143,7 @@ def update_repo(
144143
if repo_dict.get("vcs") is None:
145144
vcs = guess_vcs(url=repo_dict["url"])
146145
if vcs is None:
147-
raise Exception(
148-
f'Could not automatically determine VCS for {repo_dict["url"]}'
149-
)
146+
raise CouldNotGuessVCSFromURL(repo_url=repo_dict["url"])
150147

151148
repo_dict["vcs"] = vcs
152149

src/vcspull/config.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828

2929

3030
def expand_dir(
31-
_dir: pathlib.Path, cwd: pathlib.Path = pathlib.Path.cwd()
31+
_dir: pathlib.Path,
32+
cwd: t.Union[pathlib.Path, t.Callable[[], pathlib.Path]] = pathlib.Path.cwd,
3233
) -> pathlib.Path:
3334
"""Return path with environmental variables and tilde ~ expanded.
3435
@@ -44,15 +45,19 @@ def expand_dir(
4445
pathlib.Path :
4546
Absolute directory path
4647
"""
47-
_dir = pathlib.Path(os.path.expanduser(os.path.expandvars(str(_dir))))
48+
_dir = pathlib.Path(os.path.expandvars(str(_dir))).expanduser()
49+
if callable(cwd):
50+
cwd = cwd()
51+
4852
if not _dir.is_absolute():
4953
_dir = pathlib.Path(os.path.normpath(cwd / _dir))
5054
assert _dir == pathlib.Path(cwd, _dir).resolve(strict=False)
5155
return _dir
5256

5357

5458
def extract_repos(
55-
config: "RawConfigDict", cwd: pathlib.Path = pathlib.Path.cwd()
59+
config: "RawConfigDict",
60+
cwd: t.Union[pathlib.Path, t.Callable[[], pathlib.Path]] = pathlib.Path.cwd,
5661
) -> list["ConfigDict"]:
5762
"""Return expanded configuration.
5863
@@ -71,6 +76,9 @@ def extract_repos(
7176
list : List of normalized repository information
7277
"""
7378
configs: list["ConfigDict"] = []
79+
if callable(cwd):
80+
cwd = cwd()
81+
7482
for directory, repos in config.items():
7583
assert isinstance(repos, dict)
7684
for repo, repo_data in repos.items():
@@ -135,16 +143,16 @@ def is_valid_config_dict(val: t.Any) -> "TypeGuard[ConfigDict]":
135143

136144

137145
def find_home_config_files(
138-
filetype: t.Optional[list[str]] = None
146+
filetype: t.Optional[list[str]] = None,
139147
) -> list[pathlib.Path]:
140148
"""Return configs of ``.vcspull.{yaml,json}`` in user's home directory."""
141149
if filetype is None:
142150
filetype = ["json", "yaml"]
143151
configs: list[pathlib.Path] = []
144152

145-
yaml_config = pathlib.Path(os.path.expanduser("~/.vcspull.yaml"))
153+
yaml_config = pathlib.Path("~/.vcspull.yaml").expanduser()
146154
has_yaml_config = yaml_config.exists()
147-
json_config = pathlib.Path(os.path.expanduser("~/.vcspull.json"))
155+
json_config = pathlib.Path("~/.vcspull.json").expanduser()
148156
has_json_config = json_config.exists()
149157

150158
if not has_yaml_config and not has_json_config:
@@ -167,8 +175,8 @@ def find_home_config_files(
167175
def find_config_files(
168176
path: t.Optional[t.Union[list[pathlib.Path], pathlib.Path]] = None,
169177
match: t.Optional[t.Union[list[str], str]] = None,
170-
filetype: t.Union[
171-
t.Literal["json", "yaml", "*"], list[t.Literal["json", "yaml", "*"]]
178+
filetype: t.Optional[
179+
t.Union[t.Literal["json", "yaml", "*"], list[t.Literal["json", "yaml", "*"]]]
172180
] = None,
173181
include_home: bool = False,
174182
) -> list[pathlib.Path]:
@@ -211,7 +219,7 @@ def find_config_files(
211219
config_files.extend(find_config_files(p, match, filetype))
212220
return config_files
213221
else:
214-
path = pathlib.Path(os.path.expanduser(path))
222+
path = path.expanduser()
215223
if isinstance(match, list):
216224
for m in match:
217225
config_files.extend(find_config_files(path, m, filetype))
@@ -227,7 +235,8 @@ def find_config_files(
227235

228236

229237
def load_configs(
230-
files: list[pathlib.Path], cwd: pathlib.Path = pathlib.Path.cwd()
238+
files: list[pathlib.Path],
239+
cwd: t.Union[pathlib.Path, t.Callable[[], pathlib.Path]] = pathlib.Path.cwd,
231240
) -> list["ConfigDict"]:
232241
"""Return repos from a list of files.
233242
@@ -248,6 +257,9 @@ def load_configs(
248257
Validate scheme, check for duplicate destinations, VCS urls
249258
"""
250259
repos: list["ConfigDict"] = []
260+
if callable(cwd):
261+
cwd = cwd()
262+
251263
for file in files:
252264
if isinstance(file, str):
253265
file = pathlib.Path(file)
@@ -329,11 +341,12 @@ def in_dir(
329341
extensions = [".yml", ".yaml", ".json"]
330342
if config_dir is not None:
331343
config_dir = get_config_dir()
332-
configs = []
333344

334-
for filename in os.listdir(config_dir):
335-
if is_config_file(filename, extensions) and not filename.startswith("."):
336-
configs.append(filename)
345+
configs = [
346+
filename
347+
for filename in os.listdir(config_dir)
348+
if is_config_file(filename, extensions) and not filename.startswith(".")
349+
]
337350

338351
return configs
339352

src/vcspull/util.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import typing as t
1010
from collections.abc import Mapping
1111

12-
LEGACY_CONFIG_DIR = os.path.expanduser("~/.vcspull/") # remove dupes of this
12+
LEGACY_CONFIG_DIR = pathlib.Path("~/.vcspull/").expanduser() # remove dupes of this
1313

1414

1515
def get_config_dir() -> pathlib.Path:
@@ -27,23 +27,23 @@ def get_config_dir() -> pathlib.Path:
2727
absolute path to tmuxp config directory
2828
"""
2929

30-
paths = []
30+
paths: list[pathlib.Path] = []
3131
if "VCSPULL_CONFIGDIR" in os.environ:
32-
paths.append(os.environ["VCSPULL_CONFIGDIR"])
32+
paths.append(pathlib.Path(os.environ["VCSPULL_CONFIGDIR"]))
3333
if "XDG_CONFIG_HOME" in os.environ:
34-
paths.append(os.path.join(os.environ["XDG_CONFIG_HOME"], "vcspull"))
34+
paths.append(pathlib.Path(os.environ["XDG_CONFIG_HOME"]) / "vcspull")
3535
else:
36-
paths.append("~/.config/vcspull/")
36+
paths.append(pathlib.Path("~/.config/vcspull/"))
3737
paths.append(LEGACY_CONFIG_DIR)
3838

3939
path = None
4040
for path in paths:
41-
path = os.path.expanduser(path)
42-
if os.path.isdir(path):
43-
return pathlib.Path(path)
41+
path = path.expanduser()
42+
if path.is_dir():
43+
return path
4444

4545
# Return last path as default if none of the previous ones matched
46-
return pathlib.Path(path)
46+
return path
4747

4848

4949
T = t.TypeVar("T", bound=dict[str, t.Any])

tests/test_config_file.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,17 +83,19 @@ def test_export_yaml(tmp_path: pathlib.Path) -> None:
8383

8484

8585
def test_scan_config(tmp_path: pathlib.Path) -> None:
86-
config_files = []
86+
config_files: list[str] = []
8787

8888
exists = os.path.exists
8989
garbage_file = tmp_path / ".vcspull.psd"
9090
garbage_file.write_text("wat", encoding="utf-8")
9191

92-
for _r, _d, f in os.walk(str(tmp_path)):
93-
for filela in (
94-
x for x in f if x.endswith((".json", "yaml")) and x.startswith(".vcspull")
95-
):
96-
config_files.append(str(tmp_path / filela))
92+
for _r, _d, file in os.walk(str(tmp_path)):
93+
config_files += [
94+
str(tmp_path / scanned_file)
95+
for scanned_file in file
96+
if scanned_file.endswith((".json", "yaml"))
97+
and scanned_file.startswith(".vcspull")
98+
]
9799

98100
files = 0
99101
if exists(str(tmp_path / ".vcspull.json")):
@@ -390,5 +392,5 @@ def test_merge_nested_dict(tmp_path: pathlib.Path, config_path: pathlib.Path) ->
390392
)
391393
assert config1 in config_files
392394
assert config2 in config_files
393-
with pytest.raises(Exception):
395+
with pytest.raises(exc.VCSPullException):
394396
config.load_configs(config_files)

0 commit comments

Comments
 (0)