todo-ticker 0.1.0__tar.gz
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-0.1.0/PKG-INFO +115 -0
- todo_ticker-0.1.0/README.md +97 -0
- todo_ticker-0.1.0/pyproject.toml +54 -0
- todo_ticker-0.1.0/src/todo_ticker/__init__.py +3 -0
- todo_ticker-0.1.0/src/todo_ticker/cli.py +310 -0
- todo_ticker-0.1.0/src/todo_ticker/counting.py +70 -0
- todo_ticker-0.1.0/src/todo_ticker/discovery.py +98 -0
- todo_ticker-0.1.0/src/todo_ticker/editing.py +45 -0
- todo_ticker-0.1.0/src/todo_ticker/grouping.py +82 -0
- todo_ticker-0.1.0/src/todo_ticker/ids.py +75 -0
- todo_ticker-0.1.0/src/todo_ticker/languages.py +141 -0
- todo_ticker-0.1.0/src/todo_ticker/models.py +35 -0
- todo_ticker-0.1.0/src/todo_ticker/parser.py +141 -0
- todo_ticker-0.1.0/src/todo_ticker/render.py +204 -0
- todo_ticker-0.1.0/src/todo_ticker/resolve.py +70 -0
- todo_ticker-0.1.0/src/todo_ticker/scanning.py +89 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: todo-ticker
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Find, list and tick off markdown-style todos hiding in source code comments
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
13
|
+
Requires-Dist: click (>=8.1)
|
|
14
|
+
Requires-Dist: pathspec (>=0.12)
|
|
15
|
+
Requires-Dist: rich (>=13.0)
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# Todo Ticker
|
|
19
|
+
|
|
20
|
+
Find, list and tick off todos hiding in code comments.
|
|
21
|
+
|
|
22
|
+
```latex
|
|
23
|
+
% - [ ] Do a thing
|
|
24
|
+
% - [x] Do another thing
|
|
25
|
+
50\% done % TODO: fix the citation
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
poetry install # dev, venv in ./.venv
|
|
32
|
+
pipx install . # or install the `todo-ticker` / `tick` commands globally
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Disclaimer
|
|
36
|
+
|
|
37
|
+
95% Claude. Just wanted this project to support another project.
|
|
38
|
+
|
|
39
|
+
## What it finds
|
|
40
|
+
|
|
41
|
+
Inside comments only, anywhere on a line (start or end), in line or block comments:
|
|
42
|
+
|
|
43
|
+
Form | Meaning
|
|
44
|
+
:-- | :--
|
|
45
|
+
`- [ ] text` (`*`/`+` too) | open
|
|
46
|
+
`- [x] text` / `- [X] text` | done
|
|
47
|
+
`TODO: text`, `FIXME(me): x` | open (no box yet)
|
|
48
|
+
`TODO: [x] text` | done
|
|
49
|
+
|
|
50
|
+
Comment syntax is chosen by filename (`Makefile`, `.bashrc`, …), then
|
|
51
|
+
extension, then shebang (`#!/usr/bin/env node`), then content sniffing
|
|
52
|
+
(`\documentclass`, `<!DOCTYPE`, `<?php`), falling back to a generic mode
|
|
53
|
+
accepting `#`, `//`, `%`, `--`, `;`, `/* */` and `<!-- -->`. Markers inside
|
|
54
|
+
string literals and LaTeX's `\%` are ignored. Markdown files are scanned
|
|
55
|
+
for `<!-- -->` comments only, so ordinary task lists aren't picked up.
|
|
56
|
+
|
|
57
|
+
Directories are walked using `git ls-files` (respects `.gitignore`,
|
|
58
|
+
`.git/info/exclude` and global excludes); outside a repo, `.gitignore` files
|
|
59
|
+
are applied directly. Files named explicitly are always scanned.
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
tick # list everything under .
|
|
65
|
+
tick src/ notes.tex # specific paths
|
|
66
|
+
tick -o # open only (-d: done only)
|
|
67
|
+
tick -g name # group same-named files from different dirs
|
|
68
|
+
tick -g value # group identical todos across files (e.g. "Spelling")
|
|
69
|
+
tick -g none # flat path:line list
|
|
70
|
+
tick -k todo -k fixme # only TODO:/FIXME: comments (box = - [ ] items)
|
|
71
|
+
|
|
72
|
+
tick count # 6 open · 5 done · 11 total (45% done) · 6 files
|
|
73
|
+
tick count -o # just the number: 6
|
|
74
|
+
tick count -g file # table of open/done/total per file
|
|
75
|
+
tick count -g value -s total -n 10 # ten most-repeated todos
|
|
76
|
+
tick count --json -g name # machine-readable
|
|
77
|
+
tick count -o --exit-code # exit 1 if anything is open (CI, pre-commit)
|
|
78
|
+
|
|
79
|
+
tick check 7k2m # by id (any unique prefix, like git)
|
|
80
|
+
tick check paper.tex:12 # by location
|
|
81
|
+
tick check "fix the citation" # by text (case-insensitive substring)
|
|
82
|
+
tick uncheck 7k2m
|
|
83
|
+
tick toggle 7k2m q9xd -n # several at once; -n = dry run
|
|
84
|
+
tick check thing --all # apply to every match of an ambiguous ref
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Ticking a bare `TODO: text` turns it into `TODO: [x] text`; unticking gives
|
|
88
|
+
`TODO: [ ] text`.
|
|
89
|
+
|
|
90
|
+
### Ids
|
|
91
|
+
|
|
92
|
+
Each todo's id is a hash of the file's path within its project (the nearest
|
|
93
|
+
folder containing `.git`; the absolute path when there isn't one), the todo's
|
|
94
|
+
normalised text and its occurrence index, written in Crockford base32 (no `i`,
|
|
95
|
+
`l`, `o`, `u`). It is stable when the todo moves within the file, is
|
|
96
|
+
ticked/unticked, or the tool is run from a different directory, and identical
|
|
97
|
+
todos in same-named files in different folders get different ids. It changes
|
|
98
|
+
if the text is edited or the file is renamed or moved. `list` shows the
|
|
99
|
+
shortest unique prefix (min. 4 chars).
|
|
100
|
+
|
|
101
|
+
If any ref is missing or ambiguous, nothing is written. Files are written
|
|
102
|
+
atomically, preserving permissions and line endings.
|
|
103
|
+
|
|
104
|
+
## Development
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
poetry install # includes dev tools
|
|
108
|
+
poetry run poe test # tests + coverage (>= 90%); extra args go to pytest, e.g. -k parser
|
|
109
|
+
poetry run poe lint # ruff check
|
|
110
|
+
poetry run poe fix # ruff --fix + format
|
|
111
|
+
poetry run poe typecheck # pyright (strict)
|
|
112
|
+
poetry run poe check # everything CI runs
|
|
113
|
+
poetry run poe # list tasks
|
|
114
|
+
```
|
|
115
|
+
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Todo Ticker
|
|
2
|
+
|
|
3
|
+
Find, list and tick off todos hiding in code comments.
|
|
4
|
+
|
|
5
|
+
```latex
|
|
6
|
+
% - [ ] Do a thing
|
|
7
|
+
% - [x] Do another thing
|
|
8
|
+
50\% done % TODO: fix the citation
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
poetry install # dev, venv in ./.venv
|
|
15
|
+
pipx install . # or install the `todo-ticker` / `tick` commands globally
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Disclaimer
|
|
19
|
+
|
|
20
|
+
95% Claude. Just wanted this project to support another project.
|
|
21
|
+
|
|
22
|
+
## What it finds
|
|
23
|
+
|
|
24
|
+
Inside comments only, anywhere on a line (start or end), in line or block comments:
|
|
25
|
+
|
|
26
|
+
Form | Meaning
|
|
27
|
+
:-- | :--
|
|
28
|
+
`- [ ] text` (`*`/`+` too) | open
|
|
29
|
+
`- [x] text` / `- [X] text` | done
|
|
30
|
+
`TODO: text`, `FIXME(me): x` | open (no box yet)
|
|
31
|
+
`TODO: [x] text` | done
|
|
32
|
+
|
|
33
|
+
Comment syntax is chosen by filename (`Makefile`, `.bashrc`, …), then
|
|
34
|
+
extension, then shebang (`#!/usr/bin/env node`), then content sniffing
|
|
35
|
+
(`\documentclass`, `<!DOCTYPE`, `<?php`), falling back to a generic mode
|
|
36
|
+
accepting `#`, `//`, `%`, `--`, `;`, `/* */` and `<!-- -->`. Markers inside
|
|
37
|
+
string literals and LaTeX's `\%` are ignored. Markdown files are scanned
|
|
38
|
+
for `<!-- -->` comments only, so ordinary task lists aren't picked up.
|
|
39
|
+
|
|
40
|
+
Directories are walked using `git ls-files` (respects `.gitignore`,
|
|
41
|
+
`.git/info/exclude` and global excludes); outside a repo, `.gitignore` files
|
|
42
|
+
are applied directly. Files named explicitly are always scanned.
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
tick # list everything under .
|
|
48
|
+
tick src/ notes.tex # specific paths
|
|
49
|
+
tick -o # open only (-d: done only)
|
|
50
|
+
tick -g name # group same-named files from different dirs
|
|
51
|
+
tick -g value # group identical todos across files (e.g. "Spelling")
|
|
52
|
+
tick -g none # flat path:line list
|
|
53
|
+
tick -k todo -k fixme # only TODO:/FIXME: comments (box = - [ ] items)
|
|
54
|
+
|
|
55
|
+
tick count # 6 open · 5 done · 11 total (45% done) · 6 files
|
|
56
|
+
tick count -o # just the number: 6
|
|
57
|
+
tick count -g file # table of open/done/total per file
|
|
58
|
+
tick count -g value -s total -n 10 # ten most-repeated todos
|
|
59
|
+
tick count --json -g name # machine-readable
|
|
60
|
+
tick count -o --exit-code # exit 1 if anything is open (CI, pre-commit)
|
|
61
|
+
|
|
62
|
+
tick check 7k2m # by id (any unique prefix, like git)
|
|
63
|
+
tick check paper.tex:12 # by location
|
|
64
|
+
tick check "fix the citation" # by text (case-insensitive substring)
|
|
65
|
+
tick uncheck 7k2m
|
|
66
|
+
tick toggle 7k2m q9xd -n # several at once; -n = dry run
|
|
67
|
+
tick check thing --all # apply to every match of an ambiguous ref
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Ticking a bare `TODO: text` turns it into `TODO: [x] text`; unticking gives
|
|
71
|
+
`TODO: [ ] text`.
|
|
72
|
+
|
|
73
|
+
### Ids
|
|
74
|
+
|
|
75
|
+
Each todo's id is a hash of the file's path within its project (the nearest
|
|
76
|
+
folder containing `.git`; the absolute path when there isn't one), the todo's
|
|
77
|
+
normalised text and its occurrence index, written in Crockford base32 (no `i`,
|
|
78
|
+
`l`, `o`, `u`). It is stable when the todo moves within the file, is
|
|
79
|
+
ticked/unticked, or the tool is run from a different directory, and identical
|
|
80
|
+
todos in same-named files in different folders get different ids. It changes
|
|
81
|
+
if the text is edited or the file is renamed or moved. `list` shows the
|
|
82
|
+
shortest unique prefix (min. 4 chars).
|
|
83
|
+
|
|
84
|
+
If any ref is missing or ambiguous, nothing is written. Files are written
|
|
85
|
+
atomically, preserving permissions and line endings.
|
|
86
|
+
|
|
87
|
+
## Development
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
poetry install # includes dev tools
|
|
91
|
+
poetry run poe test # tests + coverage (>= 90%); extra args go to pytest, e.g. -k parser
|
|
92
|
+
poetry run poe lint # ruff check
|
|
93
|
+
poetry run poe fix # ruff --fix + format
|
|
94
|
+
poetry run poe typecheck # pyright (strict)
|
|
95
|
+
poetry run poe check # everything CI runs
|
|
96
|
+
poetry run poe # list tasks
|
|
97
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "todo-ticker"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Find, list and tick off markdown-style todos hiding in source code comments"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"click>=8.1",
|
|
9
|
+
"rich>=13.0",
|
|
10
|
+
"pathspec>=0.12",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
todo-ticker = "todo_ticker.cli:main"
|
|
15
|
+
tick = "todo_ticker.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.poetry]
|
|
18
|
+
packages = [{ include = "todo_ticker", from = "src" }]
|
|
19
|
+
|
|
20
|
+
[tool.poetry.group.dev.dependencies]
|
|
21
|
+
pytest = ">=8.0"
|
|
22
|
+
pytest-cov = ">=5.0"
|
|
23
|
+
ruff = ">=0.6"
|
|
24
|
+
pyright = ">=1.1.380"
|
|
25
|
+
poethepoet = ">=0.29"
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
testpaths = ["tests"]
|
|
29
|
+
addopts = "--cov=todo_ticker --cov-report=term-missing --cov-fail-under=90"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["poetry-core>=2.0.0"]
|
|
33
|
+
build-backend = "poetry.core.masonry.api"
|
|
34
|
+
|
|
35
|
+
[tool.ruff]
|
|
36
|
+
line-length = 120
|
|
37
|
+
target-version = "py310"
|
|
38
|
+
|
|
39
|
+
[tool.ruff.lint]
|
|
40
|
+
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"]
|
|
41
|
+
|
|
42
|
+
[tool.pyright]
|
|
43
|
+
include = ["src", "tests"]
|
|
44
|
+
venvPath = "."
|
|
45
|
+
venv = ".venv"
|
|
46
|
+
typeCheckingMode = "strict"
|
|
47
|
+
|
|
48
|
+
[tool.poe.tasks]
|
|
49
|
+
test = { cmd = "pytest", help = "Run tests with coverage (extra args go to pytest)" }
|
|
50
|
+
lint = { cmd = "ruff check .", help = "Lint with ruff" }
|
|
51
|
+
format = { cmd = "ruff format .", help = "Format with ruff" }
|
|
52
|
+
typecheck = { cmd = "pyright", help = "Type-check with pyright" }
|
|
53
|
+
fix = { sequence = ["ruff check --fix .", "ruff format ."], default_item_type = "cmd", help = "Autofix lint issues and format" }
|
|
54
|
+
check = { sequence = ["lint", { cmd = "ruff format --check ." }, "typecheck", "test"], help = "Everything CI runs" }
|
|
@@ -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()
|
|
@@ -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
|