-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathhelpers.py
More file actions
220 lines (180 loc) · 6.33 KB
/
Copy pathhelpers.py
File metadata and controls
220 lines (180 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from __future__ import annotations
import filecmp
import json
import os
import sys
import textwrap
from collections.abc import Mapping
from enum import Enum
from hashlib import sha1
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol
from pexpect.popen_spawn import PopenSpawn
from plumbum import local
from plumbum.cmd import git as _git
from plumbum.commands.base import BaseCommand
from prompt_toolkit.input.ansi_escape_sequences import REVERSE_ANSI_SEQUENCES
from prompt_toolkit.keys import Keys
from pytest_gitconfig.plugin import DEFAULT_GIT_USER_EMAIL, DEFAULT_GIT_USER_NAME
import copier
from copier._types import StrOrPath
if TYPE_CHECKING:
from pexpect.spawnbase import SpawnBase
PROJECT_TEMPLATE = Path(__file__).parent / "demo"
DATA = {
"py3": True,
"make_secret": lambda: sha1(os.urandom(48)).hexdigest(),
"myvar": "awesome",
"what": "world",
"project_name": "Copier",
"version": "2.0.0",
"description": "A library for rendering projects templates",
}
COPIER_CMD = local.get(
# Allow debugging in VSCode
# HACK https://github.com/microsoft/vscode-python/issues/14222
str(Path(sys.executable).parent / "copier.cmd"),
str(Path(sys.executable).parent / "copier"),
# uv installs the executable as copier.cmd in Windows
"copier.cmd",
"copier",
)
# Executing copier this way allows to debug subprocesses using debugpy
# See https://github.com/microsoft/debugpy/issues/596#issuecomment-824643237
COPIER_PATH = (sys.executable, "-m", "copier")
# Helpers to use with tests designed for old copier bracket envops defaults
BRACKET_ENVOPS = {
"autoescape": False,
"block_end_string": "%]",
"block_start_string": "[%",
"comment_end_string": "#]",
"comment_start_string": "[#",
"keep_trailing_newline": True,
"variable_end_string": "]]",
"variable_start_string": "[[",
}
BRACKET_ENVOPS_JSON = json.dumps(BRACKET_ENVOPS)
SUFFIX_TMPL = ".tmpl"
COPIER_ANSWERS_FILE: Mapping[StrOrPath, str | bytes | Path] = {
"{{ _copier_conf.answers_file }}.jinja": ("{{ _copier_answers|tojson }}")
}
class Spawn(Protocol):
def __call__(
self, cmd: tuple[str, ...], *, timeout: int | None = ...
) -> PopenSpawn: ...
class Keyboard(str, Enum):
ControlH = REVERSE_ANSI_SEQUENCES[Keys.ControlH]
ControlI = REVERSE_ANSI_SEQUENCES[Keys.ControlI]
ControlC = REVERSE_ANSI_SEQUENCES[Keys.ControlC]
Enter = "\r"
Esc = REVERSE_ANSI_SEQUENCES[Keys.Escape]
Home = REVERSE_ANSI_SEQUENCES[Keys.Home]
End = REVERSE_ANSI_SEQUENCES[Keys.End]
Up = REVERSE_ANSI_SEQUENCES[Keys.Up]
Down = REVERSE_ANSI_SEQUENCES[Keys.Down]
Right = REVERSE_ANSI_SEQUENCES[Keys.Right]
Left = REVERSE_ANSI_SEQUENCES[Keys.Left]
# Equivalent keystrokes in terminals; see python-prompt-toolkit for
# further explanations
Alt = Esc
Backspace = ControlH
Tab = ControlI
def render(tmp_path: Path, **kwargs: Any) -> None:
kwargs.setdefault("quiet", True)
copier.run_copy(str(PROJECT_TEMPLATE), tmp_path, data=DATA, **kwargs)
def assert_file(tmp_path: Path, *path: str) -> None:
p1 = tmp_path.joinpath(*path)
p2 = PROJECT_TEMPLATE.joinpath(*path)
assert filecmp.cmp(p1, p2)
def build_file_tree(
spec: Mapping[StrOrPath, str | bytes | Path],
dedent: bool = True,
encoding: str = "utf-8",
) -> None:
"""Builds a file tree based on the received spec.
Params:
spec:
A mapping from filesystem paths to file contents. If the content is
a Path object a symlink to the path will be created instead.
dedent: Dedent file contents.
"""
for path, contents in spec.items():
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
if isinstance(contents, Path):
path.symlink_to(contents)
else:
binary = isinstance(contents, bytes)
if not binary and dedent:
assert isinstance(contents, str)
contents = textwrap.dedent(contents)
mode = "wb" if binary else "w"
enc = None if binary else encoding
with Path(path).open(mode, encoding=enc) as fd:
fd.write(contents)
def expect_prompt(
tui: SpawnBase,
name: str,
expected_type: str,
help: str | None = None,
) -> None:
"""Check that we get a prompt in the standard form"""
if help:
tui.expect_exact(help)
else:
tui.expect_exact(name)
if expected_type != "str":
tui.expect_exact(f"({expected_type})")
git: BaseCommand = _git.with_env(
GIT_AUTHOR_NAME=DEFAULT_GIT_USER_NAME,
GIT_AUTHOR_EMAIL=DEFAULT_GIT_USER_EMAIL,
GIT_COMMITTER_NAME=DEFAULT_GIT_USER_NAME,
GIT_COMMITTER_EMAIL=DEFAULT_GIT_USER_EMAIL,
)
def git_save(
dst: StrOrPath = ".",
message: str = "Test commit",
tag: str | None = None,
allow_empty: bool = False,
) -> None:
"""Save the current repo state in git.
Args:
dst: Path to the repo to save.
message: Commit message.
tag: Tag to create, optionally.
allow_empty: Allow creating a commit with no changes
"""
with local.cwd(dst):
git("init")
git("add", ".")
git("commit", "-m", message, *(["--allow-empty"] if allow_empty else []))
if tag:
git("tag", tag)
def git_init(message: str = "hello world") -> None:
"""Initialize a Git repository with a first commit.
Args:
message: The first commit message.
"""
git("init")
git("add", ".")
git("commit", "-m", message)
def normalize_git_path(path: str) -> str:
r"""Convert weird characters returned by Git to normal UTF-8 path strings.
A filename like âñ will be reported by Git as "\\303\\242\\303\\261" (octal
notation).
Similarly, a filename like "<tab>foo\b<lf>ar" will be reported as "\tfoo\\b\nar".
This can be disabled with `git config core.quotepath off`.
Args:
path: The Git path to normalize.
Returns:
str: The normalized Git path.
"""
# Remove surrounding quotes
if path[0] == path[-1] == '"':
path = path[1:-1]
# Repair double-quotes
path = path.replace('\\"', '"')
# Unescape escape characters
path = path.encode("latin-1", "backslashreplace").decode("unicode-escape")
# Convert octal to utf8
return path.encode("latin-1", "backslashreplace").decode("utf-8")