A library for rendering project templates from Git repositories with Jinja2 templating and interactive questionnaires.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Type definitions, enums, and constants used throughout the copier API for type safety, configuration, and state management.
Enum for specifying version control system references when working with templates.
class VcsRef(str, Enum):
"""VCS reference enum for template versioning."""
CURRENT = ":current:"The VcsRef.CURRENT value instructs copier to use the current reference of an existing template, useful for updates without changing the template version.
Usage examples:
from copier import run_copy, VcsRef
# Use current ref for updates
worker = run_copy(
src_path="https://github.com/user/template.git",
dst_path="./project",
vcs_ref=VcsRef.CURRENT
)
# Equivalent string usage
worker = run_copy(
src_path="template/",
dst_path="project/",
vcs_ref=":current:"
)Enum representing the current execution phase during template processing.
class Phase(str, Enum):
"""Known execution phases for template processing."""
PROMPT = "prompt"
TASKS = "tasks"
MIGRATE = "migrate"
RENDER = "render"
UNDEFINED = "undefined"
@classmethod
def use(cls, phase: Phase) -> Iterator[None]:
"""
Context manager to set current processing phase.
Parameters:
- phase (Phase): Phase to set as current
Returns:
Iterator[None]: Context manager for phase setting
"""
@classmethod
def current(cls) -> Phase:
"""
Get the current processing phase.
Returns:
Phase: Current phase or UNDEFINED if not set
"""Usage examples:
from copier._types import Phase
# Check current phase
current_phase = Phase.current()
print(f"Current phase: {current_phase}")
# Set phase context
with Phase.use(Phase.RENDER):
# Code executed during render phase
pass
# Phase-specific logic
if Phase.current() == Phase.PROMPT:
# Handle user prompting
pass
elif Phase.current() == Phase.TASKS:
# Handle task execution
passDictionary implementation where values are functions evaluated only once when requested.
class LazyDict(MutableMapping[str, Any]):
"""Dictionary where values are functions evaluated only once when requested."""
def __init__(self, data: dict[str, Callable[[], Any]]): ...
def __getitem__(self, key: str) -> Any: ...
def __setitem__(self, key: str, value: Callable[[], Any]) -> None: ...
def __delitem__(self, key: str) -> None: ...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[str]: ...Usage examples:
from copier._types import LazyDict
# Create lazy dictionary with expensive computations
lazy_data = LazyDict({
"timestamp": lambda: datetime.now().isoformat(),
"git_hash": lambda: subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
"file_count": lambda: len(list(Path(".").rglob("*")))
})
# Values computed only when accessed
print(lazy_data["timestamp"]) # Computed now
print(lazy_data["timestamp"]) # Cached resultCommon type aliases used throughout the copier API for better type annotations.
# Path and string types
StrOrPath = Union[str, Path]
OptStrOrPath = Optional[StrOrPath]
# Data structures
AnyByStrDict = dict[str, Any]
AnyByStrMutableMapping = MutableMapping[str, Any]
# Sequences
IntSeq = Sequence[int]
PathSeq = Sequence[Path]
# JSON-serializable types
JSONSerializable = Union[dict, list, str, int, float, bool, None]
# Optional types
OptBool = Optional[bool]
OptStr = Optional[str]
# VCS and operation types
VCSTypes = Literal["git"]
Operation = Literal["copy", "update"]
# Environment type
Env = Mapping[str, str]
# Path validation types
AbsolutePath = Annotated[Path, AfterValidator(path_is_absolute)]
RelativePath = Annotated[Path, AfterValidator(path_is_relative)]
# Additional type aliases
ConflictMode = Literal["inline", "rej"]
PositiveInt = Annotated[int, Field(gt=0)]Special constants and sentinel values used throughout the API.
# Sentinel value for missing data
MISSING = MissingType(object())
# Settings environment variable
ENV_VAR = "COPIER_SETTINGS_PATH"Usage examples:
from copier._types import MISSING, StrOrPath, AnyByStrDict
from pathlib import Path
# Type-safe function signatures
def process_template(
src: StrOrPath,
data: AnyByStrDict,
output: OptStrOrPath = None
) -> bool:
"""Process template with type safety."""
if output is MISSING:
output = Path.cwd()
return True
# Working with path types
def handle_paths(paths: PathSeq) -> None:
for path in paths:
if path.exists():
print(f"Found: {path}")Type hints for function parameters and callbacks used in copier's type system.
# Parameter specification for generic functions
ParamSpec = TypeVar("ParamSpec")
_T = TypeVar("_T")
_P = ParamSpec("_P")
# Function type annotations
AnyCallable = Callable[..., Any]
PathValidator = Callable[[Path], Path]
QuestionValidator = Callable[[Any], Any]
PathMatcher = Callable[[Path], bool]These types ensure type safety when working with copier's templating and validation systems, enabling proper IDE support and static type checking with mypy or similar tools.
Install with Tessl CLI
npx tessl i tessl/pypi-copier