or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-usage.mdcore-operations.mderror-handling.mdindex.mdtypes-enums.md

advanced-usage.mddocs/

0

# Advanced Usage

1

2

Advanced copier functionality using the Worker class for fine-grained control over template processing and the Settings class for user configuration management.

3

4

## Capabilities

5

6

### Worker Class

7

8

The main copier process state manager that provides full control over template operations.

9

10

```python { .api }

11

class Worker:

12

"""Copier process state manager and context manager."""

13

14

def __init__(

15

self,

16

src_path: str | None = None,

17

dst_path: Path = Path(),

18

answers_file: RelativePath | None = None,

19

vcs_ref: str | VcsRef | None = None,

20

data: AnyByStrDict = None,

21

settings: Settings = None,

22

exclude: Sequence[str] = (),

23

use_prereleases: bool = False,

24

skip_if_exists: Sequence[str] = (),

25

cleanup_on_error: bool = True,

26

defaults: bool = False,

27

user_defaults: AnyByStrDict = None,

28

overwrite: bool = False,

29

pretend: bool = False,

30

quiet: bool = False,

31

conflict: Literal["inline", "rej"] = "inline",

32

context_lines: PositiveInt = 3,

33

unsafe: bool = False,

34

skip_answered: bool = False,

35

skip_tasks: bool = False

36

): ...

37

38

def run_copy(self) -> None: ...

39

def run_update(self) -> None: ...

40

def run_recopy(self) -> None: ...

41

42

def __enter__(self) -> Worker: ...

43

def __exit__(

44

self,

45

type: type[BaseException] | None,

46

value: BaseException | None,

47

traceback: TracebackType | None

48

) -> None: ...

49

50

# Properties

51

answers_relpath: Path

52

all_exclusions: Sequence[str]

53

jinja_env: YieldEnvironment

54

match_exclude: Callable[[Path], bool]

55

match_skip: Callable[[Path], bool]

56

resolved_vcs_ref: str | None

57

subproject: Subproject

58

template: Template

59

template_copy_root: Path

60

```

61

62

#### Worker Configuration Parameters

63

64

The Worker class accepts these configuration parameters:

65

66

**Template and Destination:**

67

- `src_path` (str | None): Template source path (local or Git URL)

68

- `dst_path` (Path): Destination path where to render the subproject

69

- `answers_file` (RelativePath | None): Path to answers file relative to dst_path

70

- `vcs_ref` (str | VcsRef | None): VCS tag/commit/branch to use

71

72

**Data and Settings:**

73

- `data` (AnyByStrDict): Answers to the questionnaire

74

- `settings` (Settings): User settings configuration

75

- `user_defaults` (AnyByStrDict): User default overrides for questions

76

77

**File Processing:**

78

- `exclude` (Sequence[str]): File exclusion patterns

79

- `skip_if_exists` (Sequence[str]): File skip patterns

80

- `use_prereleases` (bool): Consider prereleases when detecting latest version

81

82

**Behavior Control:**

83

- `cleanup_on_error` (bool): Delete dst_path if there's an error

84

- `defaults` (bool): Use default answers to questions without prompting

85

- `overwrite` (bool): Overwrite files that already exist without asking

86

- `pretend` (bool): Produce no real rendering (dry run)

87

- `quiet` (bool): Disable all output

88

- `unsafe` (bool): Allow usage of unsafe templates

89

- `skip_answered` (bool): Skip questions that have already been answered

90

- `skip_tasks` (bool): Skip template tasks execution

91

92

**Update/Conflict Resolution:**

93

- `conflict` (Literal["inline", "rej"]): Conflict resolution mode

94

- `context_lines` (PositiveInt): Lines of context for conflict resolution

95

96

Usage examples:

97

98

```python

99

from copier import Worker

100

101

# Context manager usage (recommended)

102

with Worker(

103

src_path="https://github.com/user/template.git",

104

dst_path="./my-project",

105

vcs_ref="v2.0.0",

106

data={"project_name": "MyApp"},

107

overwrite=True,

108

quiet=False

109

) as worker:

110

worker.run_copy()

111

print(f"Generated from: {worker.template}")

112

113

# Direct instantiation

114

worker = Worker(

115

src_path="./template",

116

dst_path="./project",

117

defaults=True,

118

pretend=True # Dry run

119

)

120

result = worker.run_copy()

121

122

# Chaining operations

123

worker = Worker(dst_path="./existing-project")

124

worker.run_update()

125

# Later...

126

worker.run_recopy()

127

```

128

129

### Settings Management

130

131

User settings configuration for copier defaults and trusted templates.

132

133

```python { .api }

134

class Settings:

135

"""User settings configuration model."""

136

137

defaults: dict[str, Any]

138

trust: set[str]

139

140

@classmethod

141

def from_file(cls, path: StrOrPath | None = None) -> Settings:

142

"""

143

Load settings from a YAML file.

144

145

Parameters:

146

- path (StrOrPath, optional): Path to settings file

147

148

Returns:

149

Settings: Loaded settings instance

150

"""

151

152

def is_trusted(self, url: str) -> bool:

153

"""

154

Check if a template URL is trusted.

155

156

Parameters:

157

- url (str): Template URL to check

158

159

Returns:

160

bool: True if URL is trusted

161

"""

162

163

def normalize(self) -> dict[str, Any]:

164

"""

165

Normalize settings data for serialization.

166

167

Returns:

168

dict: Normalized settings data

169

"""

170

```

171

172

#### Settings Configuration

173

174

Settings can be loaded from a YAML file (default location determined by `COPIER_SETTINGS_PATH` environment variable):

175

176

```yaml

177

# ~/.config/copier/settings.yml

178

defaults:

179

author: "John Doe"

180

license: "MIT"

181

python_version: "3.9"

182

183

trust:

184

- "https://github.com/trusted-org/*"

185

- "https://gitlab.com/my-company/*"

186

```

187

188

Usage examples:

189

190

```python

191

from copier import Settings

192

import os

193

194

# Load from default location

195

settings = Settings.from_file()

196

197

# Load from specific file

198

settings = Settings.from_file("./copier-settings.yml")

199

200

# Check if template is trusted

201

is_safe = settings.is_trusted("https://github.com/trusted-org/template.git")

202

203

# Use settings with Worker

204

os.environ["COPIER_SETTINGS_PATH"] = "./my-settings.yml"

205

worker = Worker(

206

src_path="template/",

207

dst_path="project/",

208

# Settings will be automatically loaded

209

)

210

```

211

212

### Advanced Template Processing

213

214

Working with template metadata and processing details:

215

216

```python

217

from copier import Worker

218

219

# Access template information

220

with Worker("template/", "project/") as worker:

221

worker.run_copy()

222

223

# Template metadata

224

print(f"Template path: {worker.template.local_abspath}")

225

print(f"Template ref: {worker.template.ref}")

226

print(f"Template version: {worker.template.version}")

227

print(f"Template commit: {worker.template.commit}")

228

229

# Processing results

230

print(f"Answers used: {worker.answers.combined}")

231

print(f"Destination: {worker.subproject.local_abspath}")

232

print(f"Answers file: {worker.answers_relpath}")

233

234

# Custom conflict resolution

235

worker = Worker(

236

src_path="template/",

237

dst_path="existing-project/",

238

conflict="rej", # Create .rej files for conflicts

239

context_lines=5 # Show 5 lines of context

240

)

241

worker.run_update()

242

```

243

244

### Environment Variable Configuration

245

246

Copier respects several environment variables:

247

248

- `COPIER_SETTINGS_PATH`: Path to settings file

249

- `GIT_*`: Git configuration variables

250

- `TMPDIR`: Temporary directory for processing

251

252

```python

253

import os

254

from copier import Worker

255

256

# Configure via environment

257

os.environ["COPIER_SETTINGS_PATH"] = "/custom/settings.yml"

258

os.environ["TMPDIR"] = "/fast/ssd/tmp"

259

260

worker = Worker("template/", "project/")

261

worker.run_copy()

262

```