topomark 0.4.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.
- topomark/__init__.py +31 -0
- topomark/__main__.py +3 -0
- topomark/changes.py +169 -0
- topomark/cli.py +209 -0
- topomark/commands/__init__.py +53 -0
- topomark/commands/_common.py +27 -0
- topomark/commands/agent_hook.py +338 -0
- topomark/commands/brief.py +272 -0
- topomark/commands/capabilities.py +47 -0
- topomark/commands/changes.py +217 -0
- topomark/commands/check.py +41 -0
- topomark/commands/diff.py +81 -0
- topomark/commands/doctor.py +67 -0
- topomark/commands/draft.py +149 -0
- topomark/commands/find.py +64 -0
- topomark/commands/gen.py +33 -0
- topomark/commands/hook.py +104 -0
- topomark/commands/impact.py +82 -0
- topomark/commands/init.py +609 -0
- topomark/commands/locate.py +109 -0
- topomark/commands/map.py +140 -0
- topomark/commands/outline.py +143 -0
- topomark/commands/owner.py +44 -0
- topomark/commands/refs.py +72 -0
- topomark/commands/search.py +82 -0
- topomark/commands/stale.py +49 -0
- topomark/commands/stamp.py +91 -0
- topomark/commands/symbol.py +98 -0
- topomark/commands/sync.py +38 -0
- topomark/commands/syntax.py +61 -0
- topomark/commands/tests_for.py +96 -0
- topomark/config.py +188 -0
- topomark/context.py +58 -0
- topomark/contract.py +28 -0
- topomark/docs.py +174 -0
- topomark/errors.py +75 -0
- topomark/graph.py +133 -0
- topomark/imports.py +321 -0
- topomark/index.py +421 -0
- topomark/lang/__init__.py +0 -0
- topomark/lang/_decl.py +140 -0
- topomark/lang/_imports.py +82 -0
- topomark/lang/base.py +160 -0
- topomark/lang/brace.py +404 -0
- topomark/lang/cfamily.py +340 -0
- topomark/lang/csharp.py +275 -0
- topomark/lang/dart.py +119 -0
- topomark/lang/go.py +104 -0
- topomark/lang/js_ts.py +275 -0
- topomark/lang/kotlin.py +83 -0
- topomark/lang/python.py +235 -0
- topomark/lang/registry.py +72 -0
- topomark/lang/rust.py +117 -0
- topomark/lang/scan.py +466 -0
- topomark/lang/simple.py +408 -0
- topomark/lang/swift.py +91 -0
- topomark/locate.py +342 -0
- topomark/masking.py +36 -0
- topomark/navigate.py +536 -0
- topomark/ranking.py +115 -0
- topomark/repo.py +376 -0
- topomark/runners.py +167 -0
- topomark/search.py +426 -0
- topomark/stamps.py +118 -0
- topomark/syntax.py +288 -0
- topomark/templates/L0.md +82 -0
- topomark/templates/_TEMPLATE.md +67 -0
- topomark/templates/__init__.py +5 -0
- topomark/templates/area.md +30 -0
- topomark/testsel.py +291 -0
- topomark/workspace.py +436 -0
- topomark-0.4.0.dist-info/METADATA +332 -0
- topomark-0.4.0.dist-info/RECORD +77 -0
- topomark-0.4.0.dist-info/WHEEL +5 -0
- topomark-0.4.0.dist-info/entry_points.txt +2 -0
- topomark-0.4.0.dist-info/licenses/LICENSE +21 -0
- topomark-0.4.0.dist-info/top_level.txt +1 -0
topomark/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""topomark: a zero-dependency code map for AI coding agents.
|
|
2
|
+
|
|
3
|
+
The distribution, the import package and the CLI command are all ``topomark``.
|
|
4
|
+
``__version__`` prefers the sibling ``pyproject.toml`` when running from a source
|
|
5
|
+
checkout (``bin/topomark`` / ``PYTHONPATH=src``) so a stale installed copy can't
|
|
6
|
+
misreport, and falls back to the installed metadata.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import tomllib
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _version() -> str:
|
|
16
|
+
pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"
|
|
17
|
+
if pyproject.is_file():
|
|
18
|
+
try:
|
|
19
|
+
with pyproject.open("rb") as fh:
|
|
20
|
+
return str(tomllib.load(fh)["project"]["version"])
|
|
21
|
+
except (OSError, KeyError, tomllib.TOMLDecodeError):
|
|
22
|
+
pass
|
|
23
|
+
from importlib import metadata # slow to import (zipfile, email): only on this fallback path
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
return metadata.version("topomark")
|
|
27
|
+
except metadata.PackageNotFoundError:
|
|
28
|
+
return "0.0.0+unknown"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__version__ = _version()
|
topomark/__main__.py
ADDED
topomark/changes.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""A diff mapped to symbols, for ``topomark changes``.
|
|
2
|
+
|
|
3
|
+
``git diff -U0`` gives the changed line ranges of each file on both sides. The old side is
|
|
4
|
+
analyzed from ``git show REV:path`` with the same language adapter as the new side, and each
|
|
5
|
+
changed line is attributed to the innermost declaration around it, on its own side. Then, by
|
|
6
|
+
qualified name:
|
|
7
|
+
|
|
8
|
+
* **interface:** a symbol that is new, gone, or whose signature (with its attributes, kind
|
|
9
|
+
and exportedness) differs between the two sides; a changed header comment counts too;
|
|
10
|
+
* **body:** a symbol present on both sides with the same signature whose lines changed.
|
|
11
|
+
|
|
12
|
+
Renames are a removal plus an addition (``--no-renames``): that is what callers see.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import codecs
|
|
18
|
+
import re
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import TYPE_CHECKING
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from .lang.base import FileInfo, Symbol
|
|
25
|
+
|
|
26
|
+
_HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class FileDiff:
|
|
31
|
+
path: str
|
|
32
|
+
status: str # added | deleted | modified
|
|
33
|
+
old: set[int] = field(default_factory=set) # changed lines on the old side
|
|
34
|
+
new: set[int] = field(default_factory=set) # changed lines on the new side
|
|
35
|
+
whole: bool = False # untracked: not in the diff at all
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _unquote(p: str) -> str:
|
|
39
|
+
if len(p) >= 2 and p[0] == '"' and p[-1] == '"':
|
|
40
|
+
raw = codecs.escape_decode(p[1:-1].encode("utf-8"))[0]
|
|
41
|
+
return raw.decode("utf-8", errors="replace")
|
|
42
|
+
return p
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _side(p: str) -> str | None:
|
|
46
|
+
"""A ``---`` / ``+++`` path without its ``a/`` or ``b/``; None for ``/dev/null``. Git ends an
|
|
47
|
+
unquoted name that holds a space with a tab (a quoted name has its tabs escaped)."""
|
|
48
|
+
if p.startswith('"'):
|
|
49
|
+
return _unquote(p)[2:]
|
|
50
|
+
if p.endswith("\t"):
|
|
51
|
+
p = p[:-1]
|
|
52
|
+
return None if p == "/dev/null" else p[2:]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _header_path(rest: str) -> str | None:
|
|
56
|
+
"""The path in ``diff --git a/P b/P``. Without renames both sides name the same file, quoted
|
|
57
|
+
alike, so the separating space sits in the middle; None when the line is not like that."""
|
|
58
|
+
half = (len(rest) - 1) // 2
|
|
59
|
+
left, right = rest[:half], rest[half + 1:]
|
|
60
|
+
if len(rest) % 2 == 0 or rest[half] != " ":
|
|
61
|
+
return None
|
|
62
|
+
a, b = _unquote(left), _unquote(right)
|
|
63
|
+
if not (a.startswith("a/") and b.startswith("b/") and a[2:] == b[2:]):
|
|
64
|
+
return None
|
|
65
|
+
return a[2:]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_diff(text: str) -> dict[str, FileDiff]:
|
|
69
|
+
"""``git diff -U0 --no-renames`` output → path → changed lines per side.
|
|
70
|
+
|
|
71
|
+
Each file starts at its ``diff --git`` header, which names it even when no ``---``/``+++``
|
|
72
|
+
lines follow (a mode change, a binary file, an empty file added or deleted); ``new file
|
|
73
|
+
mode`` and ``deleted file mode`` set the status, anything else is ``modified``. After the
|
|
74
|
+
first ``@@`` every line up to the next header is hunk content, so a removed ``-- comment``
|
|
75
|
+
line is never read as a ``---`` header."""
|
|
76
|
+
out: dict[str, FileDiff] = {}
|
|
77
|
+
old_path: str | None = None
|
|
78
|
+
cur: FileDiff | None = None
|
|
79
|
+
in_hunks = False
|
|
80
|
+
for line in text.split("\n"):
|
|
81
|
+
if line.startswith("diff --git "):
|
|
82
|
+
path = _header_path(line[len("diff --git "):])
|
|
83
|
+
cur = out.setdefault(path, FileDiff(path, "modified")) if path else None
|
|
84
|
+
old_path, in_hunks = None, False
|
|
85
|
+
elif line.startswith("@@"):
|
|
86
|
+
in_hunks = True
|
|
87
|
+
m = _HUNK.match(line)
|
|
88
|
+
if cur is None or not m:
|
|
89
|
+
continue
|
|
90
|
+
a, b = int(m[1]), int(m[2]) if m[2] is not None else 1
|
|
91
|
+
c, d = int(m[3]), int(m[4]) if m[4] is not None else 1
|
|
92
|
+
cur.old.update(range(a, a + b))
|
|
93
|
+
cur.new.update(range(c, c + d))
|
|
94
|
+
elif in_hunks:
|
|
95
|
+
continue
|
|
96
|
+
elif line.startswith("new file mode") and cur is not None:
|
|
97
|
+
cur.status = "added"
|
|
98
|
+
elif line.startswith("deleted file mode") and cur is not None:
|
|
99
|
+
cur.status = "deleted"
|
|
100
|
+
elif line.startswith("--- "):
|
|
101
|
+
old_path = _side(line[4:])
|
|
102
|
+
elif line.startswith("+++ "):
|
|
103
|
+
new_path = _side(line[4:])
|
|
104
|
+
path = new_path or old_path
|
|
105
|
+
if path and (cur is None or cur.path != path): # a header we could not read
|
|
106
|
+
status = "added" if old_path is None else "deleted" if new_path is None else "modified"
|
|
107
|
+
cur = out.setdefault(path, FileDiff(path, status))
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _key(s: Symbol) -> tuple:
|
|
112
|
+
return (s.kind, " ".join(s.signature.split()), tuple(s.attrs), bool(s.exported))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _by_qualname(info: FileInfo | None) -> dict[str, list]:
|
|
116
|
+
out: dict[str, list] = defaultdict(list)
|
|
117
|
+
if info is not None:
|
|
118
|
+
for s in info.symbols:
|
|
119
|
+
if s.kind != "namespace":
|
|
120
|
+
out[s.qualname].append(s)
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _touched(info: FileInfo | None, lines: set[int], text: list[str] | None) -> set[str]:
|
|
125
|
+
"""Qualified names of the innermost declarations around ``lines`` ("" = outside any).
|
|
126
|
+
Blank lines don't count: adding a method brings a blank line that belongs to no one."""
|
|
127
|
+
from .navigate import enclosing_symbol
|
|
128
|
+
|
|
129
|
+
out: set[str] = set()
|
|
130
|
+
if info is None:
|
|
131
|
+
return out
|
|
132
|
+
for n in lines:
|
|
133
|
+
if text is not None and (n > len(text) or not text[n - 1].strip()):
|
|
134
|
+
continue
|
|
135
|
+
s = enclosing_symbol(info, n)
|
|
136
|
+
out.add(s.qualname if s is not None else "")
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def classify(old_info: FileInfo | None, new_info: FileInfo | None, diff: FileDiff, old_text: list[str] | None = None,
|
|
141
|
+
new_text: list[str] | None = None) -> tuple[list[dict], bool, bool]:
|
|
142
|
+
"""(changed symbols, header changed, lines outside any declaration changed) for one file.
|
|
143
|
+
Symbols come in new-file order, removed ones after, each ``{"qualname", "kind", "change",
|
|
144
|
+
"signature", "old_signature", "start", "end", "exported"}`` with ``change`` in
|
|
145
|
+
added | removed | signature | body."""
|
|
146
|
+
old, new = _by_qualname(old_info), _by_qualname(new_info)
|
|
147
|
+
touched = _touched(old_info, diff.old, old_text) | _touched(new_info, diff.new, new_text)
|
|
148
|
+
out: list[dict] = []
|
|
149
|
+
for q, syms in new.items():
|
|
150
|
+
s = syms[0]
|
|
151
|
+
item = {"qualname": q, "kind": s.kind, "signature": s.signature, "old_signature": None, "start": s.start,
|
|
152
|
+
"end": s.end, "exported": bool(s.exported)}
|
|
153
|
+
if q not in old:
|
|
154
|
+
out.append({**item, "change": "added"})
|
|
155
|
+
elif sorted(map(_key, syms)) != sorted(map(_key, old[q])):
|
|
156
|
+
out.append({**item, "change": "signature", "old_signature": old[q][0].signature})
|
|
157
|
+
elif q in touched:
|
|
158
|
+
out.append({**item, "change": "body"})
|
|
159
|
+
for q, syms in old.items():
|
|
160
|
+
if q not in new:
|
|
161
|
+
s = syms[0]
|
|
162
|
+
out.append({"qualname": q, "kind": s.kind, "signature": None, "old_signature": s.signature,
|
|
163
|
+
"start": s.start, "end": s.end, "exported": bool(s.exported), "change": "removed"})
|
|
164
|
+
header = bool(old_info is not None and new_info is not None and
|
|
165
|
+
[h.strip() for h in old_info.header] != [h.strip() for h in new_info.header])
|
|
166
|
+
return out, header, "" in touched
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
INTERFACE = ("added", "removed", "signature")
|
topomark/cli.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""argparse dispatch, global flags and exit codes for the ``topomark`` CLI.
|
|
2
|
+
|
|
3
|
+
Conventions
|
|
4
|
+
-----------
|
|
5
|
+
* **stdout = data, stderr = logs.** ``--json`` prints exactly one JSON object on
|
|
6
|
+
stdout, stamped with ``schema_version`` and ``command``; failures under ``--json``
|
|
7
|
+
still print an error envelope on stdout.
|
|
8
|
+
* Global flags (``--json -C/--repo --config -q -v --debug``) are accepted before
|
|
9
|
+
or after the subcommand.
|
|
10
|
+
* Each command family is one module in ``topomark.commands`` exposing
|
|
11
|
+
``register(sub, common)``; handlers take ``(args, ctx)`` and return a
|
|
12
|
+
``Result``. Heavy imports happen inside handlers so ``--help`` stays fast.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
from typing import NoReturn
|
|
22
|
+
|
|
23
|
+
from . import __version__
|
|
24
|
+
from .commands import COMMAND_MODULES, Result, command_module
|
|
25
|
+
from .contract import SCHEMA_VERSION
|
|
26
|
+
from .errors import EXIT, TopomarkError
|
|
27
|
+
|
|
28
|
+
_GLOBAL_DEFAULTS = {"repo": None, "config": None, "verbose": 0, "quiet": False, "json": False, "debug": False}
|
|
29
|
+
_JSON_REQUESTED = False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _emit_json(payload: dict) -> None:
|
|
33
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False, allow_nan=False) + "\n")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _discard_stdout() -> None:
|
|
37
|
+
"""Point stdout at the null device, so the interpreter's flush at exit does not fail again."""
|
|
38
|
+
try:
|
|
39
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
40
|
+
except (OSError, ValueError):
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _error_payload(code: str, message: str, exit_code: int, remediation: str) -> dict:
|
|
45
|
+
return {
|
|
46
|
+
"schema_version": SCHEMA_VERSION,
|
|
47
|
+
"topomark_version": __version__,
|
|
48
|
+
"error": {"code": code, "message": message, "exit": exit_code, "remediation": remediation},
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _Parser(argparse.ArgumentParser):
|
|
53
|
+
"""ArgumentParser whose usage errors stay machine-readable under ``--json``."""
|
|
54
|
+
|
|
55
|
+
def error(self, message: str) -> NoReturn:
|
|
56
|
+
if _JSON_REQUESTED:
|
|
57
|
+
_emit_json(_error_payload("USAGE", f"{self.prog}: {message}", EXIT["USAGE"],
|
|
58
|
+
"Run `topomark <command> --help` for the accepted arguments."))
|
|
59
|
+
raise SystemExit(EXIT["USAGE"])
|
|
60
|
+
self.print_usage(sys.stderr)
|
|
61
|
+
self.exit(EXIT["USAGE"], f"{self.prog}: error: {message}\n")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _global_flags() -> argparse.ArgumentParser:
|
|
65
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
66
|
+
common.add_argument("-C", "--repo", metavar="DIR", default=argparse.SUPPRESS,
|
|
67
|
+
help="run as if started in DIR (like git -C)")
|
|
68
|
+
common.add_argument("--config", metavar="PATH", default=argparse.SUPPRESS,
|
|
69
|
+
help="path to topomark.toml (default: <repo root>/topomark.toml)")
|
|
70
|
+
common.add_argument("-v", "--verbose", action="count", default=argparse.SUPPRESS,
|
|
71
|
+
help="more detail on stderr (-v, -vv)")
|
|
72
|
+
common.add_argument("-q", "--quiet", action="store_true", default=argparse.SUPPRESS,
|
|
73
|
+
help="suppress non-error logs")
|
|
74
|
+
common.add_argument("--json", action="store_true", default=argparse.SUPPRESS,
|
|
75
|
+
help="print one machine-readable JSON object on stdout")
|
|
76
|
+
common.add_argument("--debug", action="store_true", default=argparse.SUPPRESS,
|
|
77
|
+
help="show full tracebacks for internal errors")
|
|
78
|
+
return common
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_VALUE_FLAGS = ("-C", "--repo", "--config")
|
|
82
|
+
_BARE_FLAGS = frozenset({"--json", "--debug", "--quiet", "--verbose", "--version"})
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _command_in(argv: list[str]) -> str | None:
|
|
86
|
+
"""The command word in ``argv`` when only spelled-out global flags precede it, else None.
|
|
87
|
+
|
|
88
|
+
None means "build the whole parser": help before the command, an abbreviated or unknown flag,
|
|
89
|
+
``--``, or no command at all. A wrong guess here could only cost time, never change parsing,
|
|
90
|
+
because ``build_parser`` falls back to every command when the word is not one it registered."""
|
|
91
|
+
i = 0
|
|
92
|
+
while i < len(argv):
|
|
93
|
+
token = argv[i]
|
|
94
|
+
if not token.startswith("-"):
|
|
95
|
+
return token
|
|
96
|
+
if token in _VALUE_FLAGS:
|
|
97
|
+
i += 2
|
|
98
|
+
elif token in _BARE_FLAGS or token.startswith(("--repo=", "--config=")) or (
|
|
99
|
+
token.startswith("-C") and len(token) > 2) or (token[1:] and set(token[1:]) <= {"v", "q"}):
|
|
100
|
+
i += 1
|
|
101
|
+
else:
|
|
102
|
+
return None
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def build_parser(only: str | None = None) -> argparse.ArgumentParser:
|
|
107
|
+
"""The whole parser, or with ``only`` the parser for that one command (same parse, fewer imports)."""
|
|
108
|
+
common = _global_flags()
|
|
109
|
+
parser = _Parser(
|
|
110
|
+
prog="topomark",
|
|
111
|
+
description="A zero-dependency code map for AI coding agents: progressive-disclosure "
|
|
112
|
+
"docs, per-file review stamps that catch stale summaries, and fast "
|
|
113
|
+
"symbol / impact / test navigation.",
|
|
114
|
+
epilog=(
|
|
115
|
+
"typical workflow:\n"
|
|
116
|
+
" topomark init --dry-run # see what topomark would set up\n"
|
|
117
|
+
" topomark outline src/big_file.py # symbols with line ranges\n"
|
|
118
|
+
" topomark symbol src/big_file.py#Foo # print just that symbol\n"
|
|
119
|
+
" topomark impact Foo # callers, tests, docs that mention it\n"
|
|
120
|
+
" topomark tests-for --diff # the tests your change needs\n"
|
|
121
|
+
" topomark check # code map in sync with the code?\n"
|
|
122
|
+
),
|
|
123
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
124
|
+
parents=[common],
|
|
125
|
+
)
|
|
126
|
+
parser.add_argument("--version", action="store_true", help="print the version and exit")
|
|
127
|
+
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
|
128
|
+
module = command_module(only) if only else None
|
|
129
|
+
if module is not None:
|
|
130
|
+
module.register(sub, common)
|
|
131
|
+
if only in sub.choices:
|
|
132
|
+
return parser
|
|
133
|
+
return build_parser() # the module registers another name: let argparse report all choices
|
|
134
|
+
for module in COMMAND_MODULES():
|
|
135
|
+
module.register(sub, common)
|
|
136
|
+
return parser
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _configure_streams() -> None:
|
|
140
|
+
for stream in (sys.stdout, sys.stderr):
|
|
141
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
142
|
+
if reconfigure is not None:
|
|
143
|
+
try:
|
|
144
|
+
reconfigure(encoding="utf-8", errors="replace", newline="\n")
|
|
145
|
+
except (ValueError, OSError):
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def main(argv: list[str] | None = None) -> int:
|
|
150
|
+
global _JSON_REQUESTED
|
|
151
|
+
_configure_streams()
|
|
152
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
153
|
+
_JSON_REQUESTED = "--json" in argv
|
|
154
|
+
parser = build_parser(_command_in(argv))
|
|
155
|
+
args = parser.parse_args(argv)
|
|
156
|
+
for key, value in _GLOBAL_DEFAULTS.items():
|
|
157
|
+
if not hasattr(args, key):
|
|
158
|
+
setattr(args, key, value)
|
|
159
|
+
if args.version:
|
|
160
|
+
if args.json:
|
|
161
|
+
_emit_json({"schema_version": SCHEMA_VERSION, "command": "version", "topomark_version": __version__})
|
|
162
|
+
else:
|
|
163
|
+
print(f"topomark {__version__}")
|
|
164
|
+
return EXIT["OK"]
|
|
165
|
+
handler = getattr(args, "handler", None)
|
|
166
|
+
if handler is None:
|
|
167
|
+
if args.json:
|
|
168
|
+
_emit_json(_error_payload("USAGE", "topomark: no command given", EXIT["USAGE"],
|
|
169
|
+
"Run `topomark --help` for the commands."))
|
|
170
|
+
else:
|
|
171
|
+
parser.print_help(sys.stderr)
|
|
172
|
+
return EXIT["USAGE"]
|
|
173
|
+
|
|
174
|
+
from .context import Context
|
|
175
|
+
|
|
176
|
+
try:
|
|
177
|
+
result: Result = handler(args, Context(args))
|
|
178
|
+
except TopomarkError as e:
|
|
179
|
+
if args.json:
|
|
180
|
+
_emit_json(_error_payload(e.code, e.message, e.exit, e.remediation))
|
|
181
|
+
else:
|
|
182
|
+
sys.stderr.write(f"error: {e.code}: {e.message}\nhint: {e.remediation}\n")
|
|
183
|
+
return e.exit
|
|
184
|
+
except KeyboardInterrupt:
|
|
185
|
+
return 130
|
|
186
|
+
except Exception as e: # the CLI boundary turns bugs into exit 7
|
|
187
|
+
if args.debug:
|
|
188
|
+
raise
|
|
189
|
+
message = f"{type(e).__name__}: {e}"
|
|
190
|
+
if args.json:
|
|
191
|
+
_emit_json(_error_payload("INTERNAL", message, EXIT["INTERNAL"],
|
|
192
|
+
"This is a topomark bug. Rerun with --debug and report the traceback."))
|
|
193
|
+
else:
|
|
194
|
+
sys.stderr.write(f"error: INTERNAL: {message}\nhint: rerun with --debug for the traceback\n")
|
|
195
|
+
if args.verbose:
|
|
196
|
+
import traceback # not at the top: it costs every hook call ~20 ms of imports
|
|
197
|
+
|
|
198
|
+
traceback.print_exc()
|
|
199
|
+
return EXIT["INTERNAL"]
|
|
200
|
+
|
|
201
|
+
try:
|
|
202
|
+
if args.json:
|
|
203
|
+
_emit_json({"schema_version": SCHEMA_VERSION, "command": args.command, **result.data})
|
|
204
|
+
elif result.text:
|
|
205
|
+
sys.stdout.write(result.text if result.text.endswith("\n") else result.text + "\n")
|
|
206
|
+
sys.stdout.flush()
|
|
207
|
+
except BrokenPipeError: # the reader left (`| head`): not an error, and nothing more to say
|
|
208
|
+
_discard_stdout()
|
|
209
|
+
return result.exit
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Command modules. Each exposes ``register(sub, common)`` and a handler
|
|
2
|
+
``run(args, ctx) -> Result``. ``COMMAND_MODULES`` is the registry the parser and
|
|
3
|
+
``capabilities`` both read, so a command can't exist without being described."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from types import ModuleType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
# Order here is the order in `topomark --help`.
|
|
12
|
+
_NAMES = [
|
|
13
|
+
"init", "doctor", "capabilities",
|
|
14
|
+
"gen", "check", "sync", "stamp", "diff", "stale", "owner", "draft", "hook", "agent_hook",
|
|
15
|
+
"outline", "symbol", "find", "search", "locate", "refs", "impact", "brief", "tests_for", "changes", "syntax", "map",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Result:
|
|
21
|
+
"""What a handler returns: ``data`` for --json, ``text`` for humans, ``exit`` code."""
|
|
22
|
+
|
|
23
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
24
|
+
text: str = ""
|
|
25
|
+
exit: int = 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def command_module(cli_name: str) -> ModuleType | None:
|
|
29
|
+
"""The one module behind a command as typed (``tests-for`` → ``tests_for``), or None.
|
|
30
|
+
|
|
31
|
+
Importing all of ``COMMAND_MODULES`` costs every call about 45 ms; a plugin hook runs on every
|
|
32
|
+
Read and Edit, so the CLI loads only the command it was given."""
|
|
33
|
+
name = cli_name.replace("-", "_")
|
|
34
|
+
if "_" in cli_name or name not in _NAMES:
|
|
35
|
+
return None
|
|
36
|
+
import importlib
|
|
37
|
+
|
|
38
|
+
return importlib.import_module(f"{__name__}.{name}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def COMMAND_MODULES() -> list[ModuleType]: # noqa: N802 - reads like a constant at call sites
|
|
42
|
+
# Written out (not computed from _NAMES) so `impact` and `tests-for` see who loads each command;
|
|
43
|
+
# tests/test_meta.py checks this list against _NAMES. Inside the function: the modules import Result.
|
|
44
|
+
from . import (
|
|
45
|
+
agent_hook, brief, capabilities, changes, check, diff, doctor, draft, find, gen, hook, impact, init, locate,
|
|
46
|
+
map, outline, owner, refs, search, stale, stamp, symbol, sync, syntax, tests_for,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
return [
|
|
50
|
+
init, doctor, capabilities,
|
|
51
|
+
gen, check, sync, stamp, diff, stale, owner, draft, hook, agent_hook,
|
|
52
|
+
outline, symbol, find, search, locate, refs, impact, brief, tests_for, changes, syntax, map,
|
|
53
|
+
]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Helpers shared by command modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING: # importing workspace pulls in the index and hashlib: too slow for --help and hooks
|
|
9
|
+
from ..workspace import Problem
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def add(sub: Any, common: argparse.ArgumentParser, name: str, help_text: str, description: str = "",
|
|
13
|
+
epilog: str = "") -> argparse.ArgumentParser:
|
|
14
|
+
p = sub.add_parser(name, parents=[common], help=help_text, description=description or help_text,
|
|
15
|
+
epilog=epilog or None, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
16
|
+
return p
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def format_problems(problems: list[Problem]) -> str:
|
|
20
|
+
return "\n".join(f"FAIL {p.code:<15} {p.file}: {p.message}" for p in problems)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def rel(ctx: Any, raw: str) -> str:
|
|
24
|
+
"""A user-supplied path → repo-relative POSIX path (``repo.user_path``)."""
|
|
25
|
+
from ..repo import user_path
|
|
26
|
+
|
|
27
|
+
return user_path(ctx.root, raw)
|