doclife 0.1.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.
- doclife/__init__.py +1 -0
- doclife/__main__.py +5 -0
- doclife/check.py +80 -0
- doclife/checks.py +218 -0
- doclife/cli.py +197 -0
- doclife/files.py +12 -0
- doclife/frontmatter.py +86 -0
- doclife/git.py +76 -0
- doclife/globs.py +59 -0
- doclife/idpatterns.py +19 -0
- doclife/ids.py +124 -0
- doclife/names.py +17 -0
- doclife/output.py +59 -0
- doclife/review.py +45 -0
- doclife/rule_docs.py +563 -0
- doclife/rules.py +92 -0
- doclife/settings.py +229 -0
- doclife/stamp.py +56 -0
- doclife-0.1.0.dist-info/METADATA +116 -0
- doclife-0.1.0.dist-info/RECORD +24 -0
- doclife-0.1.0.dist-info/WHEEL +5 -0
- doclife-0.1.0.dist-info/entry_points.txt +2 -0
- doclife-0.1.0.dist-info/licenses/LICENSE +674 -0
- doclife-0.1.0.dist-info/top_level.txt +1 -0
doclife/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Frontmatter checks for docs in git."""
|
doclife/__main__.py
ADDED
doclife/check.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Running every check over a repo's documents (ADR-002)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Collection, Mapping
|
|
4
|
+
from datetime import date
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from doclife.checks import (
|
|
8
|
+
check_dates,
|
|
9
|
+
check_fields,
|
|
10
|
+
check_place,
|
|
11
|
+
with_supplied_type,
|
|
12
|
+
)
|
|
13
|
+
from doclife.frontmatter import Document, ignore_comments, parse_frontmatter
|
|
14
|
+
from doclife.globs import glob_match
|
|
15
|
+
from doclife.ids import check_ids
|
|
16
|
+
from doclife.rules import UNKNOWN_RULE, Diagnostic, Rule, select_rules
|
|
17
|
+
from doclife.settings import Settings
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def check_documents(
|
|
21
|
+
texts: Mapping[str, str],
|
|
22
|
+
settings: Settings,
|
|
23
|
+
today: date,
|
|
24
|
+
committed: Mapping[str, date],
|
|
25
|
+
indexes: Mapping[str, str],
|
|
26
|
+
*,
|
|
27
|
+
report: Collection[str] | None = None,
|
|
28
|
+
) -> list[Diagnostic]:
|
|
29
|
+
"""Problems in the documents named in `report` (all when None), by path
|
|
30
|
+
then line, less the rules the settings or a document's frontmatter
|
|
31
|
+
switch off. `texts` holds every document, keyed by its path from the
|
|
32
|
+
repo root, since the id checks compare each one with the rest of its
|
|
33
|
+
type."""
|
|
34
|
+
documents = {
|
|
35
|
+
name: Document(
|
|
36
|
+
text, with_supplied_type(name, parse_frontmatter(text), settings)
|
|
37
|
+
)
|
|
38
|
+
for name, text in texts.items()
|
|
39
|
+
}
|
|
40
|
+
diagnostics = []
|
|
41
|
+
ignored: dict[str, set[Rule]] = {}
|
|
42
|
+
for name, document in documents.items():
|
|
43
|
+
if report is not None and name not in report:
|
|
44
|
+
continue
|
|
45
|
+
path, fields = Path(name), document.fields
|
|
46
|
+
comments = ignore_comments(document.text)
|
|
47
|
+
named = [(line, s) for line, selectors in comments for s in selectors]
|
|
48
|
+
ignored[name] = _ignored(name, [s for _, s in named], settings)
|
|
49
|
+
diagnostics += [
|
|
50
|
+
Diagnostic(
|
|
51
|
+
path,
|
|
52
|
+
UNKNOWN_RULE,
|
|
53
|
+
f"{selector!r} in doclife: ignore is not a rule code, name or group",
|
|
54
|
+
line,
|
|
55
|
+
)
|
|
56
|
+
for line, selector in named
|
|
57
|
+
if not select_rules(selector)
|
|
58
|
+
]
|
|
59
|
+
diagnostics += check_fields(path, fields, settings.types)
|
|
60
|
+
diagnostics += check_place(path, fields, settings)
|
|
61
|
+
diagnostics += check_dates(
|
|
62
|
+
path, fields, settings.types, today, committed.get(name)
|
|
63
|
+
)
|
|
64
|
+
diagnostics += [
|
|
65
|
+
diagnostic
|
|
66
|
+
for diagnostic in check_ids(documents, settings.types, indexes)
|
|
67
|
+
if report is None or diagnostic.path.as_posix() in report
|
|
68
|
+
]
|
|
69
|
+
kept = [d for d in diagnostics if d.rule not in ignored[d.path.as_posix()]]
|
|
70
|
+
return sorted(kept, key=lambda d: (d.path.as_posix(), d.line, d.column))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _ignored(name: str, in_frontmatter: list[str], settings: Settings) -> set[Rule]:
|
|
74
|
+
"""The rules switched off for one document: in settings for every
|
|
75
|
+
document or those its path matches, and in its own frontmatter."""
|
|
76
|
+
selectors = [*settings.ignore, *in_frontmatter]
|
|
77
|
+
for glob, rules in settings.per_file_ignores.items():
|
|
78
|
+
if glob_match(glob, name):
|
|
79
|
+
selectors += rules
|
|
80
|
+
return set().union(*map(select_rules, selectors))
|
doclife/checks.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Checks on one document."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from datetime import date
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from doclife.frontmatter import Field, parse_date
|
|
8
|
+
from doclife.globs import glob_match
|
|
9
|
+
from doclife.rules import (
|
|
10
|
+
CREATED_AFTER_MODIFIED,
|
|
11
|
+
INVALID_DATE,
|
|
12
|
+
INVALID_LAST_REVIEWED,
|
|
13
|
+
LABEL_SET_BY_PLACE,
|
|
14
|
+
MISSING_DATE,
|
|
15
|
+
MISSING_FIELD,
|
|
16
|
+
MISSING_LABEL,
|
|
17
|
+
MISSING_LAST_REVIEWED,
|
|
18
|
+
MISSING_TYPE,
|
|
19
|
+
MODIFIED_BEFORE_COMMIT,
|
|
20
|
+
NO_FRONTMATTER,
|
|
21
|
+
NO_PLACE,
|
|
22
|
+
REVIEWED_IN_FUTURE,
|
|
23
|
+
TYPE_NOT_ALLOWED,
|
|
24
|
+
UNKNOWN_LABEL,
|
|
25
|
+
Diagnostic,
|
|
26
|
+
Rule,
|
|
27
|
+
)
|
|
28
|
+
from doclife.settings import Place, Settings, TypeRules
|
|
29
|
+
|
|
30
|
+
FIXED_DATES = ("date_created", "date_modified") # every document has both
|
|
31
|
+
REVIEW_NEVER = "never" # last_reviewed for a document not yet reviewed
|
|
32
|
+
# date.fromisoformat alone also takes 20260105 and, from 3.11, more forms.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def check_fields(
|
|
36
|
+
path: Path, fields: dict[str, Field] | None, types: Mapping[str, TypeRules]
|
|
37
|
+
) -> list[Diagnostic]:
|
|
38
|
+
"""The fields the document's type needs: its type, the type's required
|
|
39
|
+
fields, and last_reviewed when the type is reviewed."""
|
|
40
|
+
if fields is None:
|
|
41
|
+
return [Diagnostic(path, NO_FRONTMATTER, "no frontmatter")]
|
|
42
|
+
|
|
43
|
+
def missing(key: str) -> bool:
|
|
44
|
+
return key not in fields or not fields[key].value
|
|
45
|
+
|
|
46
|
+
def line(key: str) -> int:
|
|
47
|
+
return fields[key].line if key in fields else 1
|
|
48
|
+
|
|
49
|
+
if missing("type"):
|
|
50
|
+
return [Diagnostic(path, MISSING_TYPE, "'type' missing", line("type"))]
|
|
51
|
+
kind = fields["type"].value
|
|
52
|
+
rules = types.get(kind, TypeRules())
|
|
53
|
+
|
|
54
|
+
diagnostics = [
|
|
55
|
+
Diagnostic(
|
|
56
|
+
path,
|
|
57
|
+
MISSING_FIELD,
|
|
58
|
+
f"{key!r} missing (required for type {kind})",
|
|
59
|
+
line(key),
|
|
60
|
+
)
|
|
61
|
+
for key in rules.required
|
|
62
|
+
if missing(key)
|
|
63
|
+
]
|
|
64
|
+
if rules.review and missing("last_reviewed"):
|
|
65
|
+
diagnostics.append(
|
|
66
|
+
Diagnostic(
|
|
67
|
+
path,
|
|
68
|
+
MISSING_LAST_REVIEWED,
|
|
69
|
+
f"'last_reviewed' missing (type {kind} is reviewed; a date, or never)",
|
|
70
|
+
line("last_reviewed"),
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
return diagnostics
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_place(path: str, settings: Settings) -> Place | None:
|
|
77
|
+
"""The first place whose glob matches the path, from the repo root."""
|
|
78
|
+
return next((p for p in settings.places if glob_match(p.path, path)), None)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def with_supplied_type(
|
|
82
|
+
path: str, fields: dict[str, Field] | None, settings: Settings
|
|
83
|
+
) -> dict[str, Field] | None:
|
|
84
|
+
"""The fields, with the type its place supplies when the document sets
|
|
85
|
+
none and the place allows only one (ADR-001)."""
|
|
86
|
+
if fields is None or ("type" in fields and fields["type"].value):
|
|
87
|
+
return fields
|
|
88
|
+
place = find_place(path, settings)
|
|
89
|
+
if place is None or len(place.types) != 1:
|
|
90
|
+
return fields
|
|
91
|
+
line = fields["type"].line if "type" in fields else 1
|
|
92
|
+
return {**fields, "type": Field(place.types[0], line)}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_place(
|
|
96
|
+
path: Path, fields: dict[str, Field] | None, settings: Settings
|
|
97
|
+
) -> list[Diagnostic]:
|
|
98
|
+
"""The document's type and label against the first place that matches
|
|
99
|
+
its path, relative to the repo root. Places are opt-in: with none, only
|
|
100
|
+
the label is checked, and each document sets its own. Missing
|
|
101
|
+
frontmatter or type is check_fields' to report."""
|
|
102
|
+
if fields is None:
|
|
103
|
+
return []
|
|
104
|
+
place = find_place(path.as_posix(), settings)
|
|
105
|
+
if place is None and settings.places:
|
|
106
|
+
return [Diagnostic(path, NO_PLACE, "matches no place in doclife.toml")]
|
|
107
|
+
|
|
108
|
+
diagnostics = []
|
|
109
|
+
kind = fields.get("type")
|
|
110
|
+
if place and kind and kind.value and kind.value not in place.types:
|
|
111
|
+
allowed = ", ".join(sorted(place.types))
|
|
112
|
+
diagnostics.append(
|
|
113
|
+
Diagnostic(
|
|
114
|
+
path,
|
|
115
|
+
TYPE_NOT_ALLOWED,
|
|
116
|
+
f"type {kind.value!r} doesn't belong in {place.path}"
|
|
117
|
+
f" (allowed: {allowed})",
|
|
118
|
+
kind.line,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
label = settings.label
|
|
123
|
+
if label is None:
|
|
124
|
+
return diagnostics
|
|
125
|
+
field = fields.get(label.field)
|
|
126
|
+
values = ", ".join(label.values)
|
|
127
|
+
if place and place.label is not None:
|
|
128
|
+
if field is not None:
|
|
129
|
+
diagnostics.append(
|
|
130
|
+
Diagnostic(
|
|
131
|
+
path,
|
|
132
|
+
LABEL_SET_BY_PLACE,
|
|
133
|
+
f"{label.field!r} is set by {place.path} ({place.label});"
|
|
134
|
+
" remove the field",
|
|
135
|
+
field.line,
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
elif field is None or not field.value:
|
|
139
|
+
diagnostics.append(
|
|
140
|
+
Diagnostic(
|
|
141
|
+
path,
|
|
142
|
+
MISSING_LABEL,
|
|
143
|
+
f"{label.field!r} missing (one of: {values})",
|
|
144
|
+
field.line if field else 1,
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
elif field.value not in label.values:
|
|
148
|
+
diagnostics.append(
|
|
149
|
+
Diagnostic(
|
|
150
|
+
path,
|
|
151
|
+
UNKNOWN_LABEL,
|
|
152
|
+
f"{label.field} {field.value!r} is not one of: {values}",
|
|
153
|
+
field.line,
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
return diagnostics
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def check_dates(
|
|
160
|
+
path: Path,
|
|
161
|
+
fields: dict[str, Field] | None,
|
|
162
|
+
types: Mapping[str, TypeRules],
|
|
163
|
+
today: date,
|
|
164
|
+
committed: date | None,
|
|
165
|
+
) -> list[Diagnostic]:
|
|
166
|
+
"""The fixed dates, the dates the type declares, last_reviewed, and
|
|
167
|
+
date_modified against the file's last commit (None: uncommitted)."""
|
|
168
|
+
if fields is None:
|
|
169
|
+
return []
|
|
170
|
+
diagnostics = []
|
|
171
|
+
|
|
172
|
+
def add(rule: Rule, message: str, line: int = 1) -> None:
|
|
173
|
+
diagnostics.append(Diagnostic(path, rule, message, line))
|
|
174
|
+
|
|
175
|
+
kind = fields.get("type")
|
|
176
|
+
declared = types.get(kind.value, TypeRules()).dates if kind else ()
|
|
177
|
+
dates: dict[str, date | None] = {}
|
|
178
|
+
for key in dict.fromkeys((*FIXED_DATES, *declared)):
|
|
179
|
+
field = fields.get(key)
|
|
180
|
+
if field is None or not field.value:
|
|
181
|
+
if key in FIXED_DATES:
|
|
182
|
+
add(MISSING_DATE, f"{key!r} missing", field.line if field else 1)
|
|
183
|
+
continue
|
|
184
|
+
dates[key] = parse_date(field.value)
|
|
185
|
+
if dates[key] is None:
|
|
186
|
+
add(INVALID_DATE, f"{key} {field.value!r} is not YYYY-MM-DD", field.line)
|
|
187
|
+
|
|
188
|
+
created, modified = dates.get("date_created"), dates.get("date_modified")
|
|
189
|
+
if created and modified and created > modified:
|
|
190
|
+
add(
|
|
191
|
+
CREATED_AFTER_MODIFIED,
|
|
192
|
+
f"date_created {created} is after date_modified {modified}",
|
|
193
|
+
fields["date_created"].line,
|
|
194
|
+
)
|
|
195
|
+
if modified and committed and modified < committed:
|
|
196
|
+
add(
|
|
197
|
+
MODIFIED_BEFORE_COMMIT,
|
|
198
|
+
f"date_modified {modified} is older than the last commit ({committed});"
|
|
199
|
+
" run doclife stamp",
|
|
200
|
+
fields["date_modified"].line,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
reviewed = fields.get("last_reviewed")
|
|
204
|
+
if reviewed and reviewed.value and reviewed.value != REVIEW_NEVER:
|
|
205
|
+
reviewed_on = parse_date(reviewed.value)
|
|
206
|
+
if reviewed_on is None:
|
|
207
|
+
add(
|
|
208
|
+
INVALID_LAST_REVIEWED,
|
|
209
|
+
f"last_reviewed {reviewed.value!r} is not YYYY-MM-DD or never",
|
|
210
|
+
reviewed.line,
|
|
211
|
+
)
|
|
212
|
+
elif reviewed_on > today:
|
|
213
|
+
add(
|
|
214
|
+
REVIEWED_IN_FUTURE,
|
|
215
|
+
f"last_reviewed {reviewed_on} is after today",
|
|
216
|
+
reviewed.line,
|
|
217
|
+
)
|
|
218
|
+
return diagnostics
|
doclife/cli.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Command line entry point (ADR-002)."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from datetime import date
|
|
7
|
+
from importlib.metadata import version
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from doclife.check import check_documents
|
|
11
|
+
from doclife.files import is_document
|
|
12
|
+
from doclife.frontmatter import parse_frontmatter
|
|
13
|
+
from doclife.git import GitError, last_commit_dates, repo_prefix, tracked_files
|
|
14
|
+
from doclife.ids import index_files, needs_every_document
|
|
15
|
+
from doclife.names import comparable
|
|
16
|
+
from doclife.output import FORMATS, render, shown
|
|
17
|
+
from doclife.review import review_due
|
|
18
|
+
from doclife.rule_docs import explain
|
|
19
|
+
from doclife.rules import find_rule
|
|
20
|
+
from doclife.settings import Settings, SettingsError, find_settings, load_settings
|
|
21
|
+
from doclife.stamp import stamp_file
|
|
22
|
+
|
|
23
|
+
EXIT_OK = 0
|
|
24
|
+
EXIT_FOUND = 1 # problems found, or documents due for review
|
|
25
|
+
EXIT_ERROR = 2 # doclife couldn't run; argparse uses 2 for usage errors too
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Failure(Exception):
|
|
29
|
+
"""A reason doclife couldn't run, such as a path that doesn't exist."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main(argv: Sequence[str] | None = None, *, today: date | None = None) -> int:
|
|
33
|
+
# Windows gives piped output the locale's code page; paths need UTF-8.
|
|
34
|
+
for stream in (sys.stdout, sys.stderr):
|
|
35
|
+
if hasattr(stream, "reconfigure"):
|
|
36
|
+
stream.reconfigure(encoding="utf-8")
|
|
37
|
+
parser = argparse.ArgumentParser(
|
|
38
|
+
prog="doclife", description="Frontmatter checks for docs in git."
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"--version", action="version", version=f"%(prog)s {version('doclife')}"
|
|
42
|
+
)
|
|
43
|
+
commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
44
|
+
configured = argparse.ArgumentParser(add_help=False)
|
|
45
|
+
configured.add_argument(
|
|
46
|
+
"--config",
|
|
47
|
+
type=Path,
|
|
48
|
+
metavar="PATH",
|
|
49
|
+
help="the settings file (default: the nearest doclife.toml)",
|
|
50
|
+
)
|
|
51
|
+
check = commands.add_parser(
|
|
52
|
+
"check",
|
|
53
|
+
parents=[configured],
|
|
54
|
+
help="report problems in the given documents, or all tracked ones",
|
|
55
|
+
)
|
|
56
|
+
check.add_argument("paths", nargs="*", type=Path, metavar="PATH")
|
|
57
|
+
check.add_argument(
|
|
58
|
+
"--output-format",
|
|
59
|
+
choices=FORMATS,
|
|
60
|
+
default=FORMATS[0],
|
|
61
|
+
help="how to write the problems found (default: %(default)s)",
|
|
62
|
+
)
|
|
63
|
+
stamp = commands.add_parser(
|
|
64
|
+
"stamp",
|
|
65
|
+
parents=[configured],
|
|
66
|
+
help="set date_modified to today in the given documents",
|
|
67
|
+
)
|
|
68
|
+
stamp.add_argument("paths", nargs="+", type=Path, metavar="PATH")
|
|
69
|
+
review = commands.add_parser(
|
|
70
|
+
"review-due",
|
|
71
|
+
parents=[configured],
|
|
72
|
+
help="list documents due for review; exits 1 if any are",
|
|
73
|
+
)
|
|
74
|
+
review.add_argument(
|
|
75
|
+
"--exit-zero",
|
|
76
|
+
action="store_true",
|
|
77
|
+
help="exit 0 even when documents are due",
|
|
78
|
+
)
|
|
79
|
+
rule = commands.add_parser("rule", help="explain a rule, by its code or name")
|
|
80
|
+
rule.add_argument("selector", metavar="CODE|NAME")
|
|
81
|
+
args = parser.parse_args(argv)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
if args.command == "rule":
|
|
85
|
+
return _rule(args.selector)
|
|
86
|
+
settings_path = args.config or find_settings(Path.cwd())
|
|
87
|
+
settings = load_settings(settings_path)
|
|
88
|
+
root = settings_path.parent
|
|
89
|
+
today = today or date.today()
|
|
90
|
+
if args.command == "check":
|
|
91
|
+
return _check(args.paths, settings, root, today, args.output_format)
|
|
92
|
+
if args.command == "stamp":
|
|
93
|
+
return _stamp(args.paths, settings, root, today)
|
|
94
|
+
return _review_due(settings, root, today, args.exit_zero)
|
|
95
|
+
except (SettingsError, GitError, _Failure) as error:
|
|
96
|
+
print(f"doclife: {error}", file=sys.stderr)
|
|
97
|
+
return EXIT_ERROR
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _rule(selector: str) -> int:
|
|
101
|
+
found = find_rule(selector)
|
|
102
|
+
if found is None:
|
|
103
|
+
raise _Failure(f"{selector!r} is not a rule code or name")
|
|
104
|
+
sys.stdout.write(explain(found))
|
|
105
|
+
return EXIT_OK
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _check(
|
|
109
|
+
paths: list[Path], settings: Settings, root: Path, today: date, output_format: str
|
|
110
|
+
) -> int:
|
|
111
|
+
report = None # every document
|
|
112
|
+
texts = {}
|
|
113
|
+
if paths:
|
|
114
|
+
report = {name for _, name in _given_documents(paths, settings, root)}
|
|
115
|
+
texts = {name: _read(root, name) for name in report}
|
|
116
|
+
tracked = []
|
|
117
|
+
if not paths or needs_every_document(settings.types): # always, with an index
|
|
118
|
+
tracked = tracked_files(root)
|
|
119
|
+
texts = _tracked_documents(root, settings, tracked) | texts # given: new
|
|
120
|
+
indexes = {}
|
|
121
|
+
if wanted := index_files(settings.types):
|
|
122
|
+
# The settings may spell an accented name in another form than git.
|
|
123
|
+
by_form = {comparable(name): name for name in tracked}
|
|
124
|
+
for name in wanted:
|
|
125
|
+
found = name if (root / name).is_file() else by_form.get(comparable(name))
|
|
126
|
+
if found:
|
|
127
|
+
indexes[name] = _read(root, found)
|
|
128
|
+
diagnostics = check_documents(
|
|
129
|
+
texts, settings, today, last_commit_dates(root), indexes, report=report
|
|
130
|
+
)
|
|
131
|
+
prefix = repo_prefix(root) if output_format == "github" else ""
|
|
132
|
+
sys.stdout.write(render(diagnostics, output_format, root, prefix=prefix))
|
|
133
|
+
if diagnostics:
|
|
134
|
+
count = len(diagnostics)
|
|
135
|
+
print(f"{count} problem{'' if count == 1 else 's'}", file=sys.stderr)
|
|
136
|
+
return EXIT_FOUND if diagnostics else EXIT_OK
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _stamp(paths: list[Path], settings: Settings, root: Path, today: date) -> int:
|
|
140
|
+
for path, _ in _given_documents(paths, settings, root):
|
|
141
|
+
if stamp_file(path, today):
|
|
142
|
+
print(f"stamped {path.as_posix()}", file=sys.stderr)
|
|
143
|
+
return EXIT_OK
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _review_due(settings: Settings, root: Path, today: date, exit_zero: bool) -> int:
|
|
147
|
+
documents = [
|
|
148
|
+
(name, parse_frontmatter(text))
|
|
149
|
+
for name, text in _tracked_documents(
|
|
150
|
+
root, settings, tracked_files(root)
|
|
151
|
+
).items()
|
|
152
|
+
]
|
|
153
|
+
due = review_due(documents, settings, today)
|
|
154
|
+
for entry in due:
|
|
155
|
+
path = shown(root, entry.path)
|
|
156
|
+
if entry.last_reviewed is None:
|
|
157
|
+
print(f"{path}: never reviewed")
|
|
158
|
+
else:
|
|
159
|
+
days = (today - entry.last_reviewed).days
|
|
160
|
+
print(f"{path}: last reviewed {entry.last_reviewed}, {days} days ago")
|
|
161
|
+
return EXIT_FOUND if due and not exit_zero else EXIT_OK
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _given_documents(
|
|
165
|
+
paths: list[Path], settings: Settings, root: Path
|
|
166
|
+
) -> list[tuple[Path, str]]:
|
|
167
|
+
"""The documents among the paths given, each with its path from the root.
|
|
168
|
+
|
|
169
|
+
Every path must exist and be in the repo, or doclife can't run.
|
|
170
|
+
"""
|
|
171
|
+
root = root.resolve()
|
|
172
|
+
documents = []
|
|
173
|
+
for path in paths:
|
|
174
|
+
if not path.is_file():
|
|
175
|
+
raise _Failure(f"{path.as_posix()}: no such file")
|
|
176
|
+
try:
|
|
177
|
+
name = path.resolve().relative_to(root).as_posix()
|
|
178
|
+
except ValueError:
|
|
179
|
+
raise _Failure(f"{path.as_posix()}: outside the repo at {root}") from None
|
|
180
|
+
if is_document(name, settings):
|
|
181
|
+
documents.append((path, name))
|
|
182
|
+
return documents
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _tracked_documents(
|
|
186
|
+
root: Path, settings: Settings, tracked: list[str]
|
|
187
|
+
) -> dict[str, str]:
|
|
188
|
+
"""Each tracked document's text, by its path from the root."""
|
|
189
|
+
return {
|
|
190
|
+
name: _read(root, name)
|
|
191
|
+
for name in tracked
|
|
192
|
+
if is_document(name, settings) and (root / name).is_file() # not deleted
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _read(root: Path, name: str) -> str:
|
|
197
|
+
return (root / name).read_text("utf-8-sig") # drops a byte order mark
|
doclife/files.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Which files are documents."""
|
|
2
|
+
|
|
3
|
+
from doclife.globs import glob_match
|
|
4
|
+
from doclife.settings import Settings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def is_document(path: str, settings: Settings) -> bool:
|
|
8
|
+
"""Whether a /-separated path from the repo root is one of the repo's
|
|
9
|
+
documents: include matches it and exclude doesn't."""
|
|
10
|
+
return any(glob_match(p, path) for p in settings.include) and not any(
|
|
11
|
+
glob_match(p, path) for p in settings.exclude
|
|
12
|
+
)
|
doclife/frontmatter.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""A document's frontmatter: the leading `---` block of `key: value` lines.
|
|
2
|
+
|
|
3
|
+
Not YAML: only top-level pairs are read, so doclife needs no parser outside
|
|
4
|
+
the standard library. Indented, comment and bare lines are skipped.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import date
|
|
10
|
+
|
|
11
|
+
DELIMITER = "---"
|
|
12
|
+
H1 = "# "
|
|
13
|
+
ISO_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
14
|
+
IGNORE_COMMENT = re.compile(r"#\s*doclife:\s*ignore\s+(.+)") # ADR-002
|
|
15
|
+
SELECTOR_SEPARATOR = re.compile(r"[,\s]+")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Field:
|
|
20
|
+
value: str
|
|
21
|
+
line: int # 1-based, in the whole document
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Document:
|
|
26
|
+
"""A document's text and its frontmatter, parsed once for every check."""
|
|
27
|
+
|
|
28
|
+
text: str
|
|
29
|
+
fields: dict[str, Field] | None # None: no frontmatter
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_frontmatter(text: str) -> dict[str, Field] | None:
|
|
33
|
+
"""The document's fields, or None when it has no closed leading block."""
|
|
34
|
+
block = _block(text)
|
|
35
|
+
if block is None:
|
|
36
|
+
return None
|
|
37
|
+
fields: dict[str, Field] = {}
|
|
38
|
+
for number, line in block:
|
|
39
|
+
key, colon, value = line.partition(":")
|
|
40
|
+
if colon and key and not key.startswith((" ", "\t", "#")):
|
|
41
|
+
fields[key.strip()] = Field(value.strip().strip("\"'"), number)
|
|
42
|
+
return fields
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ignore_comments(text: str) -> list[tuple[int, tuple[str, ...]]]:
|
|
46
|
+
"""Each `# doclife: ignore RULE...` line in the frontmatter: its line
|
|
47
|
+
number and the rules it names, as written."""
|
|
48
|
+
found = []
|
|
49
|
+
for number, line in _block(text) or []:
|
|
50
|
+
match = IGNORE_COMMENT.fullmatch(line.strip())
|
|
51
|
+
if match:
|
|
52
|
+
found.append((number, tuple(SELECTOR_SEPARATOR.split(match[1].strip()))))
|
|
53
|
+
return found
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _block(text: str) -> list[tuple[int, str]] | None:
|
|
57
|
+
"""The numbered lines inside a closed leading --- block, or None."""
|
|
58
|
+
lines = text.splitlines()
|
|
59
|
+
if not lines or lines[0].strip() != DELIMITER:
|
|
60
|
+
return None
|
|
61
|
+
for end, line in enumerate(lines[1:], start=1):
|
|
62
|
+
if line.strip() == DELIMITER:
|
|
63
|
+
return list(enumerate(lines[1:end], start=2))
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def parse_date(value: str) -> date | None:
|
|
68
|
+
"""A YYYY-MM-DD date, or None for anything else."""
|
|
69
|
+
if not ISO_DATE.fullmatch(value):
|
|
70
|
+
return None
|
|
71
|
+
try:
|
|
72
|
+
return date.fromisoformat(value)
|
|
73
|
+
except ValueError: # a day that doesn't exist, such as 2026-02-30
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def first_h1(text: str) -> tuple[int, str] | None:
|
|
78
|
+
"""The line number and text of the first H1 after the frontmatter."""
|
|
79
|
+
lines = text.splitlines()
|
|
80
|
+
body = 0
|
|
81
|
+
if lines and lines[0] == DELIMITER and DELIMITER in lines[1:]:
|
|
82
|
+
body = lines.index(DELIMITER, 1) + 1
|
|
83
|
+
for number, line in enumerate(lines[body:], start=body + 1):
|
|
84
|
+
if line.startswith(H1):
|
|
85
|
+
return number, line[len(H1) :]
|
|
86
|
+
return None
|
doclife/git.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""What doclife reads from git."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from datetime import date
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
COMMIT_MARK = "@" # starts each commit's date line, so it can't be a path
|
|
8
|
+
NOT_FOUND = 1 # git rev-parse --verify --quiet's exit code for a missing name
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GitError(Exception):
|
|
12
|
+
"""git isn't installed, or the folder isn't in a git repo (ADR-002)."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def last_commit_dates(root: Path) -> dict[str, date]:
|
|
16
|
+
"""Each file's last commit date, keyed by its path from root, as
|
|
17
|
+
tracked_files names it. root may be below the repo's top folder.
|
|
18
|
+
|
|
19
|
+
The author date, which survives a rebase. Paths are left unquoted so
|
|
20
|
+
names outside ASCII come back as they are.
|
|
21
|
+
"""
|
|
22
|
+
command = [
|
|
23
|
+
"git",
|
|
24
|
+
"-c",
|
|
25
|
+
"core.quotePath=false",
|
|
26
|
+
"log",
|
|
27
|
+
f"--format={COMMIT_MARK}%as",
|
|
28
|
+
"--name-only",
|
|
29
|
+
"--relative", # from root, not the repo's top folder
|
|
30
|
+
]
|
|
31
|
+
try:
|
|
32
|
+
log = _git(command, root)
|
|
33
|
+
except GitError:
|
|
34
|
+
# git log fails before a repo's first commit, when no file has a
|
|
35
|
+
# commit date yet (#33).
|
|
36
|
+
head = ["git", "rev-parse", "--verify", "--quiet", "HEAD"]
|
|
37
|
+
if _git(head, root, missing_ok=True):
|
|
38
|
+
raise
|
|
39
|
+
return {}
|
|
40
|
+
dates: dict[str, date] = {}
|
|
41
|
+
current: date | None = None
|
|
42
|
+
for line in log.splitlines():
|
|
43
|
+
if line.startswith(COMMIT_MARK):
|
|
44
|
+
current = date.fromisoformat(line[1:])
|
|
45
|
+
elif line and current is not None:
|
|
46
|
+
dates.setdefault(line, current) # newest first, so the first wins
|
|
47
|
+
return dates
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def tracked_files(root: Path) -> list[str]:
|
|
51
|
+
"""Every tracked file's path from root (ADR-002).
|
|
52
|
+
|
|
53
|
+
NUL-separated, so git leaves names outside ASCII unquoted.
|
|
54
|
+
"""
|
|
55
|
+
return [path for path in _git(["git", "ls-files", "-z"], root).split("\0") if path]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def repo_prefix(root: Path) -> str:
|
|
59
|
+
"""root's folder from the repo's top one, ending in /: "cfg/", or ""
|
|
60
|
+
at the top."""
|
|
61
|
+
return _git(["git", "rev-parse", "--show-prefix"], root).rstrip("\n")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _git(command: list[str], root: Path, *, missing_ok: bool = False) -> str:
|
|
65
|
+
"""git's output; empty, with missing_ok, when rev-parse finds no such
|
|
66
|
+
name."""
|
|
67
|
+
try:
|
|
68
|
+
return subprocess.run(
|
|
69
|
+
command, cwd=root, capture_output=True, encoding="utf-8", check=True
|
|
70
|
+
).stdout
|
|
71
|
+
except FileNotFoundError as error:
|
|
72
|
+
raise GitError("git is not installed or not on PATH") from error
|
|
73
|
+
except subprocess.CalledProcessError as error:
|
|
74
|
+
if missing_ok and error.returncode == NOT_FOUND:
|
|
75
|
+
return ""
|
|
76
|
+
raise GitError(error.stderr.strip() or str(error)) from error
|