codehood-cli 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codehood/__init__.py +0 -0
- codehood/__main__.py +4 -0
- codehood/actions/__init__.py +0 -0
- codehood/actions/base.py +119 -0
- codehood/actions/resources.py +30 -0
- codehood/api/__init__.py +0 -0
- codehood/api/base.py +256 -0
- codehood/api/generate.py +1370 -0
- codehood/api/generated.py +3818 -0
- codehood/api/openapi.py +134 -0
- codehood/api/pages.py +53 -0
- codehood/cli/__init__.py +64 -0
- codehood/cli/api.py +422 -0
- codehood/cli/attendance.py +136 -0
- codehood/cli/auth.py +106 -0
- codehood/cli/base.py +42 -0
- codehood/cli/chill.py +52 -0
- codehood/cli/exam.py +107 -0
- codehood/cli/grades.py +185 -0
- codehood/cli/init.py +161 -0
- codehood/cli/push.py +609 -0
- codehood/cli/show.py +77 -0
- codehood/cli/uitils.py +26 -0
- codehood/functional.py +40 -0
- codehood/globs.py +71 -0
- codehood/grades.py +74 -0
- codehood/hypothesis.py +274 -0
- codehood/models/__init__.py +0 -0
- codehood/models/base.py +15 -0
- codehood/models/repo.py +187 -0
- codehood/models/validators.py +177 -0
- codehood/push/__init__.py +225 -0
- codehood/push/base.py +216 -0
- codehood/push/calendar.py +664 -0
- codehood/push/errors.py +136 -0
- codehood/push/exam.py +636 -0
- codehood/push/exclude.py +60 -0
- codehood/push/grades.py +455 -0
- codehood/push/hook.py +48 -0
- codehood/push/links.py +614 -0
- codehood/push/ours.py +78 -0
- codehood/push/plan.py +1981 -0
- codehood/push/project.py +272 -0
- codehood/push/question.py +338 -0
- codehood/push/report.py +244 -0
- codehood/push/repository.py +326 -0
- codehood/push/resource.py +576 -0
- codehood/push/run.py +1275 -0
- codehood/push/unconsumed.py +208 -0
- codehood/push/wire.py +222 -0
- codehood/py.typed +0 -0
- codehood/repo/__init__.py +62 -0
- codehood/repo/_config.py +28 -0
- codehood/repo/_layout.py +132 -0
- codehood/repo/_scaffold.py +244 -0
- codehood/repo/diff.py +71 -0
- codehood/repo/file_tracker.py +124 -0
- codehood/theme.py +101 -0
- codehood/widgets/__init__.py +0 -0
- codehood/widgets/mascot.py +76 -0
- codehood/widgets/questions/__init__.py +65 -0
- codehood/widgets/questions/base.py +119 -0
- codehood/widgets/questions/controls.py +194 -0
- codehood/widgets/questions/fill_in.py +81 -0
- codehood/widgets/questions/responses.py +137 -0
- codehood/widgets/questions/simple.py +117 -0
- codehood_cli-0.5.0.dist-info/METADATA +294 -0
- codehood_cli-0.5.0.dist-info/RECORD +71 -0
- codehood_cli-0.5.0.dist-info/WHEEL +4 -0
- codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
- codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
codehood/push/links.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The pure core that ties `resources/` files to the `calendar.md` lessons
|
|
3
|
+
that link to them.
|
|
4
|
+
|
|
5
|
+
A lesson is an `Event`: its `description` is the markdown of its h2
|
|
6
|
+
section. A markdown link in it whose target lies under `resources/`
|
|
7
|
+
attaches that resource to the event. Nothing here touches the network or
|
|
8
|
+
the disk: `plan.py` and `run.py` only carry the result.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import posixpath
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Mapping, Sequence
|
|
16
|
+
from dataclasses import dataclass, replace
|
|
17
|
+
from pathlib import Path, PurePosixPath
|
|
18
|
+
from urllib.parse import quote, unquote
|
|
19
|
+
|
|
20
|
+
from ..models.repo import CourseKey
|
|
21
|
+
from .calendar import Event, EventKey
|
|
22
|
+
from .errors import ResourceLinkError
|
|
23
|
+
from .repository import RepositoryTree
|
|
24
|
+
from .resource import MdData, ResourceFile, content_ref
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"RepositoryLink",
|
|
28
|
+
"attach_repositories",
|
|
29
|
+
"attach_resources",
|
|
30
|
+
"extract_repository_links",
|
|
31
|
+
"extract_resource_links",
|
|
32
|
+
"rewrite_body_links",
|
|
33
|
+
"rewrite_event_links",
|
|
34
|
+
"rewrite_repository_links",
|
|
35
|
+
"rewrite_resource_links",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def extract_resource_links(markdown: str) -> tuple[PurePosixPath, ...]:
|
|
40
|
+
"""
|
|
41
|
+
List the targets of the markdown links that point under `resources/`.
|
|
42
|
+
|
|
43
|
+
Targets are returned relative to the course root, normalized (a leading
|
|
44
|
+
`./` is dropped), in order of first appearance. Links to anything else
|
|
45
|
+
(http URLs, other paths, `#anchors`) are ignored.
|
|
46
|
+
"""
|
|
47
|
+
found: dict[PurePosixPath, None] = {}
|
|
48
|
+
for start, end in _link_targets(markdown):
|
|
49
|
+
target = _resources_target(markdown[start:end])
|
|
50
|
+
if target is not None:
|
|
51
|
+
found.setdefault(target, None)
|
|
52
|
+
return tuple(found)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def attach_resources(
|
|
56
|
+
events: Sequence[Event],
|
|
57
|
+
resources: Sequence[ResourceFile],
|
|
58
|
+
root: Path,
|
|
59
|
+
) -> tuple[ResourceFile, ...]:
|
|
60
|
+
"""
|
|
61
|
+
Return `resources`, same order, with `event` set to the lesson linking
|
|
62
|
+
each one and `ref` recomputed to include it.
|
|
63
|
+
|
|
64
|
+
A resource no lesson links keeps `event=None` and its ref unchanged.
|
|
65
|
+
`root` is the course root: a link `resources/a/b.pdf` matches the
|
|
66
|
+
resource whose `path` is `root / "resources/a/b.pdf"`. The same
|
|
67
|
+
resource linked more than once inside one lesson is fine.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
ResourceLinkError: A lesson links a path under `resources/` that is
|
|
71
|
+
not one of `resources`, or one resource is linked from two
|
|
72
|
+
different lessons.
|
|
73
|
+
"""
|
|
74
|
+
by_path = {resource.path: resource for resource in resources}
|
|
75
|
+
owner: dict[Path, Event] = {}
|
|
76
|
+
for event in events:
|
|
77
|
+
for link in extract_resource_links(event.description):
|
|
78
|
+
path = root / link
|
|
79
|
+
if path not in by_path:
|
|
80
|
+
raise ResourceLinkError(
|
|
81
|
+
f"{_lesson(event)} links to {link}, which is not a resource"
|
|
82
|
+
)
|
|
83
|
+
first = owner.setdefault(path, event)
|
|
84
|
+
if first is not event and (first.week, first.time_slot) != (
|
|
85
|
+
event.week,
|
|
86
|
+
event.time_slot,
|
|
87
|
+
):
|
|
88
|
+
raise ResourceLinkError(
|
|
89
|
+
f"{link} is linked from two lessons: "
|
|
90
|
+
f"{_lesson(first)} and {_lesson(event)}"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
attached: list[ResourceFile] = []
|
|
94
|
+
for resource in resources:
|
|
95
|
+
lesson = owner.get(resource.path)
|
|
96
|
+
if lesson is None:
|
|
97
|
+
attached.append(resource)
|
|
98
|
+
continue
|
|
99
|
+
key = EventKey(week=lesson.week, time_slot=lesson.time_slot)
|
|
100
|
+
ref = content_ref(resource.title, resource.description, resource.data, key)
|
|
101
|
+
attached.append(replace(resource, event=key, ref=ref))
|
|
102
|
+
return tuple(attached)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def rewrite_resource_links(markdown: str, targets: Mapping[PurePosixPath, str]) -> str:
|
|
106
|
+
"""
|
|
107
|
+
Replace the target of every `resources/` link found in `targets` by the
|
|
108
|
+
mapped URL, keeping the link text.
|
|
109
|
+
|
|
110
|
+
`targets` maps a root-relative path (as `extract_resource_links`
|
|
111
|
+
returns it) to the URL that replaces it. A link spelled `./resources/x`
|
|
112
|
+
or with a percent-encoded path matches like `resources/x`, and a
|
|
113
|
+
`#fragment` on the original target is kept after the new URL. Anything
|
|
114
|
+
else (other links, prose, links whose path is not in `targets`) is
|
|
115
|
+
untouched.
|
|
116
|
+
|
|
117
|
+
Code (fenced blocks and code spans) is never parsed for links. Reference
|
|
118
|
+
links are rewritten at their definition only.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
out = markdown
|
|
122
|
+
for start, end in reversed(_link_targets(markdown)):
|
|
123
|
+
raw = markdown[start:end]
|
|
124
|
+
target = _resources_target(raw)
|
|
125
|
+
url = targets.get(target) if target is not None else None
|
|
126
|
+
if url is None:
|
|
127
|
+
continue
|
|
128
|
+
fragment = f"#{raw.split('#', 1)[1]}" if "#" in raw else ""
|
|
129
|
+
out = out[:start] + url + fragment + out[end:]
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def rewrite_event_links(
|
|
134
|
+
events: Sequence[Event],
|
|
135
|
+
resources: Sequence[ResourceFile],
|
|
136
|
+
root: Path,
|
|
137
|
+
key: CourseKey,
|
|
138
|
+
) -> tuple[Event, ...]:
|
|
139
|
+
"""
|
|
140
|
+
Return `events`, same order, with every link to one of `resources`
|
|
141
|
+
rewritten in the description to `key.url("resources", <slug>)`.
|
|
142
|
+
|
|
143
|
+
Link text and `#fragment` are kept. Titles, week, slot and kind are
|
|
144
|
+
unchanged; so is any event whose description links to no resource. The
|
|
145
|
+
`ref` of a returned event follows its rewritten description, like any
|
|
146
|
+
`Event`. `root` is the course root, as in `attach_resources`.
|
|
147
|
+
"""
|
|
148
|
+
targets = {
|
|
149
|
+
PurePosixPath(resource.path.relative_to(root).as_posix()): key.url(
|
|
150
|
+
"resources", resource.slug
|
|
151
|
+
)
|
|
152
|
+
for resource in resources
|
|
153
|
+
}
|
|
154
|
+
return tuple(
|
|
155
|
+
replace(event, description=rewrite_resource_links(event.description, targets))
|
|
156
|
+
for event in events
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def rewrite_body_links(
|
|
161
|
+
resources: Sequence[ResourceFile],
|
|
162
|
+
root: Path,
|
|
163
|
+
key: CourseKey,
|
|
164
|
+
) -> tuple[ResourceFile, ...]:
|
|
165
|
+
"""
|
|
166
|
+
Return `resources`, same order, with every link in an `MD` body that
|
|
167
|
+
names another resource rewritten to `key.url("resources", <slug>)`.
|
|
168
|
+
|
|
169
|
+
A target resolves against the folder of the file that holds it, as a
|
|
170
|
+
Markdown viewer reads it (``, `[rubrica](../projeto/rubrica.md)`);
|
|
171
|
+
a `resources/...` target that names no file there is tried from the
|
|
172
|
+
course root, as in a lesson. Images count: the address of a `FILE`
|
|
173
|
+
redirects to its bytes. The `ref` follows the rewritten body.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
ResourceLinkError: A relative target lands under `resources/` but
|
|
177
|
+
names no resource.
|
|
178
|
+
"""
|
|
179
|
+
by_path = {
|
|
180
|
+
PurePosixPath(resource.path.relative_to(root).as_posix()): resource.slug
|
|
181
|
+
for resource in resources
|
|
182
|
+
}
|
|
183
|
+
rewritten: list[ResourceFile] = []
|
|
184
|
+
for resource in resources:
|
|
185
|
+
if not isinstance(resource.data, MdData):
|
|
186
|
+
rewritten.append(resource)
|
|
187
|
+
continue
|
|
188
|
+
source = PurePosixPath(resource.path.relative_to(root).as_posix())
|
|
189
|
+
content = _rewrite_relative(
|
|
190
|
+
resource.data.content, source, by_path, key.url("resources")
|
|
191
|
+
)
|
|
192
|
+
if content == resource.data.content:
|
|
193
|
+
rewritten.append(resource)
|
|
194
|
+
continue
|
|
195
|
+
data = MdData(content=content)
|
|
196
|
+
ref = content_ref(resource.title, resource.description, data, resource.event)
|
|
197
|
+
rewritten.append(replace(resource, data=data, ref=ref))
|
|
198
|
+
return tuple(rewritten)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _rewrite_relative(
|
|
202
|
+
markdown: str,
|
|
203
|
+
source: PurePosixPath,
|
|
204
|
+
by_path: Mapping[PurePosixPath, str],
|
|
205
|
+
base_url: str,
|
|
206
|
+
) -> str:
|
|
207
|
+
out = markdown
|
|
208
|
+
for start, end in reversed(_link_targets(markdown)):
|
|
209
|
+
raw = markdown[start:end]
|
|
210
|
+
target = _relative_target(raw, source, by_path)
|
|
211
|
+
if target is None:
|
|
212
|
+
continue
|
|
213
|
+
fragment = f"#{raw.split('#', 1)[1]}" if "#" in raw else ""
|
|
214
|
+
out = out[:start] + f"{base_url}/{by_path[target]}" + fragment + out[end:]
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _relative_target(
|
|
219
|
+
raw: str, source: PurePosixPath, by_path: Mapping[PurePosixPath, str]
|
|
220
|
+
) -> PurePosixPath | None:
|
|
221
|
+
"""
|
|
222
|
+
The resource path a body link names, or `None` for a link outside
|
|
223
|
+
`resources/` (a URL, an anchor, another tree).
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
ResourceLinkError: The link lands under `resources/` on no resource.
|
|
227
|
+
"""
|
|
228
|
+
if "://" in raw or raw.startswith(("#", "/", "mailto:")):
|
|
229
|
+
return None
|
|
230
|
+
cleaned = unquote(raw.split("#", 1)[0].split("?", 1)[0])
|
|
231
|
+
if not cleaned:
|
|
232
|
+
return None
|
|
233
|
+
resolved = PurePosixPath(posixpath.normpath((source.parent / cleaned).as_posix()))
|
|
234
|
+
if resolved in by_path:
|
|
235
|
+
return resolved
|
|
236
|
+
from_root = _resources_target(raw)
|
|
237
|
+
if from_root is not None and from_root in by_path:
|
|
238
|
+
return from_root
|
|
239
|
+
if resolved.parts[:1] == ("resources",):
|
|
240
|
+
raise ResourceLinkError(f"{source} links to {cleaned}, which is not a resource")
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass(frozen=True)
|
|
245
|
+
class RepositoryLink:
|
|
246
|
+
"""
|
|
247
|
+
A link target under `repositories/`: a repository, or a path inside it.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
slug: str
|
|
251
|
+
#: Path inside the repository, `None` for its root.
|
|
252
|
+
path: PurePosixPath | None = None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def extract_repository_links(markdown: str) -> tuple[RepositoryLink, ...]:
|
|
256
|
+
"""
|
|
257
|
+
List the targets of the markdown links that point under `repositories/`.
|
|
258
|
+
|
|
259
|
+
Same rules as `extract_resource_links`: normalized (`./` dropped,
|
|
260
|
+
percent-decoding applied, a trailing `/` ignored), in order of first
|
|
261
|
+
appearance, code skipped, other links ignored. `repositories/lab1` and
|
|
262
|
+
`repositories/lab1/src/main.py` both count.
|
|
263
|
+
"""
|
|
264
|
+
found: dict[RepositoryLink, None] = {}
|
|
265
|
+
for start, end in _link_targets(markdown):
|
|
266
|
+
link = _repositories_target(markdown[start:end])
|
|
267
|
+
if link is not None:
|
|
268
|
+
found.setdefault(link, None)
|
|
269
|
+
return tuple(found)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def attach_repositories(
|
|
273
|
+
events: Sequence[Event], repositories: Sequence[RepositoryTree]
|
|
274
|
+
) -> tuple[Event, ...]:
|
|
275
|
+
"""
|
|
276
|
+
Return `events`, same order, with `repositories` set to the sorted slugs
|
|
277
|
+
each lesson links.
|
|
278
|
+
|
|
279
|
+
A link to a path inside a repository must name one of its files or a
|
|
280
|
+
directory that holds some. One repository may be linked from many
|
|
281
|
+
lessons. An event that links none keeps `repositories=()`.
|
|
282
|
+
|
|
283
|
+
Raises:
|
|
284
|
+
ResourceLinkError: A lesson links a slug that is not in
|
|
285
|
+
`repositories`, or a path that is not in its tree.
|
|
286
|
+
"""
|
|
287
|
+
by_slug = {tree.slug: tree for tree in repositories}
|
|
288
|
+
attached: list[Event] = []
|
|
289
|
+
for event in events:
|
|
290
|
+
slugs: set[str] = set()
|
|
291
|
+
for link in extract_repository_links(event.description):
|
|
292
|
+
tree = by_slug.get(link.slug)
|
|
293
|
+
where = f"repositories/{link.slug}"
|
|
294
|
+
if tree is None:
|
|
295
|
+
raise ResourceLinkError(
|
|
296
|
+
f"{_lesson(event)} links to {where}, which is not a repository"
|
|
297
|
+
)
|
|
298
|
+
if link.path is not None and not _in_tree(tree, link.path):
|
|
299
|
+
raise ResourceLinkError(
|
|
300
|
+
f"{_lesson(event)} links to {where}/{link.path}, "
|
|
301
|
+
"which is not in the repository"
|
|
302
|
+
)
|
|
303
|
+
slugs.add(link.slug)
|
|
304
|
+
attached.append(replace(event, repositories=tuple(sorted(slugs))))
|
|
305
|
+
return tuple(attached)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def rewrite_repository_links(
|
|
309
|
+
events: Sequence[Event], key: CourseKey
|
|
310
|
+
) -> tuple[Event, ...]:
|
|
311
|
+
"""
|
|
312
|
+
Return `events`, same order, with every `repositories/` link rewritten to
|
|
313
|
+
`key.url("repositories", <slug>)`, plus `/<path>` for a file.
|
|
314
|
+
|
|
315
|
+
Link text and `#fragment` are kept; other links are untouched. Run it
|
|
316
|
+
after `attach_repositories`, which validates the targets.
|
|
317
|
+
"""
|
|
318
|
+
return tuple(
|
|
319
|
+
replace(
|
|
320
|
+
event,
|
|
321
|
+
description=_rewrite_repositories(event.description, key),
|
|
322
|
+
)
|
|
323
|
+
for event in events
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _rewrite_repositories(markdown: str, key: CourseKey) -> str:
|
|
328
|
+
out = markdown
|
|
329
|
+
for start, end in reversed(_link_targets(markdown)):
|
|
330
|
+
raw = markdown[start:end]
|
|
331
|
+
link = _repositories_target(raw)
|
|
332
|
+
if link is None:
|
|
333
|
+
continue
|
|
334
|
+
url = key.url("repositories", link.slug)
|
|
335
|
+
if link.path is not None:
|
|
336
|
+
url += "/" + quote(link.path.as_posix())
|
|
337
|
+
fragment = f"#{raw.split('#', 1)[1]}" if "#" in raw else ""
|
|
338
|
+
out = out[:start] + url + fragment + out[end:]
|
|
339
|
+
return out
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _in_tree(tree: RepositoryTree, path: PurePosixPath) -> bool:
|
|
343
|
+
"""
|
|
344
|
+
Whether `path` is a file of `tree` or a directory that holds one.
|
|
345
|
+
"""
|
|
346
|
+
prefix = path.as_posix()
|
|
347
|
+
return any(
|
|
348
|
+
entry.path == prefix or entry.path.startswith(prefix + "/")
|
|
349
|
+
for entry in tree.entries
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _repositories_target(raw: str) -> RepositoryLink | None:
|
|
354
|
+
"""
|
|
355
|
+
The repository link a target names, or `None` when it points elsewhere.
|
|
356
|
+
"""
|
|
357
|
+
if "://" in raw or raw.startswith(("#", "/", "mailto:")):
|
|
358
|
+
return None
|
|
359
|
+
cleaned = unquote(raw.split("#", 1)[0].split("?", 1)[0])
|
|
360
|
+
parts = PurePosixPath(cleaned).parts
|
|
361
|
+
if len(parts) < 2 or parts[0] != "repositories" or ".." in parts:
|
|
362
|
+
return None
|
|
363
|
+
rest = parts[2:]
|
|
364
|
+
return RepositoryLink(parts[1], PurePosixPath(*rest) if rest else None)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _lesson(event: Event) -> str:
|
|
368
|
+
return f"lesson {event.title!r} (week {event.week}, {event.time_slot})"
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _resources_target(raw: str) -> PurePosixPath | None:
|
|
372
|
+
"""
|
|
373
|
+
The root-relative path a link target names under `resources/`, or
|
|
374
|
+
`None` when it points anywhere else.
|
|
375
|
+
"""
|
|
376
|
+
if "://" in raw or raw.startswith(("#", "/", "mailto:")):
|
|
377
|
+
return None
|
|
378
|
+
cleaned = unquote(raw.split("#", 1)[0].split("?", 1)[0])
|
|
379
|
+
path = PurePosixPath(cleaned)
|
|
380
|
+
if len(path.parts) < 2 or path.parts[0] != "resources" or ".." in path.parts:
|
|
381
|
+
return None
|
|
382
|
+
return path
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
#
|
|
386
|
+
# Markdown scanning
|
|
387
|
+
#
|
|
388
|
+
|
|
389
|
+
#: A fence opener: up to 3 spaces of indent, then 3 or more backticks or tildes.
|
|
390
|
+
FENCE_RE = re.compile(r"^ {0,3}(?P<fence>`{3,}|~{3,})(?P<info>.*)$")
|
|
391
|
+
|
|
392
|
+
#: A link reference definition on a single line.
|
|
393
|
+
DEFINITION_RE = re.compile(
|
|
394
|
+
r"^ {0,3}\[(?P<label>(?:[^\]\\]|\\.)+)\]:[ \t]*"
|
|
395
|
+
r"(?:<(?P<angle>[^>\n]*)>|(?P<plain>\S+))"
|
|
396
|
+
r"(?:[ \t]+(?:\"[^\"]*\"|'[^']*'|\([^)]*\)))?[ \t]*$"
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
Span = tuple[int, int]
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _link_targets(markdown: str) -> list[Span]:
|
|
403
|
+
"""
|
|
404
|
+
The `(start, end)` span of the destination of every link in `markdown`,
|
|
405
|
+
in document order and without duplicates.
|
|
406
|
+
|
|
407
|
+
Inline links give their own destination. Reference links give the
|
|
408
|
+
destination of their definition, once per definition. Code is skipped.
|
|
409
|
+
"""
|
|
410
|
+
code, definitions, paragraphs = _code_mask(markdown)
|
|
411
|
+
spans: set[Span] = set()
|
|
412
|
+
defined: dict[str, Span] = {}
|
|
413
|
+
definition_lines: set[int] = set()
|
|
414
|
+
for line_start, line in definitions:
|
|
415
|
+
match = DEFINITION_RE.match(line)
|
|
416
|
+
if match is None:
|
|
417
|
+
continue
|
|
418
|
+
group = "angle" if match.group("angle") is not None else "plain"
|
|
419
|
+
start, end = match.span(group)
|
|
420
|
+
definition_lines.add(line_start)
|
|
421
|
+
label = _normalize_label(match.group("label"))
|
|
422
|
+
defined.setdefault(label, (line_start + start, line_start + end))
|
|
423
|
+
|
|
424
|
+
used: set[str] = set()
|
|
425
|
+
for first, last in paragraphs:
|
|
426
|
+
i = first
|
|
427
|
+
while i < last:
|
|
428
|
+
if markdown[i] != "[" or code[i] or _escaped(markdown, i):
|
|
429
|
+
i += 1
|
|
430
|
+
continue
|
|
431
|
+
close = _closing_bracket(markdown, code, i, last)
|
|
432
|
+
if close is None:
|
|
433
|
+
i += 1
|
|
434
|
+
continue
|
|
435
|
+
text = markdown[i + 1 : close]
|
|
436
|
+
after = markdown[close + 1 : close + 2]
|
|
437
|
+
if after == "(":
|
|
438
|
+
span = _inline_target(markdown, close + 1, last)
|
|
439
|
+
if span is not None:
|
|
440
|
+
spans.add(span)
|
|
441
|
+
elif after == "[":
|
|
442
|
+
label_end = _closing_bracket(markdown, code, close + 1, last)
|
|
443
|
+
if label_end is not None:
|
|
444
|
+
label = markdown[close + 2 : label_end]
|
|
445
|
+
used.add(_normalize_label(label or text))
|
|
446
|
+
elif not _is_definition_label(markdown, i, definition_lines):
|
|
447
|
+
used.add(_normalize_label(text))
|
|
448
|
+
i += 1
|
|
449
|
+
spans.update(defined[label] for label in used if label in defined)
|
|
450
|
+
return sorted(spans)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _is_definition_label(markdown: str, index: int, definition_lines: set[int]) -> bool:
|
|
454
|
+
"""
|
|
455
|
+
Whether the `[` at `index` opens the label of a definition line.
|
|
456
|
+
"""
|
|
457
|
+
start = markdown.rfind("\n", 0, index) + 1
|
|
458
|
+
return start in definition_lines
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _normalize_label(label: str) -> str:
|
|
462
|
+
return " ".join(label.split()).casefold()
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _escaped(text: str, index: int) -> bool:
|
|
466
|
+
"""
|
|
467
|
+
Whether the character at `index` is backslash-escaped.
|
|
468
|
+
"""
|
|
469
|
+
count = 0
|
|
470
|
+
while index - count > 0 and text[index - count - 1] == "\\":
|
|
471
|
+
count += 1
|
|
472
|
+
return count % 2 == 1
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _closing_bracket(
|
|
476
|
+
text: str, code: list[bool], opening: int, limit: int
|
|
477
|
+
) -> int | None:
|
|
478
|
+
"""
|
|
479
|
+
The index of the `]` that closes the `[` at `opening`, or `None`.
|
|
480
|
+
"""
|
|
481
|
+
depth = 0
|
|
482
|
+
i = opening
|
|
483
|
+
while i < limit:
|
|
484
|
+
char = text[i]
|
|
485
|
+
if code[i]:
|
|
486
|
+
pass
|
|
487
|
+
elif char == "\\":
|
|
488
|
+
i += 1
|
|
489
|
+
elif char == "[":
|
|
490
|
+
depth += 1
|
|
491
|
+
elif char == "]":
|
|
492
|
+
depth -= 1
|
|
493
|
+
if depth == 0:
|
|
494
|
+
return i
|
|
495
|
+
i += 1
|
|
496
|
+
return None
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _inline_target(text: str, paren: int, limit: int) -> Span | None:
|
|
500
|
+
"""
|
|
501
|
+
The span of the destination of the inline link whose `(` is at `paren`.
|
|
502
|
+
"""
|
|
503
|
+
i = paren + 1
|
|
504
|
+
while i < limit and text[i] in " \t\n":
|
|
505
|
+
i += 1
|
|
506
|
+
if i < limit and text[i] == "<":
|
|
507
|
+
end = i + 1
|
|
508
|
+
while end < limit and text[end] not in ">\n":
|
|
509
|
+
end += 1
|
|
510
|
+
return (i + 1, end) if end < limit and text[end] == ">" else None
|
|
511
|
+
start = i
|
|
512
|
+
depth = 0
|
|
513
|
+
while i < limit:
|
|
514
|
+
char = text[i]
|
|
515
|
+
if char == "\\":
|
|
516
|
+
i += 2
|
|
517
|
+
continue
|
|
518
|
+
if char.isspace():
|
|
519
|
+
break
|
|
520
|
+
if char == "(":
|
|
521
|
+
depth += 1
|
|
522
|
+
elif char == ")":
|
|
523
|
+
if depth == 0:
|
|
524
|
+
break
|
|
525
|
+
depth -= 1
|
|
526
|
+
i += 1
|
|
527
|
+
return (start, i) if depth == 0 and i > start else None
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _code_mask(markdown: str) -> tuple[list[bool], list[tuple[int, str]], list[Span]]:
|
|
531
|
+
"""
|
|
532
|
+
Locate code in `markdown`.
|
|
533
|
+
|
|
534
|
+
Returns:
|
|
535
|
+
A per-character flag that is true inside fenced blocks and code
|
|
536
|
+
spans, the `(offset, text)` of every line outside a fence, and the
|
|
537
|
+
spans of the paragraphs (runs of non-blank lines outside fences).
|
|
538
|
+
"""
|
|
539
|
+
code = [False] * len(markdown)
|
|
540
|
+
lines: list[tuple[int, str]] = []
|
|
541
|
+
paragraphs: list[Span] = []
|
|
542
|
+
fence: tuple[str, int] | None = None
|
|
543
|
+
para_start: int | None = None
|
|
544
|
+
offset = 0
|
|
545
|
+
for raw in markdown.splitlines(keepends=True):
|
|
546
|
+
line = raw.rstrip("\r\n")
|
|
547
|
+
end = offset + len(raw)
|
|
548
|
+
if fence is not None:
|
|
549
|
+
code[offset:end] = [True] * (end - offset)
|
|
550
|
+
closer = FENCE_RE.match(line)
|
|
551
|
+
if (
|
|
552
|
+
closer is not None
|
|
553
|
+
and closer.group("fence")[0] == fence[0]
|
|
554
|
+
and len(closer.group("fence")) >= fence[1]
|
|
555
|
+
and not closer.group("info").strip()
|
|
556
|
+
):
|
|
557
|
+
fence = None
|
|
558
|
+
else:
|
|
559
|
+
opener = FENCE_RE.match(line)
|
|
560
|
+
if opener is not None and not (
|
|
561
|
+
opener.group("fence")[0] == "`" and "`" in opener.group("info")
|
|
562
|
+
):
|
|
563
|
+
if para_start is not None:
|
|
564
|
+
paragraphs.append((para_start, offset))
|
|
565
|
+
para_start = None
|
|
566
|
+
fence = (opener.group("fence")[0], len(opener.group("fence")))
|
|
567
|
+
code[offset:end] = [True] * (end - offset)
|
|
568
|
+
elif line.strip():
|
|
569
|
+
lines.append((offset, line))
|
|
570
|
+
if para_start is None:
|
|
571
|
+
para_start = offset
|
|
572
|
+
elif para_start is not None:
|
|
573
|
+
paragraphs.append((para_start, offset))
|
|
574
|
+
para_start = None
|
|
575
|
+
offset = end
|
|
576
|
+
if para_start is not None:
|
|
577
|
+
paragraphs.append((para_start, offset))
|
|
578
|
+
for first, last in paragraphs:
|
|
579
|
+
_mask_code_spans(markdown, code, first, last)
|
|
580
|
+
return code, lines, paragraphs
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _mask_code_spans(text: str, code: list[bool], first: int, last: int) -> None:
|
|
584
|
+
"""
|
|
585
|
+
Flag the code spans inside `text[first:last]`: a backtick run closed by
|
|
586
|
+
the next run of the same length.
|
|
587
|
+
"""
|
|
588
|
+
i = first
|
|
589
|
+
while i < last:
|
|
590
|
+
if text[i] == "\\":
|
|
591
|
+
i += 2
|
|
592
|
+
elif text[i] == "`":
|
|
593
|
+
run = _backtick_run(text, i, last)
|
|
594
|
+
j = i + run
|
|
595
|
+
while j < last:
|
|
596
|
+
if text[j] == "`":
|
|
597
|
+
other = _backtick_run(text, j, last)
|
|
598
|
+
if other == run:
|
|
599
|
+
code[i : j + other] = [True] * (j + other - i)
|
|
600
|
+
j += other
|
|
601
|
+
break
|
|
602
|
+
j += other
|
|
603
|
+
else:
|
|
604
|
+
j += 1
|
|
605
|
+
i = j if j > i + run and code[i] else i + run
|
|
606
|
+
else:
|
|
607
|
+
i += 1
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _backtick_run(text: str, index: int, limit: int) -> int:
|
|
611
|
+
end = index
|
|
612
|
+
while end < limit and text[end] == "`":
|
|
613
|
+
end += 1
|
|
614
|
+
return end - index
|
codehood/push/ours.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`--ours`: settle `Conflict`s of a plan in favour of the repository.
|
|
3
|
+
|
|
4
|
+
Pure functions on a `Plan` and the globs the user passed. A glob is matched
|
|
5
|
+
against `"<kind>/<key>"`, for example `resource/intro` or
|
|
6
|
+
`calendar_event/1/mon`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from fnmatch import fnmatchcase
|
|
13
|
+
|
|
14
|
+
from .plan import Conflict, OtherCli, Plan, order_writes
|
|
15
|
+
|
|
16
|
+
__all__ = ["conflict_name", "ours_warnings", "resolve_ours"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def conflict_name(conflict: Conflict | OtherCli) -> str:
|
|
20
|
+
"""
|
|
21
|
+
The string `--ours` globs are matched against: `<kind>/<key>`.
|
|
22
|
+
"""
|
|
23
|
+
return f"{conflict.kind}/{conflict.key}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def resolve_ours(plan: Plan, globs: Sequence[str]) -> Plan:
|
|
27
|
+
"""
|
|
28
|
+
Replace every conflict and other-CLI entry a glob matches by the
|
|
29
|
+
operations that keep the repository's version.
|
|
30
|
+
|
|
31
|
+
The operations join the writes in the order a plan runs them, with their
|
|
32
|
+
base confirmations. A match that has no operations stays where it is.
|
|
33
|
+
"""
|
|
34
|
+
conflicts = [
|
|
35
|
+
c for c in plan.conflicts if c.ours and _matches(conflict_name(c), globs)
|
|
36
|
+
]
|
|
37
|
+
others = [o for o in plan.other_cli if o.ours and _matches(conflict_name(o), globs)]
|
|
38
|
+
if not conflicts and not others:
|
|
39
|
+
return plan
|
|
40
|
+
matched: list[Conflict | OtherCli] = [*conflicts, *others]
|
|
41
|
+
ours = Plan.of(op for c in matched for op in c.ours)
|
|
42
|
+
merged = Plan(
|
|
43
|
+
order_writes((*plan.writes, *ours.writes)),
|
|
44
|
+
plan.notices + ours.notices,
|
|
45
|
+
plan.pulls,
|
|
46
|
+
tuple(c for c in plan.conflicts if c not in conflicts),
|
|
47
|
+
tuple(o for o in plan.other_cli if o not in others),
|
|
48
|
+
plan.base_updates,
|
|
49
|
+
plan.confirmations + ours.confirmations,
|
|
50
|
+
)
|
|
51
|
+
return merged
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ours_warnings(plan: Plan, globs: Sequence[str]) -> tuple[str, ...]:
|
|
55
|
+
"""
|
|
56
|
+
The warnings `--ours` earns on `plan`: a glob that matches no conflict,
|
|
57
|
+
and a matched conflict that has no automatic resolution.
|
|
58
|
+
"""
|
|
59
|
+
entries: tuple[Conflict | OtherCli, ...] = (*plan.conflicts, *plan.other_cli)
|
|
60
|
+
names = [conflict_name(c) for c in entries]
|
|
61
|
+
warnings = [
|
|
62
|
+
f"--ours {glob} matches no conflict"
|
|
63
|
+
for glob in globs
|
|
64
|
+
if not any(fnmatchcase(name, glob) for name in names)
|
|
65
|
+
]
|
|
66
|
+
warnings.extend(
|
|
67
|
+
f"conflict {conflict_name(c)} has no automatic resolution; reconcile it by hand"
|
|
68
|
+
for c in entries
|
|
69
|
+
if not c.ours and _matches(conflict_name(c), globs)
|
|
70
|
+
)
|
|
71
|
+
return tuple(warnings)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
#
|
|
75
|
+
# Utilities
|
|
76
|
+
#
|
|
77
|
+
def _matches(name: str, globs: Sequence[str]) -> bool:
|
|
78
|
+
return any(fnmatchcase(name, glob) for glob in globs)
|