Skip to content

Commit

Permalink
Linting: Aggressive ruff pass (ruff v0.3.4, #442)
Browse files Browse the repository at this point in the history
  • Loading branch information
tony authored Mar 24, 2024
2 parents 7297ba5 + 1795702 commit 7d415db
Show file tree
Hide file tree
Showing 15 changed files with 78 additions and 70 deletions.
19 changes: 19 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,25 @@ _Maintenance only, no bug fixes or new features_

### Development

- Aggressive automated lint fixes via `ruff` (#442)

via ruff v0.3.4, all automated lint fixes, including unsafe and previews were applied:

```sh
ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; ruff format .
```

Branches were treated with:

```sh
git rebase \
--strategy-option=theirs \
--exec 'poetry run ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; poetry run ruff format .; git add src tests; git commit --amend --no-edit' \
origin/master
```

### Development

- poetry: 1.7.1 -> 1.8.1

See also: https://github.com/python-poetry/poetry/blob/1.8.1/CHANGELOG.md
Expand Down
5 changes: 2 additions & 3 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def setup(
xdg_config_path: pathlib.Path,
) -> None:
"""Automatically load the pytest fixtures in the parameters."""
pass


@pytest.fixture(autouse=True)
Expand All @@ -57,7 +56,7 @@ def xdg_config_path(
return p


@pytest.fixture(scope="function")
@pytest.fixture()
def config_path(
xdg_config_path: pathlib.Path,
request: pytest.FixtureRequest,
Expand All @@ -82,7 +81,7 @@ def set_xdg_config_path(
monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_config_path))


@pytest.fixture(scope="function")
@pytest.fixture()
def repos_path(user_path: pathlib.Path, request: pytest.FixtureRequest) -> pathlib.Path:
"""Return temporary directory for repository checkout guaranteed unique."""
path = user_path / "repos"
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,15 +205,14 @@ def linkcode_resolve(domain: str, info: dict[str, str]) -> t.Union[None, str]:
fn,
linespec,
)
else:
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)


def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:
Expand Down
19 changes: 11 additions & 8 deletions scripts/generate_gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""Example script for export gitlab organization to vcspull config file."""

import argparse
import logging
import os
import pathlib
import sys
Expand All @@ -13,10 +14,13 @@
from vcspull.cli.sync import CouldNotGuessVCSFromURL, guess_vcs
from vcspull.types import RawConfig

log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(message)s")

try:
gitlab_token = os.environ["GITLAB_TOKEN"]
except KeyError:
print("Please provide the environment variable GITLAB_TOKEN")
log.info("Please provide the environment variable GITLAB_TOKEN")
sys.exit(1)

parser = argparse.ArgumentParser(
Expand Down Expand Up @@ -52,16 +56,15 @@
)

if result != "y":
print(
"Aborting per user request as existing config file (%s) \
should not be overwritten!"
% (config_filename),
log.info(
f"Aborting per user request as existing config file ({config_filename})"
+ " should not be overwritten!",
)
sys.exit(0)

config_file = config_filename.open(mode="w")
except OSError:
print(f"File {config_filename} not accessible")
log.info(f"File {config_filename} not accessible")
sys.exit(1)

response = requests.get(
Expand All @@ -71,7 +74,7 @@
)

if response.status_code != 200:
print("Error: ", response)
log.info(f"Error: {response}")
sys.exit(1)

path_prefix = pathlib.Path().cwd()
Expand Down Expand Up @@ -111,7 +114,7 @@

config_yaml = yaml.dump(config)

print(config_yaml)
log.info(config_yaml)

config_file.write(config_yaml)
config_file.close()
16 changes: 7 additions & 9 deletions src/vcspull/_internal/config_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,10 @@ def _load(fmt: "FormatLiteral", content: str) -> dict[str, t.Any]:
Loader=yaml.SafeLoader,
),
)
elif fmt == "json":
if fmt == "json":
return t.cast(dict[str, t.Any], json.loads(content))
else:
msg = f"{fmt} not supported in configuration"
raise NotImplementedError(msg)
msg = f"{fmt} not supported in configuration"
raise NotImplementedError(msg)

@classmethod
def load(cls, fmt: "FormatLiteral", content: str) -> "ConfigReader":
Expand Down Expand Up @@ -105,7 +104,7 @@ def _from_file(cls, path: pathlib.Path) -> dict[str, t.Any]:
assert isinstance(path, pathlib.Path)
content = path.open().read()

if path.suffix in [".yaml", ".yml"]:
if path.suffix in {".yaml", ".yml"}:
fmt: "FormatLiteral" = "yaml"
elif path.suffix == ".json":
fmt = "json"
Expand Down Expand Up @@ -180,14 +179,13 @@ def _dump(
default_flow_style=False,
Dumper=yaml.SafeDumper,
)
elif fmt == "json":
if fmt == "json":
return json.dumps(
content,
indent=2,
)
else:
msg = f"{fmt} not supported in config"
raise NotImplementedError(msg)
msg = f"{fmt} not supported in config"
raise NotImplementedError(msg)

def dump(self, fmt: "FormatLiteral", indent: int = 2, **kwargs: t.Any) -> str:
r"""Dump via ConfigReader instance.
Expand Down
7 changes: 4 additions & 3 deletions src/vcspull/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

from libvcs.__about__ import __version__ as libvcs_version

from ..__about__ import __version__
from ..log import setup_logger
from vcspull.__about__ import __version__
from vcspull.log import setup_logger

from .sync import create_sync_subparser, sync

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -85,7 +86,7 @@ def cli(_args: t.Optional[list[str]] = None) -> None:
if args.subparser_name is None:
parser.print_help()
return
elif args.subparser_name == "sync":
if args.subparser_name == "sync":
sync(
repo_patterns=args.repo_patterns,
config=args.config,
Expand Down
6 changes: 3 additions & 3 deletions src/vcspull/cli/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from libvcs.sync.git import GitSync
from libvcs.url import registry as url_tools

from .. import exc
from ..config import filter_repos, find_config_files, load_configs
from vcspull import exc
from vcspull.config import filter_repos, find_config_files, load_configs

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -91,7 +91,7 @@ def sync(
# collect the repos from the config files
found = filter_repos(configs, path=path, vcs_url=vcs_url, name=name)
if len(found) == 0:
print(NO_REPOS_FOR_TERM_MSG.format(name=name))
log.info(NO_REPOS_FOR_TERM_MSG.format(name=name))
found_repos.extend(filter_repos(configs, path=path, vcs_url=vcs_url, name=name))

for repo in found_repos:
Expand Down
17 changes: 7 additions & 10 deletions src/vcspull/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def find_home_config_files(
)
else:
if sum(filter(None, [has_json_config, has_yaml_config])) > 1:
raise exc.MultipleConfigWarning()
raise exc.MultipleConfigWarning
if has_yaml_config:
configs.append(yaml_config)
if has_json_config:
Expand Down Expand Up @@ -221,13 +221,12 @@ def find_config_files(
if isinstance(match, list):
for m in match:
config_files.extend(find_config_files(path, m, filetype))
elif isinstance(filetype, list):
for f in filetype:
config_files.extend(find_config_files(path, match, f))
else:
if isinstance(filetype, list):
for f in filetype:
config_files.extend(find_config_files(path, match, f))
else:
match = f"{match}.{filetype}"
config_files = list(path.glob(match))
match = f"{match}.{filetype}"
config_files = list(path.glob(match))

return config_files

Expand Down Expand Up @@ -341,14 +340,12 @@ def in_dir(
if config_dir is not None:
config_dir = get_config_dir()

configs = [
return [
filename
for filename in os.listdir(config_dir)
if is_config_file(filename, extensions) and not filename.startswith(".")
]

return configs


def filter_repos(
config: list["ConfigDict"],
Expand Down
2 changes: 1 addition & 1 deletion src/vcspull/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ class VCSPullException(Exception):
class MultipleConfigWarning(VCSPullException):
"""Multiple eligible config files found at the same time."""

message = "Multiple configs found in home directory use only one." " .yaml, .json."
message = "Multiple configs found in home directory use only one. .yaml, .json."
12 changes: 4 additions & 8 deletions src/vcspull/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,7 @@ def template(self, record: logging.LogRecord) -> str:
" ",
]

tpl = "".join(reset + levelname + asctime + name + reset)

return tpl
return "".join(reset + levelname + asctime + name + reset)

def __init__(self, color: bool = True, **kwargs: t.Any) -> None:
logging.Formatter.__init__(self, **kwargs)
Expand Down Expand Up @@ -164,20 +162,18 @@ def template(self, record: logging.LogRecord) -> str:
"%(lineno)d",
]

tpl = "".join(
return "".join(
reset + levelname + asctime + name + module_funcName + lineno + reset,
)

return tpl


class RepoLogFormatter(LogFormatter):
"""Log message for VCS repository."""

def template(self, record: logging.LogRecord) -> str:
"""Template for logging vcs bin name, along with a contextual hint."""
record.message = "".join(
[Fore.MAGENTA, Style.BRIGHT, record.message, Fore.RESET, Style.RESET_ALL],
record.message = (
f"{Fore.MAGENTA}{Style.BRIGHT}{record.message}{Fore.RESET}{Style.RESET_ALL}"
)
return f"{Fore.GREEN + Style.DIM}|{record.bin_name}| {Fore.YELLOW}({record.keyword}) {Fore.RESET}" # type:ignore # noqa: E501

Expand Down
2 changes: 1 addition & 1 deletion src/vcspull/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,5 @@ def update_dict(
r = update_dict(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
d[k] = v
return d
16 changes: 6 additions & 10 deletions tests/fixtures/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,14 @@
"path": pathlib.Path("/home/me/myproject/github_projects/kaptan"),
"remotes": {
"upstream": GitRemote(
**{
"name": "upstream",
"fetch_url": "git+https://github.com/emre/kaptan",
"push_url": "git+https://github.com/emre/kaptan",
},
name="upstream",
fetch_url="git+https://github.com/emre/kaptan",
push_url="git+https://github.com/emre/kaptan",
),
"ms": GitRemote(
**{
"name": "ms",
"fetch_url": "git+https://github.com/ms/kaptan.git",
"push_url": "git+https://github.com/ms/kaptan.git",
},
name="ms",
fetch_url="git+https://github.com/ms/kaptan.git",
push_url="git+https://github.com/ms/kaptan.git",
),
},
},
Expand Down
4 changes: 2 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ class SyncCLINonExistentRepo(t.NamedTuple):
def test_sync_cli_filter_non_existent(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
Expand Down Expand Up @@ -99,8 +100,7 @@ def test_sync_cli_filter_non_existent(
with contextlib.suppress(SystemExit):
cli(["sync", *sync_args])

result = capsys.readouterr()
output = "".join(list(result.out))
output = "".join(list(caplog.messages) + list(capsys.readouterr().out))

if expected_in_out is not None:
if isinstance(expected_in_out, str):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __call__(
...


@pytest.fixture
@pytest.fixture()
def load_yaml(tmp_path: pathlib.Path) -> LoadYAMLFn:
"""Return a yaml loading function that uses temporary directory path."""

Expand Down
4 changes: 2 additions & 2 deletions tests/test_config_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
from .helpers import EnvironmentVarGuard, load_raw, write_config


@pytest.fixture(scope="function")
@pytest.fixture()
def yaml_config(config_path: pathlib.Path) -> pathlib.Path:
"""Ensure and return vcspull yaml configuration file path."""
yaml_file = config_path / "repos1.yaml"
yaml_file.touch()
return yaml_file


@pytest.fixture(scope="function")
@pytest.fixture()
def json_config(config_path: pathlib.Path) -> pathlib.Path:
"""Ensure and return vcspull json configuration file path."""
json_file = config_path / "repos2.json"
Expand Down

0 comments on commit 7d415db

Please sign in to comment.