Skip to content

Commit

Permalink
remove redundant type aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel.eades committed Feb 19, 2024
1 parent 14a6731 commit a9f2a9b
Show file tree
Hide file tree
Showing 12 changed files with 41 additions and 49 deletions.
5 changes: 3 additions & 2 deletions copier/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
copier --help-all
```
"""
from __future__ import annotations

import sys
from os import PathLike
Expand All @@ -60,7 +61,7 @@
from .errors import UnsafeTemplateError, UserMessageError
from .main import Worker
from .tools import copier_version
from .types import AnyByStrDict, OptStr, StrSeq
from .types import AnyByStrDict, StrSeq


def _handle_exceptions(method: Callable[[], None]) -> int:
Expand Down Expand Up @@ -195,7 +196,7 @@ def data_file_switch(self, path: cli.ExistingFile) -> None:
}
self.data.update(updates_without_cli_overrides)

def _worker(self, src_path: OptStr = None, dst_path: str = ".", **kwargs) -> Worker:
def _worker(self, src_path: str | None = None, dst_path: str = ".", **kwargs) -> Worker:
"""Run Copier's internal API using CLI switches.
Arguments:
Expand Down
10 changes: 4 additions & 6 deletions copier/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@
MISSING,
AnyByStrDict,
JSONSerializable,
OptStr,
RelativePath,
StrOrPath,
StrSeq,
)
from .user_data import DEFAULT_DATA, AnswersMap, Question
Expand Down Expand Up @@ -169,7 +167,7 @@ class Worker:
src_path: str | None = None
dst_path: Path = Path(".")
answers_file: RelativePath | None = None
vcs_ref: OptStr = None
vcs_ref: str | None = None
data: AnyByStrDict = field(default_factory=dict)
exclude: StrSeq = ()
use_prereleases: bool = False
Expand Down Expand Up @@ -1006,7 +1004,7 @@ def _git_initialize_repo(self):

def run_copy(
src_path: str,
dst_path: StrOrPath = ".",
dst_path: str | Path = ".",
data: AnyByStrDict | None = None,
**kwargs,
) -> Worker:
Expand All @@ -1024,7 +1022,7 @@ def run_copy(


def run_recopy(
dst_path: StrOrPath = ".", data: AnyByStrDict | None = None, **kwargs
dst_path: str | Path = ".", data: AnyByStrDict | None = None, **kwargs
) -> Worker:
"""Update a subproject from its template, discarding subproject evolution.
Expand All @@ -1040,7 +1038,7 @@ def run_recopy(


def run_update(
dst_path: StrOrPath = ".",
dst_path: str | Path = ".",
data: AnyByStrDict | None = None,
**kwargs,
) -> Worker:
Expand Down
10 changes: 5 additions & 5 deletions copier/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
UnsupportedVersionError,
)
from .tools import copier_version, handle_remove_readonly
from .types import AnyByStrDict, Env, OptStr, StrSeq, Union, VCSTypes
from .types import AnyByStrDict, Env, StrSeq, VCSTypes
from .vcs import checkout_latest_tag, clone, get_git, get_repo

# Default list of files in the template to exclude from the rendered project
Expand Down Expand Up @@ -153,7 +153,7 @@ class Task:
Additional environment variables to set while executing the command.
"""

cmd: Union[str, Sequence[str]]
cmd: str | Sequence[str]
extra_env: Env = field(default_factory=dict)


Expand Down Expand Up @@ -195,7 +195,7 @@ class Template:
"""

url: str
ref: OptStr = None
ref: str | None = None
use_prereleases: bool = False

def _cleanup(self) -> None:
Expand Down Expand Up @@ -260,14 +260,14 @@ def answers_relpath(self) -> Path:
return result

@cached_property
def commit(self) -> OptStr:
def commit(self) -> str | None:
"""If the template is VCS-tracked, get its commit description."""
if self.vcs == "git":
with local.cwd(self.local_abspath):
return get_git()("describe", "--tags", "--always").strip()

@cached_property
def commit_hash(self) -> OptStr:
def commit_hash(self) -> str | None:
"""If the template is VCS-tracked, get its commit full hash."""
if self.vcs == "git":
return get_git()("-C", self.local_abspath, "rev-parse", "HEAD").strip()
Expand Down
8 changes: 0 additions & 8 deletions copier/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
Literal,
Mapping,
NewType,
Optional,
Sequence,
TypeVar,
Union,
)

from pydantic import AfterValidator
Expand All @@ -22,19 +20,13 @@
from typing_extensions import Annotated

# simple types
StrOrPath = Union[str, Path]
AnyByStrDict = Dict[str, Any]

# sequences
IntSeq = Sequence[int]
StrSeq = Sequence[str]
PathSeq = Sequence[Path]

# optional types
OptBool = Optional[bool]
OptStrOrPath = Optional[StrOrPath]
OptStr = Optional[str]

# miscellaneous
T = TypeVar("T")
JSONSerializable = (dict, list, str, int, float, bool, type(None))
Expand Down
8 changes: 4 additions & 4 deletions copier/user_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

from .errors import InvalidTypeError, UserMessageError
from .tools import cast_to_bool, cast_to_str, force_str_end
from .types import MISSING, AnyByStrDict, MissingType, OptStr, OptStrOrPath, StrOrPath
from .types import MISSING, AnyByStrDict, MissingType


# TODO Remove these two functions as well as DEFAULT_DATA in a future release
Expand Down Expand Up @@ -109,7 +109,7 @@ def combined(self) -> Mapping[str, Any]:
)
)

def old_commit(self) -> OptStr:
def old_commit(self) -> str | None:
"""Commit when the project was updated from this template the last time."""
return self.last.get("_commit")

Expand Down Expand Up @@ -473,8 +473,8 @@ def parse_yaml_string(string: str) -> Any:


def load_answersfile_data(
dst_path: StrOrPath,
answers_file: OptStrOrPath = None,
dst_path: str | Path,
answers_file: str | Path | None = None,
) -> AnyByStrDict:
"""Load answers data from a `$dst_path/$answers_file` file if it exists."""
try:
Expand Down
17 changes: 9 additions & 8 deletions copier/vcs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Utilities related to VCS."""
from __future__ import annotations

import os
import re
import sys
Expand All @@ -13,10 +15,9 @@
from plumbum.machines import LocalCommand

from .errors import DirtyLocalWarning, ShallowCloneWarning
from .types import OptBool, OptStr, OptStrOrPath, StrOrPath


def get_git(context_dir: OptStrOrPath = None) -> LocalCommand:
def get_git(context_dir: str | Path | None = None) -> LocalCommand:
"""Gets `git` command, or fails if it's not available."""
command = local["git"]
if context_dir:
Expand All @@ -41,7 +42,7 @@ def get_git_version() -> Version:
)


def is_git_repo_root(path: StrOrPath) -> bool:
def is_git_repo_root(path: str | Path) -> bool:
"""Indicate if a given path is a git repo root directory."""
try:
with local.cwd(Path(path, ".git")):
Expand All @@ -50,7 +51,7 @@ def is_git_repo_root(path: StrOrPath) -> bool:
return False


def is_in_git_repo(path: StrOrPath) -> bool:
def is_in_git_repo(path: str | Path) -> bool:
"""Indicate if a given path is in a git repo directory."""
try:
get_git()("-C", path, "rev-parse", "--show-toplevel")
Expand All @@ -59,7 +60,7 @@ def is_in_git_repo(path: StrOrPath) -> bool:
return False


def is_git_shallow_repo(path: StrOrPath) -> bool:
def is_git_shallow_repo(path: str | Path) -> bool:
"""Indicate if a given path is a git shallow repo directory."""
try:
return (
Expand All @@ -80,7 +81,7 @@ def is_git_bundle(path: Path) -> bool:
return bool(get_git()["bundle", "verify", path] & TF)


def get_repo(url: str) -> OptStr:
def get_repo(url: str) -> str | None:
"""Transform `url` into a git-parseable origin URL.
Args:
Expand Down Expand Up @@ -116,7 +117,7 @@ def get_repo(url: str) -> OptStr:
return None


def checkout_latest_tag(local_repo: StrOrPath, use_prereleases: OptBool = False) -> str:
def checkout_latest_tag(local_repo: str | Path, use_prereleases: bool | None = False) -> str:
"""Checkout latest git tag and check it out, sorted by PEP 440.
Parameters:
Expand Down Expand Up @@ -146,7 +147,7 @@ def checkout_latest_tag(local_repo: StrOrPath, use_prereleases: OptBool = False)
return latest_tag


def clone(url: str, ref: OptStr = None) -> str:
def clone(url: str, ref: str | None = None) -> str:
"""Clone repo into some temporary destination.
Includes dirty changes for local templates by copying into a temp
Expand Down
7 changes: 3 additions & 4 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from prompt_toolkit.keys import Keys

import copier
from copier.types import OptStr, StrOrPath

PROJECT_TEMPLATE = Path(__file__).parent / "demo"

Expand Down Expand Up @@ -96,7 +95,7 @@ def assert_file(tmp_path: Path, *path: str) -> None:
assert filecmp.cmp(p1, p2)


def build_file_tree(spec: Mapping[StrOrPath, str | bytes | Path], dedent: bool = True):
def build_file_tree(spec: Mapping[str | Path, str | bytes | Path], dedent: bool = True):
"""Builds a file tree based on the received spec.
Params:
Expand All @@ -122,7 +121,7 @@ def build_file_tree(spec: Mapping[StrOrPath, str | bytes | Path], dedent: bool =


def expect_prompt(
tui: PopenSpawn, name: str, expected_type: str, help: OptStr = None
tui: PopenSpawn, name: str, expected_type: str, help: str | None = None
) -> None:
"""Check that we get a prompt in the standard form"""
if help:
Expand All @@ -134,7 +133,7 @@ def expect_prompt(


def git_save(
dst: StrOrPath = ".", message: str = "Test commit", tag: str | None = None
dst: str | Path = ".", message: str = "Test commit", tag: str | None = None
):
"""Save the current repo state in git.
Expand Down
5 changes: 3 additions & 2 deletions tests/test_answersfile.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from __future__ import annotations

from pathlib import Path
from textwrap import dedent

import pytest

import copier
from copier.types import OptStr
from copier.user_data import load_answersfile_data

from .helpers import BRACKET_ENVOPS_JSON, SUFFIX_TMPL, build_file_tree
Expand Down Expand Up @@ -52,7 +53,7 @@ def template_path(tmp_path_factory: pytest.TempPathFactory) -> str:


@pytest.mark.parametrize("answers_file", [None, ".changed-by-user.yaml"])
def test_answersfile(template_path: str, tmp_path: Path, answers_file: OptStr) -> None:
def test_answersfile(template_path: str, tmp_path: Path, answers_file: str | None) -> None:
"""Test copier behaves properly when using an answersfile."""
round_file = tmp_path / "round.txt"

Expand Down
5 changes: 3 additions & 2 deletions tests/test_complex_questions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import json
from collections import deque
from pathlib import Path
Expand All @@ -11,7 +13,6 @@
from plumbum.cmd import git

from copier import run_copy, run_update
from copier.types import OptStr

from .helpers import (
BRACKET_ENVOPS,
Expand Down Expand Up @@ -122,7 +123,7 @@ def check_invalid(
name: str,
format: str,
invalid_value: str,
help: OptStr = None,
help: str | None = None,
err: str = "Invalid input",
) -> None:
"""Check that invalid input is reported correctly"""
Expand Down
5 changes: 3 additions & 2 deletions tests/test_exclude.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import platform
from pathlib import Path
from typing import Mapping
Expand All @@ -6,7 +8,6 @@

from copier.main import run_copy
from copier.template import DEFAULT_EXCLUDE
from copier.types import StrOrPath

from .helpers import PROJECT_TEMPLATE, build_file_tree

Expand Down Expand Up @@ -61,7 +62,7 @@ def test_config_include(tmp_path_factory: pytest.TempPathFactory) -> None:
)
def test_path_filter(tmp_path_factory: pytest.TempPathFactory) -> None:
src, dst = map(tmp_path_factory.mktemp, ("src", "dst"))
file_excluded: Mapping[StrOrPath, bool] = {
file_excluded: Mapping[str | Path, bool] = {
"x.exclude": True,
"do_not.exclude!": False,
# dir patterns and their negations
Expand Down
6 changes: 2 additions & 4 deletions tests/test_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from plumbum import local
from plumbum.cmd import git

from copier.types import StrOrPath

from .helpers import (
BRACKET_ENVOPS,
BRACKET_ENVOPS_JSON,
Expand All @@ -30,7 +28,7 @@
from typing_extensions import TypeAlias


MARIO_TREE: Mapping[StrOrPath, str | bytes] = {
MARIO_TREE: Mapping[str | Path, str | bytes] = {
"copier.yml": (
f"""\
_templates_suffix: {SUFFIX_TMPL}
Expand All @@ -55,7 +53,7 @@
"[[ _copier_conf.answers_file ]].tmpl": "[[_copier_answers|to_nice_yaml]]",
}

MARIO_TREE_WITH_NEW_FIELD: Mapping[StrOrPath, str | bytes] = {
MARIO_TREE_WITH_NEW_FIELD: Mapping[str | Path, str | bytes] = {
"copier.yml": (
f"""\
_templates_suffix: {SUFFIX_TMPL}
Expand Down
4 changes: 2 additions & 2 deletions tests/test_templated_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from copier import Worker
from copier.errors import InvalidTypeError
from copier.types import AnyByStrDict, OptStr
from copier.types import AnyByStrDict

from .helpers import (
BRACKET_ENVOPS,
Expand All @@ -32,7 +32,7 @@


class Prompt:
def __init__(self, name: str, format: str, help: OptStr = None) -> None:
def __init__(self, name: str, format: str, help: str | None = None) -> None:
self.name = name
self.format = format
self.help = help
Expand Down

0 comments on commit a9f2a9b

Please sign in to comment.