todo-ticker 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.
- todo_ticker/__init__.py +3 -0
- todo_ticker/cli.py +310 -0
- todo_ticker/counting.py +70 -0
- todo_ticker/discovery.py +98 -0
- todo_ticker/editing.py +45 -0
- todo_ticker/grouping.py +82 -0
- todo_ticker/ids.py +75 -0
- todo_ticker/languages.py +141 -0
- todo_ticker/models.py +35 -0
- todo_ticker/parser.py +141 -0
- todo_ticker/render.py +204 -0
- todo_ticker/resolve.py +70 -0
- todo_ticker/scanning.py +89 -0
- todo_ticker-0.1.0.dist-info/METADATA +115 -0
- todo_ticker-0.1.0.dist-info/RECORD +17 -0
- todo_ticker-0.1.0.dist-info/WHEEL +4 -0
- todo_ticker-0.1.0.dist-info/entry_points.txt +4 -0
todo_ticker/__init__.py
ADDED
todo_ticker/cli.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Command-line interface (the imperative shell)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.markup import escape
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .counting import SORTS, Sort, summarise
|
|
19
|
+
from .discovery import discover
|
|
20
|
+
from .editing import EditError, apply_states
|
|
21
|
+
from .grouping import GROUPS, KINDS, Group, Kind, Status, by_kind, display_path, status_filter
|
|
22
|
+
from .ids import shortest_unique_prefixes
|
|
23
|
+
from .models import Entry
|
|
24
|
+
from .render import render, render_change, render_counts
|
|
25
|
+
from .resolve import location_path, resolve
|
|
26
|
+
from .scanning import UnreadableFile, collect, read_text, scan_file_text
|
|
27
|
+
|
|
28
|
+
Action = Literal["check", "uncheck", "toggle"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DefaultToList(click.Group):
|
|
32
|
+
"""Run ``list`` when no sub-command is given, so ``tick foo.tex`` works."""
|
|
33
|
+
|
|
34
|
+
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
|
|
35
|
+
if not args or (args[0] not in self.commands and args[0] not in ("--help", "-h", "--version")):
|
|
36
|
+
args = ["list", *args]
|
|
37
|
+
return super().parse_args(ctx, args)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _consoles(no_color: bool) -> tuple[Console, Console]:
|
|
41
|
+
out = Console(no_color=no_color or None, highlight=False)
|
|
42
|
+
err = Console(stderr=True, no_color=no_color or None, highlight=False)
|
|
43
|
+
return out, err
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _scan(paths: Sequence[Path], err: Console, quiet: bool) -> list[Entry]:
|
|
47
|
+
try:
|
|
48
|
+
files = discover(paths or [Path(".")])
|
|
49
|
+
except FileNotFoundError as exc:
|
|
50
|
+
raise click.BadParameter(f"no such file or directory: {exc.args[0]}", param_hint="PATHS") from exc
|
|
51
|
+
|
|
52
|
+
def warn(message: str) -> None:
|
|
53
|
+
if not quiet:
|
|
54
|
+
err.print(f"[yellow]warning:[/] {message}", markup=True, highlight=False)
|
|
55
|
+
|
|
56
|
+
return collect(files, warn=warn)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_path_type = click.Path(exists=True, path_type=Path)
|
|
60
|
+
_no_color = click.option("--no-color", is_flag=True, envvar="NO_COLOR", help="Disable colour output.")
|
|
61
|
+
_quiet = click.option("-q", "--quiet", is_flag=True, help="Hide warnings about skipped files.")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@click.group(cls=DefaultToList, context_settings={"help_option_names": ["-h", "--help"]})
|
|
65
|
+
@click.version_option(__version__, "--version")
|
|
66
|
+
def main() -> None:
|
|
67
|
+
"""Find, list and tick off todos hiding in code comments.
|
|
68
|
+
|
|
69
|
+
\b
|
|
70
|
+
Recognised inside comments (any comment syntax, start or end of line):
|
|
71
|
+
- [ ] open item - [x] done item
|
|
72
|
+
TODO: something TODO: [x] something done
|
|
73
|
+
FIXME(me): something
|
|
74
|
+
|
|
75
|
+
Running with no sub-command lists todos, e.g. `tick src/ notes.tex`.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_status_options = [
|
|
80
|
+
click.option("-o", "--open", "only_open", is_flag=True, help="Only unticked todos."),
|
|
81
|
+
click.option("-d", "--done", "only_done", is_flag=True, help="Only ticked todos."),
|
|
82
|
+
]
|
|
83
|
+
_kind_option = click.option(
|
|
84
|
+
"-k",
|
|
85
|
+
"--kind",
|
|
86
|
+
"kinds",
|
|
87
|
+
multiple=True,
|
|
88
|
+
type=click.Choice(KINDS),
|
|
89
|
+
help="Only todos of this kind: box (- [ ]), todo (TODO:), fixme (FIXME:). Repeatable.",
|
|
90
|
+
)
|
|
91
|
+
_GROUP_HELP = (
|
|
92
|
+
"Group by file path, by file name (same-named files together), by todo value (identical todos "
|
|
93
|
+
"together), or not at all."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _group_option(default: Group) -> Any:
|
|
98
|
+
return click.option(
|
|
99
|
+
"-g", "--group", type=click.Choice(GROUPS), default=default, show_default=True, help=_GROUP_HELP
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _status(only_open: bool, only_done: bool) -> Status:
|
|
104
|
+
if only_open and only_done:
|
|
105
|
+
raise click.UsageError("--open and --done are mutually exclusive")
|
|
106
|
+
return "open" if only_open else "done" if only_done else "all"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _with(*decorators: Any) -> Any:
|
|
110
|
+
def apply(func: Any) -> Any:
|
|
111
|
+
for decorator in reversed(decorators):
|
|
112
|
+
func = decorator(func)
|
|
113
|
+
return func
|
|
114
|
+
|
|
115
|
+
return apply
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@main.command("list")
|
|
119
|
+
@click.argument("paths", nargs=-1, type=_path_type)
|
|
120
|
+
@_with(*_status_options, _kind_option, _group_option("file"), _no_color, _quiet)
|
|
121
|
+
def list_cmd(
|
|
122
|
+
paths: tuple[Path, ...],
|
|
123
|
+
only_open: bool,
|
|
124
|
+
only_done: bool,
|
|
125
|
+
kinds: tuple[Kind, ...],
|
|
126
|
+
group: Group,
|
|
127
|
+
no_color: bool,
|
|
128
|
+
quiet: bool,
|
|
129
|
+
) -> None:
|
|
130
|
+
"""List todos in PATHS (default: current directory, minus gitignored files)."""
|
|
131
|
+
status = _status(only_open, only_done)
|
|
132
|
+
out, err = _consoles(no_color)
|
|
133
|
+
entries = _scan(paths, err, quiet)
|
|
134
|
+
short = shortest_unique_prefixes([e.id for e in entries])
|
|
135
|
+
render(out, by_kind(entries, kinds), short, cwd=Path.cwd(), group=group, visible=status_filter(status))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@main.command("count")
|
|
139
|
+
@click.argument("paths", nargs=-1, type=_path_type)
|
|
140
|
+
@_with(*_status_options, _kind_option, _group_option("none"))
|
|
141
|
+
@click.option("-s", "--sort", type=click.Choice(SORTS), default="open", show_default=True, help="Order of groups.")
|
|
142
|
+
@click.option("-n", "--limit", type=click.IntRange(min=1), help="Show only the first N groups.")
|
|
143
|
+
@click.option("--json", "as_json", is_flag=True, help="Print machine-readable JSON.")
|
|
144
|
+
@click.option("--exit-code", is_flag=True, help="Exit with status 1 if any open todos are counted (for CI/hooks).")
|
|
145
|
+
@_with(_no_color, _quiet)
|
|
146
|
+
def count_cmd(
|
|
147
|
+
paths: tuple[Path, ...],
|
|
148
|
+
only_open: bool,
|
|
149
|
+
only_done: bool,
|
|
150
|
+
kinds: tuple[Kind, ...],
|
|
151
|
+
group: Group,
|
|
152
|
+
sort: Sort,
|
|
153
|
+
limit: int | None,
|
|
154
|
+
as_json: bool,
|
|
155
|
+
exit_code: bool,
|
|
156
|
+
no_color: bool,
|
|
157
|
+
quiet: bool,
|
|
158
|
+
) -> None:
|
|
159
|
+
"""Count todos in PATHS (default: current directory, minus gitignored files).
|
|
160
|
+
|
|
161
|
+
\b
|
|
162
|
+
With -o or -d (and no -g) just the number is printed, for scripts:
|
|
163
|
+
tick count -o -> 9
|
|
164
|
+
"""
|
|
165
|
+
status = _status(only_open, only_done)
|
|
166
|
+
out, err = _consoles(no_color)
|
|
167
|
+
keep = status_filter(status)
|
|
168
|
+
entries = [e for e in by_kind(_scan(paths, err, quiet), kinds) if keep(e)]
|
|
169
|
+
overall, groups = summarise(entries, group, Path.cwd(), sort=sort)
|
|
170
|
+
omitted = max(0, len(groups) - limit) if limit is not None else 0
|
|
171
|
+
groups = groups[: len(groups) - omitted]
|
|
172
|
+
|
|
173
|
+
if as_json:
|
|
174
|
+
payload: dict[str, Any] = overall.as_dict()
|
|
175
|
+
del payload["label"]
|
|
176
|
+
if group != "none":
|
|
177
|
+
payload["group"] = group
|
|
178
|
+
payload["groups"] = [t.as_dict() for t in groups]
|
|
179
|
+
payload["omitted_groups"] = omitted
|
|
180
|
+
click.echo(json.dumps(payload, indent=2))
|
|
181
|
+
elif status != "all" and group == "none":
|
|
182
|
+
click.echo(overall.total)
|
|
183
|
+
else:
|
|
184
|
+
render_counts(out, overall, groups, group=group, omitted=omitted)
|
|
185
|
+
|
|
186
|
+
if exit_code and overall.open:
|
|
187
|
+
raise SystemExit(1)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _write_atomic(path: Path, text: str) -> None:
|
|
191
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tick")
|
|
192
|
+
tmp = Path(tmp_name)
|
|
193
|
+
try:
|
|
194
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
|
|
195
|
+
handle.write(text)
|
|
196
|
+
os.chmod(tmp, path.stat().st_mode & 0o7777)
|
|
197
|
+
os.replace(tmp, path)
|
|
198
|
+
except BaseException:
|
|
199
|
+
tmp.unlink(missing_ok=True)
|
|
200
|
+
raise
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _apply(
|
|
204
|
+
action: Action,
|
|
205
|
+
refs: tuple[str, ...],
|
|
206
|
+
paths: tuple[Path, ...],
|
|
207
|
+
text_only: bool,
|
|
208
|
+
allow_many: bool,
|
|
209
|
+
dry_run: bool,
|
|
210
|
+
no_color: bool,
|
|
211
|
+
quiet: bool,
|
|
212
|
+
) -> None:
|
|
213
|
+
out, err = _consoles(no_color)
|
|
214
|
+
scope = list(paths) or [Path(".")]
|
|
215
|
+
scope += [p for p in (location_path(r) for r in refs) if p is not None]
|
|
216
|
+
entries = _scan(scope, err, quiet)
|
|
217
|
+
short = shortest_unique_prefixes([e.id for e in entries])
|
|
218
|
+
cwd = Path.cwd()
|
|
219
|
+
|
|
220
|
+
# Resolve everything before touching any file: all-or-nothing.
|
|
221
|
+
selected: dict[tuple[Path, str], Entry] = {}
|
|
222
|
+
problems: list[str] = []
|
|
223
|
+
for ref in refs:
|
|
224
|
+
res = resolve(ref, entries, text_only=text_only)
|
|
225
|
+
if not res.matches:
|
|
226
|
+
problems.append(f"no todo matches [bold]{escape(repr(ref))}[/]")
|
|
227
|
+
elif len(res.matches) > 1 and not allow_many:
|
|
228
|
+
lines = "\n".join(
|
|
229
|
+
f" [magenta]{short[e.id]}[/] "
|
|
230
|
+
f"[cyan]{display_path(e.path, cwd)}:{e.todo.line}[/] {escape(e.todo.text)}"
|
|
231
|
+
for e in res.matches
|
|
232
|
+
)
|
|
233
|
+
problems.append(
|
|
234
|
+
f"{escape(repr(ref))} is ambiguous ({len(res.matches)} matches by {res.how}); "
|
|
235
|
+
f"use an id, path:line, or --all:\n{lines}"
|
|
236
|
+
)
|
|
237
|
+
else:
|
|
238
|
+
for entry in res.matches:
|
|
239
|
+
selected[(entry.path, entry.id)] = entry
|
|
240
|
+
if problems:
|
|
241
|
+
for problem in problems:
|
|
242
|
+
err.print(f"[red]error:[/] {problem}", highlight=False)
|
|
243
|
+
raise SystemExit(1)
|
|
244
|
+
|
|
245
|
+
by_file: defaultdict[Path, list[tuple[Entry, bool]]] = defaultdict(list)
|
|
246
|
+
for entry in selected.values():
|
|
247
|
+
target = {"check": True, "uncheck": False}.get(action, not entry.todo.checked)
|
|
248
|
+
by_file[entry.path].append((entry, target))
|
|
249
|
+
|
|
250
|
+
for path, changes in by_file.items():
|
|
251
|
+
try:
|
|
252
|
+
text = read_text(path)
|
|
253
|
+
except UnreadableFile as exc:
|
|
254
|
+
raise click.ClickException(str(exc)) from exc
|
|
255
|
+
current = {(t.line, t.text) for t in scan_file_text(path, text)}
|
|
256
|
+
if any((e.todo.line, e.todo.text) not in current for e, _ in changes): # pragma: no cover - race
|
|
257
|
+
raise click.ClickException(f"{path} changed while running; nothing written")
|
|
258
|
+
real = [(e.todo, c) for e, c in changes if e.todo.checked != c or not e.todo.has_box]
|
|
259
|
+
try:
|
|
260
|
+
new_text = apply_states(text, real)
|
|
261
|
+
except EditError as exc:
|
|
262
|
+
raise click.ClickException(f"{path}: {exc}") from exc
|
|
263
|
+
if new_text != text and not dry_run:
|
|
264
|
+
_write_atomic(path, new_text)
|
|
265
|
+
for entry, checked in sorted(changes, key=lambda c: c[0].todo.line):
|
|
266
|
+
changed = entry.todo.checked != checked or not entry.todo.has_box
|
|
267
|
+
render_change(out, entry, checked, short[entry.id], cwd, changed=changed)
|
|
268
|
+
|
|
269
|
+
if dry_run:
|
|
270
|
+
out.print("[bright_black italic](dry run: no files were modified)[/]")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _edit_command(action: Action, help_text: str) -> Any:
|
|
274
|
+
@main.command(action, help=help_text)
|
|
275
|
+
@click.argument("refs", nargs=-1, required=True)
|
|
276
|
+
@click.option(
|
|
277
|
+
"-p", "--path", "paths", multiple=True, type=_path_type, help="Restrict the search (repeatable). Default: ."
|
|
278
|
+
)
|
|
279
|
+
@click.option("-t", "--text", "text_only", is_flag=True, help="Treat REFS as todo text only (not ids/locations).")
|
|
280
|
+
@click.option("-a", "--all", "allow_many", is_flag=True, help="Apply to every match of an ambiguous ref.")
|
|
281
|
+
@click.option("-n", "--dry-run", is_flag=True, help="Show what would change without writing.")
|
|
282
|
+
@_no_color
|
|
283
|
+
@_quiet
|
|
284
|
+
def command(
|
|
285
|
+
refs: tuple[str, ...],
|
|
286
|
+
paths: tuple[Path, ...],
|
|
287
|
+
text_only: bool,
|
|
288
|
+
allow_many: bool,
|
|
289
|
+
dry_run: bool,
|
|
290
|
+
no_color: bool,
|
|
291
|
+
quiet: bool,
|
|
292
|
+
) -> None:
|
|
293
|
+
_apply(action, refs, paths, text_only, allow_many, dry_run, no_color, quiet)
|
|
294
|
+
|
|
295
|
+
return command
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
_REF_HELP = """
|
|
299
|
+
|
|
300
|
+
REFS can be an id (or unique prefix) as shown by `list`, a `path:line`
|
|
301
|
+
location, or (part of) the todo's text, case-insensitive.
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
check = _edit_command("check", "Tick todos. Bare TODO: comments gain a [x]." + _REF_HELP)
|
|
305
|
+
uncheck = _edit_command("uncheck", "Untick todos. Bare TODO: comments gain a [ ]." + _REF_HELP)
|
|
306
|
+
toggle = _edit_command("toggle", "Flip todos between ticked and unticked." + _REF_HELP)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
if __name__ == "__main__": # pragma: no cover
|
|
310
|
+
main()
|
todo_ticker/counting.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Pure tallying of todos for the ``count`` command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from .grouping import Group, group_label, ordered_groups
|
|
11
|
+
from .models import Entry
|
|
12
|
+
|
|
13
|
+
Sort = Literal["open", "total", "done", "name"]
|
|
14
|
+
SORTS: tuple[Sort, ...] = ("open", "total", "done", "name")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Tally:
|
|
19
|
+
label: str
|
|
20
|
+
open: int
|
|
21
|
+
done: int
|
|
22
|
+
files: int
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def total(self) -> int:
|
|
26
|
+
return self.open + self.done
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def percent_done(self) -> float:
|
|
30
|
+
return 100.0 * self.done / self.total if self.total else 0.0
|
|
31
|
+
|
|
32
|
+
def as_dict(self) -> dict[str, str | int | float]:
|
|
33
|
+
return {
|
|
34
|
+
"label": self.label,
|
|
35
|
+
"open": self.open,
|
|
36
|
+
"done": self.done,
|
|
37
|
+
"total": self.total,
|
|
38
|
+
"files": self.files,
|
|
39
|
+
"percent_done": round(self.percent_done, 1),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def tally(entries: Sequence[Entry], label: str = "all") -> Tally:
|
|
44
|
+
done = sum(e.todo.checked for e in entries)
|
|
45
|
+
return Tally(label, len(entries) - done, done, len({e.path for e in entries}))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_SORT_KEYS: dict[Sort, Callable[[Tally], tuple[int | str, ...]]] = {
|
|
49
|
+
"open": lambda t: (-t.open, -t.total, t.label.casefold()),
|
|
50
|
+
"total": lambda t: (-t.total, -t.open, t.label.casefold()),
|
|
51
|
+
"done": lambda t: (-t.done, -t.total, t.label.casefold()),
|
|
52
|
+
"name": lambda t: (t.label.casefold(),),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def summarise(
|
|
57
|
+
entries: Sequence[Entry],
|
|
58
|
+
group: Group,
|
|
59
|
+
cwd: Path,
|
|
60
|
+
*,
|
|
61
|
+
sort: Sort = "open",
|
|
62
|
+
) -> tuple[Tally, list[Tally]]:
|
|
63
|
+
"""Overall tally plus one sorted tally per group (empty for
|
|
64
|
+
``group="none"``)."""
|
|
65
|
+
overall = tally(entries)
|
|
66
|
+
if group == "none":
|
|
67
|
+
return overall, []
|
|
68
|
+
groups = [tally(m, group_label(m, group, cwd)) for m in ordered_groups(entries, group, cwd)]
|
|
69
|
+
groups.sort(key=_SORT_KEYS[sort])
|
|
70
|
+
return overall, groups
|
todo_ticker/discovery.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Find the files to scan, honouring ``.gitignore``.
|
|
2
|
+
|
|
3
|
+
Inside a git work tree we ask git itself (``git ls-files``), which also covers
|
|
4
|
+
``.git/info/exclude`` and global excludes. Elsewhere we walk the directory and
|
|
5
|
+
apply any ``.gitignore`` files found along the way.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import pathspec
|
|
16
|
+
|
|
17
|
+
GitLister = Callable[[Path], "list[Path] | None"]
|
|
18
|
+
|
|
19
|
+
ALWAYS_SKIP_DIRS = frozenset({".git", ".hg", ".svn"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def git_ls_files(directory: Path) -> list[Path] | None:
|
|
23
|
+
"""Tracked and untracked-but-not-ignored files under ``directory``, or
|
|
24
|
+
``None`` if git is unavailable or this is not a work tree."""
|
|
25
|
+
try:
|
|
26
|
+
result = subprocess.run(
|
|
27
|
+
["git", "-C", str(directory), "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
|
|
28
|
+
capture_output=True,
|
|
29
|
+
check=False,
|
|
30
|
+
)
|
|
31
|
+
except OSError:
|
|
32
|
+
return None
|
|
33
|
+
if result.returncode != 0:
|
|
34
|
+
return None
|
|
35
|
+
names = result.stdout.decode("utf-8", "surrogateescape").split("\0")
|
|
36
|
+
return [directory / name for name in names if name]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _load_spec(directory: Path) -> pathspec.GitIgnoreSpec | None:
|
|
40
|
+
ignore_file = directory / ".gitignore"
|
|
41
|
+
try:
|
|
42
|
+
lines = ignore_file.read_text(encoding="utf-8").splitlines()
|
|
43
|
+
except (OSError, UnicodeDecodeError):
|
|
44
|
+
return None
|
|
45
|
+
return pathspec.GitIgnoreSpec.from_lines(lines)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def walk_with_gitignore(root: Path) -> Iterator[Path]:
|
|
49
|
+
"""Walk ``root`` skipping anything matched by ``.gitignore`` files.
|
|
50
|
+
|
|
51
|
+
Each ``.gitignore`` applies to paths relative to its own directory. A
|
|
52
|
+
path is skipped if any applicable ``.gitignore`` ignores it.
|
|
53
|
+
"""
|
|
54
|
+
specs: list[tuple[Path, pathspec.GitIgnoreSpec]] = []
|
|
55
|
+
|
|
56
|
+
def ignored(path: Path, is_dir: bool) -> bool:
|
|
57
|
+
for base, spec in specs:
|
|
58
|
+
try:
|
|
59
|
+
rel = path.relative_to(base).as_posix()
|
|
60
|
+
except ValueError:
|
|
61
|
+
continue
|
|
62
|
+
if spec.match_file(rel + "/" if is_dir else rel):
|
|
63
|
+
return True
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
67
|
+
current = Path(dirpath)
|
|
68
|
+
# Drop specs from sibling branches we have left.
|
|
69
|
+
specs[:] = [(base, spec) for base, spec in specs if current == base or base in current.parents]
|
|
70
|
+
spec = _load_spec(current)
|
|
71
|
+
if spec is not None:
|
|
72
|
+
specs.append((current, spec))
|
|
73
|
+
dirnames[:] = sorted(d for d in dirnames if d not in ALWAYS_SKIP_DIRS and not ignored(current / d, True))
|
|
74
|
+
for name in sorted(filenames):
|
|
75
|
+
path = current / name
|
|
76
|
+
if not ignored(path, False):
|
|
77
|
+
yield path
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def discover(paths: Iterable[Path], git_lister: GitLister = git_ls_files) -> list[Path]:
|
|
81
|
+
"""Expand ``paths`` into the files to scan.
|
|
82
|
+
|
|
83
|
+
Explicitly named files are always included, even if ignored. Directories
|
|
84
|
+
are expanded respecting ignore rules. The result is de-duplicated.
|
|
85
|
+
"""
|
|
86
|
+
found: dict[Path, None] = {}
|
|
87
|
+
for path in paths:
|
|
88
|
+
if path.is_dir():
|
|
89
|
+
listed = git_lister(path)
|
|
90
|
+
candidates = listed if listed is not None else walk_with_gitignore(path)
|
|
91
|
+
for candidate in candidates:
|
|
92
|
+
if candidate.is_file() and not candidate.is_symlink():
|
|
93
|
+
found.setdefault(candidate, None)
|
|
94
|
+
elif path.is_file():
|
|
95
|
+
found.setdefault(path, None)
|
|
96
|
+
else:
|
|
97
|
+
raise FileNotFoundError(path)
|
|
98
|
+
return list(found)
|
todo_ticker/editing.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Pure text transformations for ticking/unticking todos."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from .models import Todo
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EditError(ValueError):
|
|
11
|
+
"""Raised when a line no longer looks like the todo we expected."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def set_line_state(line: str, todo: Todo, checked: bool) -> str:
|
|
15
|
+
"""Return ``line`` with ``todo`` set to ``checked``.
|
|
16
|
+
|
|
17
|
+
Checkbox todos have their mark replaced. Bare ``TODO:`` comments gain a
|
|
18
|
+
``[x] `` or ``[ ] `` box in front of their text.
|
|
19
|
+
"""
|
|
20
|
+
mark = "x" if checked else " "
|
|
21
|
+
if todo.has_box:
|
|
22
|
+
if todo.col >= len(line) or line[todo.col] not in " xX":
|
|
23
|
+
raise EditError(f"line {todo.line}: expected a checkbox at column {todo.col + 1}")
|
|
24
|
+
if (line[todo.col] != " ") == checked:
|
|
25
|
+
return line # already in the requested state; keep e.g. an "X"
|
|
26
|
+
return line[: todo.col] + mark + line[todo.col + 1 :]
|
|
27
|
+
|
|
28
|
+
if todo.col > len(line):
|
|
29
|
+
raise EditError(f"line {todo.line}: line is shorter than expected")
|
|
30
|
+
spacer = "" if todo.col == 0 or line[todo.col - 1] in " \t" else " "
|
|
31
|
+
return f"{line[: todo.col]}{spacer}[{mark}] {line[todo.col :]}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def apply_states(text: str, changes: Iterable[tuple[Todo, bool]]) -> str:
|
|
35
|
+
"""Apply several ``(todo, checked)`` changes to ``text`` at once.
|
|
36
|
+
|
|
37
|
+
Lines are split on ``\\n`` only, so ``\\r\\n`` endings survive untouched.
|
|
38
|
+
"""
|
|
39
|
+
lines = text.split("\n")
|
|
40
|
+
# Right-to-left within a line so earlier columns stay valid.
|
|
41
|
+
for todo, checked in sorted(changes, key=lambda c: (c[0].line, c[0].col), reverse=True):
|
|
42
|
+
if not 1 <= todo.line <= len(lines):
|
|
43
|
+
raise EditError(f"line {todo.line} is out of range")
|
|
44
|
+
lines[todo.line - 1] = set_line_state(lines[todo.line - 1], todo, checked)
|
|
45
|
+
return "\n".join(lines)
|
todo_ticker/grouping.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Pure helpers for grouping and filtering entries, shared by list and count."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from .ids import normalise
|
|
11
|
+
from .models import Entry
|
|
12
|
+
|
|
13
|
+
Group = Literal["file", "name", "value", "none"]
|
|
14
|
+
Kind = Literal["box", "todo", "fixme"]
|
|
15
|
+
Status = Literal["all", "open", "done"]
|
|
16
|
+
Filter = Callable[[Entry], bool]
|
|
17
|
+
|
|
18
|
+
GROUPS: tuple[Group, ...] = ("file", "name", "value", "none")
|
|
19
|
+
KINDS: tuple[Kind, ...] = ("box", "todo", "fixme")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def display_path(path: Path, cwd: Path) -> str:
|
|
23
|
+
"""``path`` relative to ``cwd``, always with forward slashes (matching ids
|
|
24
|
+
and ``path:line`` refs, which Windows accepts too)."""
|
|
25
|
+
try:
|
|
26
|
+
return Path(os.path.relpath(path, cwd)).as_posix()
|
|
27
|
+
except ValueError: # pragma: no cover - different drive on Windows
|
|
28
|
+
return path.as_posix()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def group_key(entry: Entry, group: Group, cwd: Path) -> str:
|
|
32
|
+
if group == "name":
|
|
33
|
+
return entry.path.name
|
|
34
|
+
if group == "value":
|
|
35
|
+
return normalise(entry.todo.text)
|
|
36
|
+
if group == "none":
|
|
37
|
+
return ""
|
|
38
|
+
return display_path(entry.path, cwd)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def group_label(members: Sequence[Entry], group: Group, cwd: Path) -> str:
|
|
42
|
+
"""Human-readable name for a group (``members`` must be non-empty)."""
|
|
43
|
+
first = members[0]
|
|
44
|
+
if group == "value":
|
|
45
|
+
return first.todo.text
|
|
46
|
+
if group == "name":
|
|
47
|
+
return first.path.name
|
|
48
|
+
if group == "none":
|
|
49
|
+
return "all"
|
|
50
|
+
return display_path(first.path, cwd)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def ordered_groups(entries: Sequence[Entry], group: Group, cwd: Path) -> list[list[Entry]]:
|
|
54
|
+
"""Split ``entries`` into groups, each in path then line order. Value
|
|
55
|
+
groups are ordered most-repeated first; file and name groups
|
|
56
|
+
alphabetically."""
|
|
57
|
+
buckets: dict[str, list[Entry]] = {}
|
|
58
|
+
for entry in sorted(entries, key=lambda e: (display_path(e.path, cwd), e.todo.line)):
|
|
59
|
+
buckets.setdefault(group_key(entry, group, cwd), []).append(entry)
|
|
60
|
+
if group == "value":
|
|
61
|
+
return [buckets[k] for k in sorted(buckets, key=lambda k: (-len(buckets[k]), k))]
|
|
62
|
+
return [buckets[k] for k in sorted(buckets)]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def kind_of(entry: Entry) -> Kind:
|
|
66
|
+
if entry.todo.kind == "box":
|
|
67
|
+
return "box"
|
|
68
|
+
return "fixme" if entry.todo.keyword == "FIXME" else "todo"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def by_kind(entries: Iterable[Entry], kinds: Iterable[Kind]) -> list[Entry]:
|
|
72
|
+
"""Keep entries of the given kinds; no kinds means keep everything."""
|
|
73
|
+
wanted = set(kinds)
|
|
74
|
+
return [e for e in entries if not wanted or kind_of(e) in wanted]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def status_filter(status: Status) -> Filter:
|
|
78
|
+
if status == "open":
|
|
79
|
+
return lambda e: not e.todo.checked
|
|
80
|
+
if status == "done":
|
|
81
|
+
return lambda e: e.todo.checked
|
|
82
|
+
return lambda _e: True
|
todo_ticker/ids.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Stable, human-friendly ids for todos.
|
|
2
|
+
|
|
3
|
+
An id is derived from a *file key* (the file's path relative to its project
|
|
4
|
+
root, see :func:`todo_ticker.scanning.id_key`), the todo's normalised text and
|
|
5
|
+
its occurrence index among identical texts in that file. It therefore survives
|
|
6
|
+
the todo moving around the file, being ticked/unticked, being converted from
|
|
7
|
+
``TODO:`` to ``- [ ]``, and running the tool from a different directory, while
|
|
8
|
+
identical todos in same-named files in different folders still get different
|
|
9
|
+
ids.
|
|
10
|
+
|
|
11
|
+
Ids use Crockford's base32 alphabet (no ``i l o u``) so they are easy to read
|
|
12
|
+
aloud and type. Like git hashes, any unique prefix can be used.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import re
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from collections.abc import Iterable, Sequence
|
|
21
|
+
|
|
22
|
+
from .models import Todo
|
|
23
|
+
|
|
24
|
+
ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"
|
|
25
|
+
ID_LENGTH = 8
|
|
26
|
+
MIN_DISPLAY = 4
|
|
27
|
+
|
|
28
|
+
_WS = re.compile(r"\s+")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def normalise(text: str) -> str:
|
|
32
|
+
return _WS.sub(" ", text.strip()).casefold()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def make_id(file_key: str, text: str, occurrence: int = 0) -> str:
|
|
36
|
+
digest = hashlib.sha1(f"{file_key}\0{normalise(text)}\0{occurrence}".encode()).digest()
|
|
37
|
+
value = int.from_bytes(digest[:5], "big") # 40 bits -> 8 base32 chars
|
|
38
|
+
chars: list[str] = []
|
|
39
|
+
for _ in range(ID_LENGTH):
|
|
40
|
+
value, rem = divmod(value, 32)
|
|
41
|
+
chars.append(ALPHABET[rem])
|
|
42
|
+
return "".join(reversed(chars))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def assign_ids(file_key: str, todos: Iterable[Todo]) -> list[str]:
|
|
46
|
+
seen: Counter[str] = Counter()
|
|
47
|
+
ids: list[str] = []
|
|
48
|
+
for todo in todos:
|
|
49
|
+
key = normalise(todo.text)
|
|
50
|
+
ids.append(make_id(file_key, todo.text, seen[key]))
|
|
51
|
+
seen[key] += 1
|
|
52
|
+
return ids
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def shortest_unique_prefixes(ids: Sequence[str], minimum: int = MIN_DISPLAY) -> dict[str, str]:
|
|
56
|
+
"""Map each id to its shortest prefix (at least ``minimum`` long) that no
|
|
57
|
+
other id in ``ids`` shares."""
|
|
58
|
+
ordered = sorted(set(ids))
|
|
59
|
+
result: dict[str, str] = {}
|
|
60
|
+
for i, current in enumerate(ordered):
|
|
61
|
+
needed = minimum
|
|
62
|
+
for neighbour in (ordered[i - 1] if i > 0 else None, ordered[i + 1] if i + 1 < len(ordered) else None):
|
|
63
|
+
if neighbour is None:
|
|
64
|
+
continue
|
|
65
|
+
common = 0
|
|
66
|
+
while common < len(current) and current[common] == neighbour[common]:
|
|
67
|
+
common += 1
|
|
68
|
+
needed = max(needed, common + 1)
|
|
69
|
+
result[current] = current[: min(needed, len(current))]
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def looks_like_id(ref: str) -> bool:
|
|
74
|
+
ref = ref.lower()
|
|
75
|
+
return len(ref) >= 3 and all(c in ALPHABET for c in ref)
|