Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: enable more ruff lints #1558

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion copier/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Docs: https://copier.readthedocs.io/
"""

from .main import * # noqa: F401,F403
from .main import * # noqa: F403

# This version is a placeholder autoupdated by poetry-dynamic-versioning
__version__ = "0.0.0"
4 changes: 2 additions & 2 deletions copier/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ def run_copy(self) -> None:
self._render_folder(src_abspath)
if not self.quiet:
# TODO Unify printing tools
print("") # padding space
print() # padding space
self._execute_tasks(self.template.tasks)
except Exception:
if not was_existing and self.cleanup_on_error:
Expand All @@ -774,7 +774,7 @@ def run_copy(self) -> None:
self._print_message(self.template.message_after_copy)
if not self.quiet:
# TODO Unify printing tools
print("") # padding space
print() # padding space

def run_recopy(self) -> None:
"""Update a subproject, keeping answers but discarding evolution."""
Expand Down
2 changes: 1 addition & 1 deletion copier/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def _raw_config(self) -> AnyByStrDict:
conf_paths = [
p
for p in self.local_abspath.glob("copier.*")
if p.is_file() and re.match(r"\.ya?ml", p.suffix, re.I)
if p.is_file() and re.match(r"\.ya?ml", p.suffix, re.IGNORECASE)
]
if len(conf_paths) > 1:
raise MultipleConfigFilesError(conf_paths)
Expand Down
17 changes: 9 additions & 8 deletions copier/tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Some utility functions."""

from __future__ import annotations

import errno
Expand All @@ -13,7 +14,7 @@
from importlib.metadata import version
from pathlib import Path
from types import TracebackType
from typing import Any, Callable, Literal, TextIO, cast
from typing import Any, Callable, ClassVar, Literal, TextIO, cast

import colorama
from packaging.version import Version
Expand All @@ -25,11 +26,11 @@
class Style:
"""Common color styles."""

OK = [colorama.Fore.GREEN, colorama.Style.BRIGHT]
WARNING = [colorama.Fore.YELLOW, colorama.Style.BRIGHT]
IGNORE = [colorama.Fore.CYAN]
DANGER = [colorama.Fore.RED, colorama.Style.BRIGHT]
RESET = [colorama.Fore.RESET, colorama.Style.RESET_ALL]
OK: ClassVar[list[str]] = [colorama.Fore.GREEN, colorama.Style.BRIGHT]
WARNING: ClassVar[list[str]] = [colorama.Fore.YELLOW, colorama.Style.BRIGHT]
IGNORE: ClassVar[list[str]] = [colorama.Fore.CYAN]
DANGER: ClassVar[list[str]] = [colorama.Fore.RED, colorama.Style.BRIGHT]
RESET: ClassVar[list[str]] = [colorama.Fore.RESET, colorama.Style.RESET_ALL]


INDENT = " " * 2
Expand Down Expand Up @@ -75,7 +76,7 @@ def printf(
if not style:
return action + _msg

out = style + [action] + Style.RESET + [INDENT, _msg]
out = [*style, action, *Style.RESET, INDENT, _msg]
print(*out, sep="", file=file_)
return None

Expand All @@ -85,7 +86,7 @@ def printf_exception(
) -> None:
"""Print exception with common format."""
if not quiet:
print("", file=sys.stderr)
print(file=sys.stderr)
printf(action, msg=msg, style=Style.DANGER, indent=indent, file_=sys.stderr)
print(HLINE, file=sys.stderr)
print(e, file=sys.stderr)
Expand Down
4 changes: 2 additions & 2 deletions copier/user_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,9 @@ def _formatted_choices(self) -> Sequence[Choice]:
# The value can be templated
value = self.render_value(value)
checked = (
self.multiselect
(self.multiselect
and isinstance(default, list)
and self.cast_answer(value) in default
and self.cast_answer(value) in default)
or None
)
c = Choice(name, value, disabled=disabled, checked=checked)
Expand Down
16 changes: 7 additions & 9 deletions copier/vcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,11 @@ def is_git_bundle(path: Path) -> bool:
"""Indicate if a path is a valid git bundle."""
with suppress(OSError):
path = path.resolve()
with TemporaryDirectory(prefix=f"{__name__}.is_git_bundle.") as dirname:
with local.cwd(dirname):
get_git()("init")
return bool(get_git()["bundle", "verify", path] & TF)
with TemporaryDirectory(prefix=f"{__name__}.is_git_bundle.") as dirname, local.cwd(
dirname
):
get_git()("init")
return bool(get_git()["bundle", "verify", path] & TF)


def get_repo(url: str) -> str | None:
Expand All @@ -105,7 +106,7 @@ def get_repo(url: str) -> str | None:
if url.startswith("git+"):
url = url[4:]
elif url.startswith("https://") and not url.endswith(GIT_POSTFIX):
url = "".join((url, GIT_POSTFIX))
url = f"{url}{GIT_POSTFIX}"
return url

url_path = Path(url)
Expand Down Expand Up @@ -168,10 +169,7 @@ def clone(url: str, ref: str | None = None) -> str:
# Faster clones if possible
if git_version >= Version("2.27"):
url_match = re.match("(file://)?(.*)", url)
if url_match is not None:
file_url = url_match.groups()[-1]
else:
file_url = url
file_url = url_match.groups()[-1] if url_match is not None else url
if is_git_shallow_repo(file_url):
warn(
f"The repository '{url}' is a shallow clone, this might lead to unexpected "
Expand Down
3 changes: 2 additions & 1 deletion devtasks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Development helper tasks."""

import logging
import shutil
from pathlib import Path
Expand All @@ -25,7 +26,7 @@
"**/*.pyc",
"**/*.pyo",
)
project_dir = Path(".").resolve()
project_dir = Path.cwd()

Check warning on line 29 in devtasks.py

View check run for this annotation

Codecov / codecov/patch

devtasks.py#L29

Added line #L29 was not covered by tests
for pattern in build_artefacts + python_artefacts:
for matching_path in project_dir.glob(pattern):
print(f"Deleting {matching_path}")
Expand Down
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,19 @@ extend-select = [
"ARG",
"B",
"C90",
"C4",
"D",
"E",
"F",
"FA",
"FLY",
"FURB",
"I",
"PERF",
"PIE",
"PGH",
"RUF",
"SIM",
"UP",
]
extend-ignore = ['B028', "B904", "D105", "D107", "E501"]
Expand Down
19 changes: 5 additions & 14 deletions tests/test_complex_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def test_api(template_path: str, tmp_path: Path) -> None:

def test_cli_interactive(template_path: str, tmp_path: Path, spawn: Spawn) -> None:
"""Test copier correctly processes advanced questions and answers through CLI."""
tui = spawn(COPIER_PATH + ("copy", template_path, str(tmp_path)), timeout=10)
tui = spawn((*COPIER_PATH, "copy", template_path, str(tmp_path)), timeout=10)
expect_prompt(tui, "love_me", "bool", help="I need to know it. Do you love me?")
tui.send("y")
expect_prompt(tui, "your_name", "str", help="Please tell me your name.")
Expand Down Expand Up @@ -311,16 +311,7 @@ def test_cli_interatively_with_flag_data_and_type_casts(
) -> None:
"""Assert how choices work when copier is invoked with --data interactively."""
tui = spawn(
COPIER_PATH
+ (
"copy",
"--data=choose_list=second",
"--data=choose_dict=first",
"--data=choose_tuple=third",
"--data=choose_number=1",
template_path,
str(tmp_path),
),
(*COPIER_PATH, "copy", "--data=choose_list=second", "--data=choose_dict=first", "--data=choose_tuple=third", "--data=choose_number=1", template_path, str(tmp_path)),
timeout=10,
)
expect_prompt(tui, "love_me", "bool", help="I need to know it. Do you love me?")
Expand Down Expand Up @@ -406,7 +397,7 @@ def test_tui_inherited_default(
git("add", "--all")
git("commit", "--message", "init template")
git("tag", "1")
tui = spawn(COPIER_PATH + ("copy", str(src), str(dst)), timeout=10)
tui = spawn((*COPIER_PATH, "copy", str(src), str(dst)), timeout=10)
expect_prompt(tui, "owner1", "str")
tui.sendline("example")
expect_prompt(tui, "has_2_owners", "bool")
Expand Down Expand Up @@ -465,7 +456,7 @@ def test_tui_typed_default(
),
}
)
tui = spawn(COPIER_PATH + ("copy", str(src), str(dst)), timeout=10)
tui = spawn((*COPIER_PATH, "copy", str(src), str(dst)), timeout=10)
tui.expect_exact(pexpect.EOF)
assert json.loads((dst / "answers.json").read_text()) == {"_src_path": str(src)}
assert json.loads((dst / "context.json").read_text()) == {
Expand Down Expand Up @@ -506,7 +497,7 @@ def test_selection_type_cast(
(src / "answers.json.jinja"): "{{ _copier_answers|to_json }}",
}
)
tui = spawn(COPIER_PATH + ("copy", str(src), str(dst)), timeout=10)
tui = spawn((*COPIER_PATH, "copy", str(src), str(dst)), timeout=10)
expect_prompt(
tui, "postgres1", "yaml", help="Which PostgreSQL version do you want to deploy?"
)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_conditional_file_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def test_answer_changes(
git("tag", "v1")

if interactive:
tui = spawn(COPIER_PATH + ("copy", str(src), str(dst)), timeout=10)
tui = spawn((*COPIER_PATH, "copy", str(src), str(dst)), timeout=10)
expect_prompt(tui, "condition", "bool")
tui.expect_exact("(y/N)")
tui.sendline("y")
Expand All @@ -101,7 +101,7 @@ def test_answer_changes(
git("commit", "-mv1")

if interactive:
tui = spawn(COPIER_PATH + ("update", str(dst)), timeout=10)
tui = spawn((*COPIER_PATH, "update", str(dst)), timeout=10)
expect_prompt(tui, "condition", "bool")
tui.expect_exact("(Y/n)")
tui.sendline("n")
Expand Down
4 changes: 2 additions & 2 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@


def is_subdict(small: dict[Any, Any], big: dict[Any, Any]) -> bool:
return {**big, **small} == big
return big == {**big, **small}

Check warning on line 298 in tests/test_config.py

View check run for this annotation

Codecov / codecov/patch

tests/test_config.py#L298

Added line #L298 was not covered by tests


def test_worker_good_data(tmp_path: Path) -> None:
Expand All @@ -316,7 +316,7 @@
# func_args > defaults
(
{"src_path": ".", "exclude": ["aaa"]},
tuple(DEFAULT_EXCLUDE) + ("aaa",),
(*DEFAULT_EXCLUDE, "aaa"),
),
# func_args > user_data
(
Expand Down
7 changes: 4 additions & 3 deletions tests/test_interrupts.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ def test_keyboard_interrupt(
)
worker = Worker(str(src), dst, defaults=False)

with patch("copier.main.unsafe_prompt", side_effect=side_effect):
with pytest.raises(KeyboardInterrupt):
worker.run_copy()
with patch("copier.main.unsafe_prompt", side_effect=side_effect), pytest.raises(
KeyboardInterrupt
):
worker.run_copy()


def test_multiple_questions_interrupt(tmp_path_factory: pytest.TempPathFactory) -> None:
Expand Down
Loading
Loading