0
# Types and Enums
1
2
Type definitions, enums, and constants used throughout the copier API for type safety, configuration, and state management.
3
4
## Capabilities
5
6
### VCS Reference Enum
7
8
Enum for specifying version control system references when working with templates.
9
10
```python { .api }
11
class VcsRef(str, Enum):
12
"""VCS reference enum for template versioning."""
13
14
CURRENT = ":current:"
15
```
16
17
The `VcsRef.CURRENT` value instructs copier to use the current reference of an existing template, useful for updates without changing the template version.
18
19
Usage examples:
20
21
```python
22
from copier import run_copy, VcsRef
23
24
# Use current ref for updates
25
worker = run_copy(
26
src_path="https://github.com/user/template.git",
27
dst_path="./project",
28
vcs_ref=VcsRef.CURRENT
29
)
30
31
# Equivalent string usage
32
worker = run_copy(
33
src_path="template/",
34
dst_path="project/",
35
vcs_ref=":current:"
36
)
37
```
38
39
### Processing Phase Enum
40
41
Enum representing the current execution phase during template processing.
42
43
```python { .api }
44
class Phase(str, Enum):
45
"""Known execution phases for template processing."""
46
47
PROMPT = "prompt"
48
TASKS = "tasks"
49
MIGRATE = "migrate"
50
RENDER = "render"
51
UNDEFINED = "undefined"
52
53
@classmethod
54
def use(cls, phase: Phase) -> Iterator[None]:
55
"""
56
Context manager to set current processing phase.
57
58
Parameters:
59
- phase (Phase): Phase to set as current
60
61
Returns:
62
Iterator[None]: Context manager for phase setting
63
"""
64
65
@classmethod
66
def current(cls) -> Phase:
67
"""
68
Get the current processing phase.
69
70
Returns:
71
Phase: Current phase or UNDEFINED if not set
72
"""
73
```
74
75
Usage examples:
76
77
```python
78
from copier._types import Phase
79
80
# Check current phase
81
current_phase = Phase.current()
82
print(f"Current phase: {current_phase}")
83
84
# Set phase context
85
with Phase.use(Phase.RENDER):
86
# Code executed during render phase
87
pass
88
89
# Phase-specific logic
90
if Phase.current() == Phase.PROMPT:
91
# Handle user prompting
92
pass
93
elif Phase.current() == Phase.TASKS:
94
# Handle task execution
95
pass
96
```
97
98
### Lazy Dictionary
99
100
Dictionary implementation where values are functions evaluated only once when requested.
101
102
```python { .api }
103
class LazyDict(MutableMapping[str, Any]):
104
"""Dictionary where values are functions evaluated only once when requested."""
105
106
def __init__(self, data: dict[str, Callable[[], Any]]): ...
107
def __getitem__(self, key: str) -> Any: ...
108
def __setitem__(self, key: str, value: Callable[[], Any]) -> None: ...
109
def __delitem__(self, key: str) -> None: ...
110
def __len__(self) -> int: ...
111
def __iter__(self) -> Iterator[str]: ...
112
```
113
114
Usage examples:
115
116
```python
117
from copier._types import LazyDict
118
119
# Create lazy dictionary with expensive computations
120
lazy_data = LazyDict({
121
"timestamp": lambda: datetime.now().isoformat(),
122
"git_hash": lambda: subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
123
"file_count": lambda: len(list(Path(".").rglob("*")))
124
})
125
126
# Values computed only when accessed
127
print(lazy_data["timestamp"]) # Computed now
128
print(lazy_data["timestamp"]) # Cached result
129
```
130
131
### Type Aliases
132
133
Common type aliases used throughout the copier API for better type annotations.
134
135
```python { .api }
136
# Path and string types
137
StrOrPath = Union[str, Path]
138
OptStrOrPath = Optional[StrOrPath]
139
140
# Data structures
141
AnyByStrDict = dict[str, Any]
142
AnyByStrMutableMapping = MutableMapping[str, Any]
143
144
# Sequences
145
IntSeq = Sequence[int]
146
PathSeq = Sequence[Path]
147
148
# JSON-serializable types
149
JSONSerializable = Union[dict, list, str, int, float, bool, None]
150
151
# Optional types
152
OptBool = Optional[bool]
153
OptStr = Optional[str]
154
155
# VCS and operation types
156
VCSTypes = Literal["git"]
157
Operation = Literal["copy", "update"]
158
159
# Environment type
160
Env = Mapping[str, str]
161
162
# Path validation types
163
AbsolutePath = Annotated[Path, AfterValidator(path_is_absolute)]
164
RelativePath = Annotated[Path, AfterValidator(path_is_relative)]
165
166
# Additional type aliases
167
ConflictMode = Literal["inline", "rej"]
168
PositiveInt = Annotated[int, Field(gt=0)]
169
```
170
171
### Constants and Sentinels
172
173
Special constants and sentinel values used throughout the API.
174
175
```python { .api }
176
# Sentinel value for missing data
177
MISSING = MissingType(object())
178
179
# Settings environment variable
180
ENV_VAR = "COPIER_SETTINGS_PATH"
181
```
182
183
Usage examples:
184
185
```python
186
from copier._types import MISSING, StrOrPath, AnyByStrDict
187
from pathlib import Path
188
189
# Type-safe function signatures
190
def process_template(
191
src: StrOrPath,
192
data: AnyByStrDict,
193
output: OptStrOrPath = None
194
) -> bool:
195
"""Process template with type safety."""
196
if output is MISSING:
197
output = Path.cwd()
198
return True
199
200
# Working with path types
201
def handle_paths(paths: PathSeq) -> None:
202
for path in paths:
203
if path.exists():
204
print(f"Found: {path}")
205
```
206
207
### Function Parameter Types
208
209
Type hints for function parameters and callbacks used in copier's type system.
210
211
```python { .api }
212
# Parameter specification for generic functions
213
ParamSpec = TypeVar("ParamSpec")
214
_T = TypeVar("_T")
215
_P = ParamSpec("_P")
216
217
# Function type annotations
218
AnyCallable = Callable[..., Any]
219
PathValidator = Callable[[Path], Path]
220
QuestionValidator = Callable[[Any], Any]
221
PathMatcher = Callable[[Path], bool]
222
```
223
224
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.