ramani 0.1.0a1__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.

Potentially problematic release.


This version of ramani might be problematic. Click here for more details.

ramani/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ # ramani: src/ramani/__init__.py
2
+ """ramani (Swahili for "map"): keep a path comment at the top of every source file."""
3
+
4
+ from .cli import main
5
+ from .core import mark_text, run, strip_text
6
+
7
+ __all__ = ["main", "mark_text", "run", "strip_text"]
ramani/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ # ramani: src/ramani/__main__.py
2
+ """Allow ``python -m ramani``."""
3
+
4
+ from .cli import main
5
+
6
+ raise SystemExit(main())
ramani/cli.py ADDED
@@ -0,0 +1,183 @@
1
+ # ramani: src/ramani/cli.py
2
+ """Command-line interface."""
3
+
4
+ import argparse
5
+ import sys
6
+ from collections import Counter
7
+ from importlib.metadata import PackageNotFoundError, version
8
+ from pathlib import Path
9
+
10
+ from .config import IGNORE_DIRS, IGNORE_EXTS
11
+ from .core import Styles, run
12
+ from .settings import load_pyproject_styles, parse_style
13
+ from .tree import build_tree, copy_to_clipboard
14
+
15
+ CHANGED = {"added", "updated", "removed"}
16
+ HIDDEN = {"skipped", "unsupported"}
17
+
18
+ try:
19
+ VERSION = version("ramani")
20
+ except PackageNotFoundError:
21
+ VERSION = "unknown"
22
+
23
+
24
+ def _label(rel: str) -> str:
25
+ """Name a file type for the report: its extension, or the file name if it has none.
26
+
27
+ Examples::
28
+
29
+ _label("src/data.xyz") # ".xyz"
30
+ _label("bin/runner") # "runner"
31
+ """
32
+ path = Path(rel)
33
+ return path.suffix.lower() or path.name
34
+
35
+
36
+ def _norm_ext(ext: str) -> str:
37
+ """Lower-case an extension and make sure it starts with a dot.
38
+
39
+ Examples::
40
+
41
+ _norm_ext("MD") # ".md"
42
+ """
43
+ ext = ext.lower()
44
+ return ext if ext.startswith(".") else "." + ext
45
+
46
+
47
+ def _parser() -> argparse.ArgumentParser:
48
+ """Build the argument parser."""
49
+ p = argparse.ArgumentParser(
50
+ prog="ramani",
51
+ description="Keep a path comment at the top of every source file, refreshed when files move.",
52
+ )
53
+ p.add_argument("-V", "--version", action="version", version=f"%(prog)s {VERSION}")
54
+ p.add_argument(
55
+ "path",
56
+ nargs="?",
57
+ default=".",
58
+ type=Path,
59
+ help="folder or file (default: current folder)",
60
+ )
61
+ p.add_argument(
62
+ "-e",
63
+ "--ignore-ext",
64
+ action="append",
65
+ default=[],
66
+ metavar="EXT",
67
+ help="extra extension to skip, e.g. -e .txt (repeatable)",
68
+ )
69
+ p.add_argument(
70
+ "-d",
71
+ "--ignore-dir",
72
+ action="append",
73
+ default=[],
74
+ metavar="NAME",
75
+ help="extra folder name or glob to skip (repeatable)",
76
+ )
77
+ p.add_argument(
78
+ "-c",
79
+ "--comment",
80
+ action="append",
81
+ default=[],
82
+ metavar="EXT=START[,END]",
83
+ help="comment style for an extension, e.g. -c .abc=// or -c .tpl='<!--,-->' (repeatable)",
84
+ )
85
+ p.add_argument(
86
+ "--no-gitignore", action="store_true", help="don't read .gitignore files"
87
+ )
88
+ p.add_argument(
89
+ "--remove",
90
+ action="store_true",
91
+ help="strip ramani comments instead of adding them",
92
+ )
93
+ p.add_argument(
94
+ "-n",
95
+ "--dry-run",
96
+ action="store_true",
97
+ help="show what would change without writing",
98
+ )
99
+ p.add_argument(
100
+ "--check",
101
+ action="store_true",
102
+ help="dry run that exits 1 if any file needs changes",
103
+ )
104
+ p.add_argument(
105
+ "-v", "--verbose", action="store_true", help="also list unchanged files"
106
+ )
107
+ p.add_argument(
108
+ "-t",
109
+ "--tree",
110
+ action="store_true",
111
+ help="print the folder structure as a tree instead of marking files (same ignores)",
112
+ )
113
+ p.add_argument(
114
+ "--copy",
115
+ action="store_true",
116
+ help="copy the tree to the clipboard (implies --tree)",
117
+ )
118
+ return p
119
+
120
+
121
+ def main(argv: list[str] | None = None) -> int:
122
+ """Run the CLI and return the exit code."""
123
+ parser = _parser()
124
+ args = parser.parse_args(argv)
125
+ if not args.path.exists():
126
+ parser.error(f"path not found: {args.path}")
127
+
128
+ ignore_dirs = (*IGNORE_DIRS, *args.ignore_dir)
129
+ ignore_exts = (*IGNORE_EXTS, *map(_norm_ext, args.ignore_ext))
130
+
131
+ if args.tree or args.copy:
132
+ if args.remove or args.check:
133
+ parser.error("--tree/--copy can't be combined with --remove or --check")
134
+ tree = build_tree(args.path, ignore_dirs, ignore_exts, not args.no_gitignore)
135
+ print(tree)
136
+ if args.copy:
137
+ try:
138
+ copy_to_clipboard(tree)
139
+ except RuntimeError as err:
140
+ print(f"ramani: could not copy to clipboard: {err}", file=sys.stderr)
141
+ return 1
142
+ print("(copied to clipboard)", file=sys.stderr)
143
+ return 0
144
+
145
+ root = args.path if args.path.is_dir() else args.path.parent
146
+ styles: Styles = {}
147
+ for folder in dict.fromkeys([Path.cwd(), root.resolve()]):
148
+ styles.update(load_pyproject_styles(folder))
149
+ try:
150
+ styles.update(parse_style(spec) for spec in args.comment)
151
+ except ValueError as err:
152
+ parser.error(str(err))
153
+
154
+ dry_run = args.dry_run or args.check
155
+ results = run(
156
+ args.path,
157
+ remove=args.remove,
158
+ dry_run=dry_run,
159
+ ignore_dirs=ignore_dirs,
160
+ ignore_exts=ignore_exts,
161
+ use_gitignore=not args.no_gitignore,
162
+ styles=styles,
163
+ )
164
+
165
+ for rel, status in results:
166
+ if status in CHANGED or (args.verbose and status not in HIDDEN):
167
+ print(f"{status:<9} {rel}")
168
+
169
+ counts = Counter(status for _, status in results)
170
+ summary = (
171
+ ", ".join(f"{n} {status}" for status, n in sorted(counts.items()))
172
+ or "no files found"
173
+ )
174
+ print(("(dry run) " if dry_run else "") + summary)
175
+
176
+ unknown = Counter(_label(rel) for rel, status in results if status == "unsupported")
177
+ if unknown:
178
+ listed = ", ".join(f"{label} x{n}" for label, n in sorted(unknown.items()))
179
+ print(f"no comment style for: {listed}")
180
+ print(
181
+ " add one with -c EXT=START[,END] or [tool.ramani.comments] in pyproject.toml"
182
+ )
183
+ return 1 if args.check and CHANGED & counts.keys() else 0
ramani/config.py ADDED
@@ -0,0 +1,108 @@
1
+ # ramani: src/ramani/config.py
2
+ """Defaults: comment styles and ignore lists."""
3
+
4
+ MARKER = "ramani:"
5
+
6
+ _HASH = (
7
+ ".py",
8
+ ".pyi",
9
+ ".sh",
10
+ ".bash",
11
+ ".zsh",
12
+ ".rb",
13
+ ".pl",
14
+ ".r",
15
+ ".jl",
16
+ ".ex",
17
+ ".exs",
18
+ ".yml",
19
+ ".yaml",
20
+ ".toml",
21
+ ".cfg",
22
+ ".conf",
23
+ ".tf",
24
+ ".ps1",
25
+ ".mk",
26
+ ".nix",
27
+ ".graphql",
28
+ )
29
+ _SLASH = (
30
+ ".js",
31
+ ".mjs",
32
+ ".cjs",
33
+ ".jsx",
34
+ ".ts",
35
+ ".tsx",
36
+ ".java",
37
+ ".kt",
38
+ ".kts",
39
+ ".scala",
40
+ ".c",
41
+ ".h",
42
+ ".cc",
43
+ ".cpp",
44
+ ".hpp",
45
+ ".cs",
46
+ ".go",
47
+ ".rs",
48
+ ".swift",
49
+ ".dart",
50
+ ".scss",
51
+ ".less",
52
+ ".proto",
53
+ ".sol",
54
+ ".zig",
55
+ )
56
+ _DASH = (".sql", ".lua", ".hs", ".elm")
57
+ _HTML = (".html", ".htm", ".xml", ".svg", ".vue", ".svelte", ".md", ".markdown")
58
+ _JINJA = (".j2", ".jinja", ".jinja2")
59
+
60
+ # extension -> (comment start, comment end); end is "" for line comments
61
+ COMMENT_STYLES: dict[str, tuple[str, str]] = {
62
+ **dict.fromkeys(_HASH, ("#", "")),
63
+ **dict.fromkeys(_SLASH, ("//", "")),
64
+ **dict.fromkeys(_DASH, ("--", "")),
65
+ **dict.fromkeys(_HTML, ("<!--", "-->")),
66
+ **dict.fromkeys(_JINJA, ("{#", "#}")),
67
+ ".css": ("/*", "*/"),
68
+ ".tex": ("%", ""),
69
+ ".mdx": ("{/*", "*/}"), # MDX 2+ has no HTML comments
70
+ }
71
+
72
+ # Markdown files may open with a front matter block (--- ... --- or +++ ... +++) that must stay first
73
+ FRONT_MATTER_EXTS = (".md", ".markdown", ".mdx")
74
+
75
+ # files with no useful extension, matched by exact name
76
+ NAME_STYLES: dict[str, tuple[str, str]] = {
77
+ "Dockerfile": ("#", ""),
78
+ "Makefile": ("#", ""),
79
+ ".gitignore": ("#", ""),
80
+ ".dockerignore": ("#", ""),
81
+ ".editorconfig": ("#", ""),
82
+ }
83
+
84
+ # first lines that must stay first (shebang, encoding, XML declaration, Dockerfile directives)
85
+ KEEP_FIRST = ("#!", "# -*-", "# coding", "<?xml", "# syntax=", "# escape=")
86
+
87
+ # folder names (globs allowed) and file endings skipped by default
88
+ IGNORE_DIRS = (
89
+ ".git",
90
+ ".hg",
91
+ ".svn",
92
+ "__pycache__",
93
+ "node_modules",
94
+ ".venv",
95
+ "venv",
96
+ ".tox",
97
+ ".nox",
98
+ ".mypy_cache",
99
+ ".pytest_cache",
100
+ ".ruff_cache",
101
+ ".idea",
102
+ ".vscode",
103
+ "dist",
104
+ "build",
105
+ ".next",
106
+ "*.egg-info",
107
+ )
108
+ IGNORE_EXTS = (".pyc", ".pyo", ".min.js", ".min.css", ".map", ".lock", ".log")
ramani/core.py ADDED
@@ -0,0 +1,273 @@
1
+ # ramani: src/ramani/core.py
2
+ """Add, refresh and strip path comments."""
3
+
4
+ import re
5
+ from collections.abc import Iterator
6
+ from fnmatch import fnmatch
7
+ from pathlib import Path
8
+
9
+ from .config import (
10
+ COMMENT_STYLES,
11
+ FRONT_MATTER_EXTS,
12
+ IGNORE_DIRS,
13
+ IGNORE_EXTS,
14
+ KEEP_FIRST,
15
+ MARKER,
16
+ NAME_STYLES,
17
+ )
18
+ from .gitignore import Rule, is_gitignored, parse_gitignore
19
+
20
+ Styles = dict[str, tuple[str, str]]
21
+
22
+
23
+ def style_for(path: Path, extra: Styles | None = None) -> tuple[str, str] | None:
24
+ """Return the (start, end) comment style for a file, or None if unsupported.
25
+
26
+ ``extra`` maps extensions or file names to styles and beats the built-ins.
27
+
28
+ Examples::
29
+
30
+ style_for(Path("app.py")) # ("#", "")
31
+ style_for(Path("logo.png")) # None
32
+ style_for(Path("a.abc"), {".abc": ("//", "")}) # ("//", "")
33
+ """
34
+ extra = extra or {}
35
+ suffix = path.suffix.lower()
36
+ return (
37
+ extra.get(path.name)
38
+ or extra.get(suffix)
39
+ or NAME_STYLES.get(path.name)
40
+ or COMMENT_STYLES.get(suffix)
41
+ )
42
+
43
+
44
+ def make_comment(rel: str, start: str, end: str = "") -> str:
45
+ """Build the marker comment for a relative path.
46
+
47
+ Examples::
48
+
49
+ make_comment("src/a.py", "#") # "# ramani: src/a.py"
50
+ make_comment("a.html", "<!--", "-->") # "<!-- ramani: a.html -->"
51
+ """
52
+ return f"{start} {MARKER} {rel}" + (f" {end}" if end else "")
53
+
54
+
55
+ def _mark_re(start: str, end: str) -> "re.Pattern[str]":
56
+ """Regex matching a marker comment; the stored path is the ``rel`` group."""
57
+ tail = rf"\s*{re.escape(end)}" if end else ""
58
+ return re.compile(
59
+ rf"^\s*{re.escape(start)}\s*{re.escape(MARKER)}\s*(?P<rel>.*?){tail}\s*$"
60
+ )
61
+
62
+
63
+ def _preamble(lines: list[str], front_matter: bool = False) -> int:
64
+ """Count leading lines the comment must come after (shebang, encoding, XML declaration, front matter).
65
+
66
+ Examples::
67
+
68
+ _preamble(["#!/bin/sh", "echo hi"]) # 1
69
+ _preamble(["import os"]) # 0
70
+ _preamble(["---\n", "title: A\n", "---\n", "# Hi\n"], front_matter=True) # 3
71
+ """
72
+ n = 0
73
+ if front_matter and lines and (fence := lines[0].rstrip()) in ("---", "+++"):
74
+ closers = (fence, "...") if fence == "---" else (fence,)
75
+ for j in range(1, len(lines)):
76
+ if lines[j].rstrip() in closers:
77
+ n = j + 1
78
+ break
79
+ while n < len(lines) and lines[n].startswith(KEEP_FIRST):
80
+ n += 1
81
+ return n
82
+
83
+
84
+ def mark_text(
85
+ text: str, rel: str, start: str, end: str = "", front_matter: bool = False
86
+ ) -> tuple[str, str]:
87
+ r"""Add or refresh the path comment; returns (new_text, status).
88
+
89
+ Status is "added", "updated" (path changed) or "unchanged".
90
+
91
+ Examples::
92
+
93
+ mark_text("x = 1\n", "a/b.py", "#") # ("# ramani: a/b.py\nx = 1\n", "added")
94
+ mark_text("# ramani: old.py\nx = 1\n", "new.py", "#") # ("# ramani: new.py\nx = 1\n", "updated")
95
+ """
96
+ lines = text.splitlines(keepends=True)
97
+ eol = "\r\n" if "\r\n" in text else "\n"
98
+ i = _preamble(lines, front_matter)
99
+ comment = make_comment(rel, start, end)
100
+
101
+ line = lines[i] if i < len(lines) else ""
102
+ bare = line.rstrip("\r\n")
103
+ found = _mark_re(start, end).match(bare)
104
+ if found:
105
+ if found["rel"] == rel:
106
+ return text, "unchanged"
107
+ lines[i] = comment + line[len(bare) :]
108
+ return "".join(lines), "updated"
109
+
110
+ if i and not lines[i - 1].endswith(("\n", "\r")):
111
+ lines[i - 1] += eol
112
+ lines.insert(i, comment + eol)
113
+ return "".join(lines), "added"
114
+
115
+
116
+ def strip_text(
117
+ text: str, start: str, end: str = "", front_matter: bool = False
118
+ ) -> tuple[str, bool]:
119
+ r"""Remove the path comment if present; returns (new_text, removed).
120
+
121
+ Examples::
122
+
123
+ strip_text("# ramani: a.py\nx = 1\n", "#") # ("x = 1\n", True)
124
+ strip_text("x = 1\n", "#") # ("x = 1\n", False)
125
+ """
126
+ lines = text.splitlines(keepends=True)
127
+ i = _preamble(lines, front_matter)
128
+ if i < len(lines) and _mark_re(start, end).match(lines[i].rstrip("\r\n")):
129
+ del lines[i]
130
+ return "".join(lines), True
131
+ return text, False
132
+
133
+
134
+ GitStack = list[tuple[Path, list[Rule]]]
135
+
136
+
137
+ def visible_children(
138
+ directory: Path,
139
+ stack: GitStack,
140
+ ignore_dirs: tuple[str, ...] = IGNORE_DIRS,
141
+ ignore_exts: tuple[str, ...] = IGNORE_EXTS,
142
+ use_gitignore: bool = True,
143
+ ) -> tuple[list[tuple[Path, bool]], GitStack]:
144
+ """List a folder's non-ignored entries as (path, is_dir), folders first, plus the updated .gitignore stack.
145
+
146
+ Examples::
147
+
148
+ visible_children(Path("."), []) # ([(Path("src"), True), (Path("README.md"), False)], [...])
149
+ """
150
+ gitignore = directory / ".gitignore"
151
+ if use_gitignore and gitignore.is_file():
152
+ rules = parse_gitignore(gitignore.read_text(encoding="utf-8", errors="ignore"))
153
+ stack = [*stack, (directory, rules)]
154
+ try:
155
+ entries = sorted(directory.iterdir(), key=lambda p: p.name)
156
+ except PermissionError:
157
+ return [], stack
158
+ exts = tuple(e.lower() for e in ignore_exts)
159
+ kept = []
160
+ for entry in entries:
161
+ if entry.is_symlink():
162
+ continue
163
+ is_dir = entry.is_dir()
164
+ if is_dir and any(fnmatch(entry.name, pattern) for pattern in ignore_dirs):
165
+ continue
166
+ if not is_dir and entry.name.lower().endswith(exts):
167
+ continue
168
+ if use_gitignore and is_gitignored(entry, is_dir, stack):
169
+ continue
170
+ kept.append((entry, is_dir))
171
+ kept.sort(key=lambda item: not item[1])
172
+ return kept, stack
173
+
174
+
175
+ def iter_files(
176
+ root: Path,
177
+ ignore_dirs: tuple[str, ...] = IGNORE_DIRS,
178
+ ignore_exts: tuple[str, ...] = IGNORE_EXTS,
179
+ use_gitignore: bool = True,
180
+ ) -> Iterator[Path]:
181
+ """Yield files under ``root``, skipping ignored folders, extensions and symlinks.
182
+
183
+ Examples::
184
+
185
+ list(iter_files(Path("."))) # [PosixPath("src/app.py"), ...]
186
+ """
187
+
188
+ def walk(directory: Path, stack: GitStack) -> Iterator[Path]:
189
+ children, stack = visible_children(
190
+ directory, stack, ignore_dirs, ignore_exts, use_gitignore
191
+ )
192
+ for entry, is_dir in children:
193
+ if is_dir:
194
+ yield from walk(entry, stack)
195
+ else:
196
+ yield entry
197
+
198
+ yield from walk(root, [])
199
+
200
+
201
+ def process_file(
202
+ path: Path,
203
+ rel: str,
204
+ *,
205
+ remove: bool = False,
206
+ dry_run: bool = False,
207
+ styles: Styles | None = None,
208
+ ) -> str:
209
+ """Add, refresh or strip one file's comment; returns its status.
210
+
211
+ Status is "added", "updated", "removed", "unchanged", "unsupported" (no comment
212
+ style known) or "skipped" (unreadable, not UTF-8, or binary: contains NUL bytes).
213
+
214
+ Examples::
215
+
216
+ process_file(Path("app.py"), "app.py") # "added"
217
+ process_file(Path("data.xyz"), "data.xyz") # "unsupported"
218
+ process_file(Path("blob.py"), "blob.py") # "skipped" (has NUL bytes)
219
+ """
220
+ style = style_for(path, styles)
221
+ if style is None:
222
+ return "unsupported"
223
+ try:
224
+ raw = path.read_text(encoding="utf-8", newline="")
225
+ except (UnicodeDecodeError, OSError):
226
+ return "skipped"
227
+ if "\0" in raw:
228
+ return "skipped"
229
+
230
+ bom, text = ("", raw[1:]) if raw.startswith("") else ("", raw)
231
+ front = path.suffix.lower() in FRONT_MATTER_EXTS
232
+ if remove:
233
+ new, removed = strip_text(text, *style, front_matter=front)
234
+ status = "removed" if removed else "unchanged"
235
+ else:
236
+ new, status = mark_text(text, rel, *style, front_matter=front)
237
+
238
+ if new != text and not dry_run:
239
+ path.write_text(bom + new, encoding="utf-8", newline="")
240
+ return status
241
+
242
+
243
+ def run(
244
+ root: Path,
245
+ *,
246
+ remove: bool = False,
247
+ dry_run: bool = False,
248
+ ignore_dirs: tuple[str, ...] = IGNORE_DIRS,
249
+ ignore_exts: tuple[str, ...] = IGNORE_EXTS,
250
+ use_gitignore: bool = True,
251
+ styles: Styles | None = None,
252
+ ) -> list[tuple[str, str]]:
253
+ """Process every file under ``root``; returns (relative path, status) pairs.
254
+
255
+ Examples::
256
+
257
+ run(Path("."), dry_run=True) # [("src/app.py", "added"), ("data.xyz", "unsupported")]
258
+ """
259
+ root = root.resolve()
260
+ if root.is_file():
261
+ files, base = [root], root.parent
262
+ else:
263
+ files, base = iter_files(root, ignore_dirs, ignore_exts, use_gitignore), root
264
+ results = []
265
+ for file in files:
266
+ rel = file.relative_to(base).as_posix()
267
+ results.append(
268
+ (
269
+ rel,
270
+ process_file(file, rel, remove=remove, dry_run=dry_run, styles=styles),
271
+ )
272
+ )
273
+ return results
ramani/gitignore.py ADDED
@@ -0,0 +1,117 @@
1
+ # ramani: src/ramani/gitignore.py
2
+ """Minimal .gitignore parsing and matching."""
3
+
4
+ import re
5
+ from pathlib import Path
6
+
7
+ # (compiled regex, negated, dir_only)
8
+ type Rule = tuple["re.Pattern[str]", bool, bool]
9
+
10
+
11
+ def _glob_to_regex(pattern: str) -> str:
12
+ """Translate a gitignore glob into a regex body.
13
+
14
+ Examples::
15
+
16
+ _glob_to_regex("*.py") # "[^/]*\\.py"
17
+ _glob_to_regex("a/**/b") # "a/(?:.*/)?b"
18
+ _glob_to_regex("a/**b") # "a/[^/]*b" (** needs a slash or end on both sides)
19
+ _glob_to_regex("a**/b") # "a(?:.*/)?b" (git: first wildcard of a slashed pattern)
20
+ """
21
+ out: list[str] = []
22
+ i, n = 0, len(pattern)
23
+ while i < n:
24
+ c = pattern[i]
25
+ if c == "*":
26
+ stars = len(pattern[i:]) - len(pattern[i:].lstrip("*"))
27
+ after = pattern[i + stars : i + stars + 1]
28
+ # git quirk: besides after "/" or at the start, a ** that is the first wildcard
29
+ # of a pattern containing "/" is special too (so `a**/b` matches `a/x/b` and `ab`)
30
+ first_wildcard = "/" in pattern and not any(
31
+ ch in "*?[\\" for ch in pattern[:i]
32
+ )
33
+ if (
34
+ stars >= 2
35
+ and after in ("", "/")
36
+ and (i == 0 or pattern[i - 1] == "/" or first_wildcard)
37
+ ):
38
+ out.append("(?:.*/)?" if after else ".*")
39
+ i += stars + len(after)
40
+ continue
41
+ out.append("[^/]*")
42
+ i += stars
43
+ continue
44
+ elif c == "?":
45
+ out.append("[^/]")
46
+ elif c == "[" and (j := pattern.find("]", i + 2)) != -1:
47
+ body = pattern[i + 1 : j].replace("\\", "\\\\")
48
+ out.append("[" + ("^" + body[1:] if body.startswith("!") else body) + "]")
49
+ i = j
50
+ elif c == "\\" and i + 1 < n:
51
+ i += 1
52
+ out.append(re.escape(pattern[i]))
53
+ else:
54
+ out.append(re.escape(c))
55
+ i += 1
56
+ return "".join(out)
57
+
58
+
59
+ def parse_gitignore(text: str) -> list[Rule]:
60
+ """Parse .gitignore text into rules.
61
+
62
+ Examples::
63
+
64
+ len(parse_gitignore("*.log")) # 1
65
+ parse_gitignore("# note") # []
66
+ """
67
+ rules: list[Rule] = []
68
+ for raw in text.splitlines():
69
+ line = raw.rstrip()
70
+ if not line or line.startswith("#"):
71
+ continue
72
+ negated = line.startswith("!")
73
+ if negated:
74
+ line = line[1:]
75
+ dir_only = line.endswith("/")
76
+ line = line.rstrip("/")
77
+ if not line:
78
+ continue
79
+ anchored = "/" in line
80
+ line = line.lstrip("/")
81
+ prefix = "" if anchored else "(?:.*/)?"
82
+ rules.append(
83
+ (re.compile(f"^{prefix}{_glob_to_regex(line)}$"), negated, dir_only)
84
+ )
85
+ return rules
86
+
87
+
88
+ def match_rules(rel: str, is_dir: bool, rules: list[Rule]) -> bool | None:
89
+ """Last matching rule wins: True = ignored, False = re-included, None = no match.
90
+
91
+ Examples::
92
+
93
+ match_rules("a.log", False, parse_gitignore("*.log")) # True
94
+ match_rules("a.log", False, parse_gitignore("*.log\n!a.log")) # False
95
+ """
96
+ verdict = None
97
+ for regex, negated, dir_only in rules:
98
+ if (is_dir or not dir_only) and regex.match(rel):
99
+ verdict = not negated
100
+ return verdict
101
+
102
+
103
+ def is_gitignored(
104
+ path: Path, is_dir: bool, stack: list[tuple[Path, list[Rule]]]
105
+ ) -> bool:
106
+ """Check ``path`` against nested .gitignore rules, outermost first so inner files win.
107
+
108
+ Examples::
109
+
110
+ is_gitignored(Path("/p/a.log"), False, [(Path("/p"), parse_gitignore("*.log"))]) # True
111
+ """
112
+ verdict = False
113
+ for base, rules in stack:
114
+ result = match_rules(path.relative_to(base).as_posix(), is_dir, rules)
115
+ if result is not None:
116
+ verdict = result
117
+ return verdict
ramani/py.typed ADDED
File without changes
ramani/settings.py ADDED
@@ -0,0 +1,58 @@
1
+ # ramani: src/ramani/settings.py
2
+ """User-defined comment styles from ``--comment`` flags and ``[tool.ramani]``."""
3
+
4
+ import tomllib
5
+ from pathlib import Path
6
+
7
+ from .core import Styles
8
+
9
+
10
+ def parse_style(spec: str) -> tuple[str, tuple[str, str]]:
11
+ """Parse ``EXT=START`` or ``EXT=START,END`` into ``(key, (start, end))``.
12
+
13
+ Examples::
14
+
15
+ parse_style(".abc=//") # (".abc", ("//", ""))
16
+ parse_style("vue=<!--,-->") # (".vue", ("<!--", "-->"))
17
+ parse_style("Jenkinsfile=//") # ("Jenkinsfile", ("//", ""))
18
+ """
19
+ key, sep, value = spec.partition("=")
20
+ key, start = key.strip(), value.split(",", 1)[0].strip()
21
+ if not sep or not key or not start:
22
+ raise ValueError(f"expected EXT=START or EXT=START,END, got {spec!r}")
23
+ end = value.partition(",")[2].strip()
24
+ if "." not in key and key.islower():
25
+ key = "." + key
26
+ return (key.lower() if key.startswith(".") else key), (start, end)
27
+
28
+
29
+ def load_pyproject_styles(directory: Path) -> Styles:
30
+ """Read ``[tool.ramani.comments]`` from ``directory/pyproject.toml``.
31
+
32
+ Values are a start string or a ``[start, end]`` list.
33
+
34
+ Examples::
35
+
36
+ # [tool.ramani.comments]
37
+ # ".abc" = "//"
38
+ # ".tpl" = ["<!--", "-->"]
39
+ load_pyproject_styles(Path(".")) # {".abc": ("//", ""), ".tpl": ("<!--", "-->")}
40
+ """
41
+ file = directory / "pyproject.toml"
42
+ if not file.is_file():
43
+ return {}
44
+ try:
45
+ table = tomllib.loads(file.read_text(encoding="utf-8"))["tool"]["ramani"][
46
+ "comments"
47
+ ]
48
+ except (KeyError, tomllib.TOMLDecodeError):
49
+ return {}
50
+ styles: Styles = {}
51
+ for key, value in table.items():
52
+ start, end = (
53
+ (value, "")
54
+ if isinstance(value, str)
55
+ else (value[0], value[1] if len(value) > 1 else "")
56
+ )
57
+ styles[parse_style(f"{key}={start},{end}")[0]] = (start, end)
58
+ return styles
ramani/tree.py ADDED
@@ -0,0 +1,62 @@
1
+ # ramani: src/ramani/tree.py
2
+ """Render a folder as a text tree and copy text to the clipboard."""
3
+
4
+ from pathlib import Path
5
+
6
+ from .config import IGNORE_DIRS, IGNORE_EXTS
7
+ from .core import GitStack, visible_children
8
+
9
+
10
+ def build_tree(
11
+ root: Path,
12
+ ignore_dirs: tuple[str, ...] = IGNORE_DIRS,
13
+ ignore_exts: tuple[str, ...] = IGNORE_EXTS,
14
+ use_gitignore: bool = True,
15
+ ) -> str:
16
+ """Draw ``root`` and everything under it, honouring the same ignores as marking.
17
+
18
+ Examples::
19
+
20
+ build_tree(Path("proj"))
21
+ # proj/
22
+ # ├── src/
23
+ # │ └── app.py
24
+ # └── README.md
25
+ """
26
+ root = root.resolve()
27
+ if root.is_file():
28
+ return root.name
29
+
30
+ lines = [f"{root.name}/"]
31
+
32
+ def walk(directory: Path, stack: GitStack, prefix: str) -> None:
33
+ children, stack = visible_children(
34
+ directory, stack, ignore_dirs, ignore_exts, use_gitignore
35
+ )
36
+ for i, (entry, is_dir) in enumerate(children):
37
+ last = i == len(children) - 1
38
+ lines.append(
39
+ f"{prefix}{'└── ' if last else '├── '}{entry.name}{'/' if is_dir else ''}"
40
+ )
41
+ if is_dir:
42
+ walk(entry, stack, prefix + (" " if last else "│ "))
43
+
44
+ walk(root, [], "")
45
+ return "\n".join(lines)
46
+
47
+
48
+ def copy_to_clipboard(text: str) -> None:
49
+ """Copy ``text`` with pyperclip; raises RuntimeError with a readable reason on failure.
50
+
51
+ Examples::
52
+
53
+ copy_to_clipboard("proj/\\n└── a.py") # None
54
+ """
55
+ try:
56
+ import pyperclip
57
+ except ImportError:
58
+ raise RuntimeError("pyperclip is not installed (uv add pyperclip)") from None
59
+ try:
60
+ pyperclip.copy(text)
61
+ except pyperclip.PyperclipException as err:
62
+ raise RuntimeError(f"no clipboard available: {err}") from None
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.4
2
+ Name: ramani
3
+ Version: 0.1.0a1
4
+ Summary: Ramani (Swahili for “map”): keeps each file's path as a comment on its first line, updates it when files move, and prints your project as a tree.
5
+ Keywords: comments,paths,tree,project-structure,cli,swahili
6
+ Author: Kevin Wasike Wakhisi
7
+ Author-email: Kevin Wasike Wakhisi <kevin@treeolive.tech>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Topic :: Software Development
20
+ Classifier: Topic :: Utilities
21
+ Requires-Dist: pyperclip>=1.8
22
+ Maintainer: Kevin Wasike Wakhisi
23
+ Maintainer-email: Kevin Wasike Wakhisi <kevin@treeolive.tech>
24
+ Requires-Python: >=3.13
25
+ Project-URL: Repository, https://github.com/kvnwaks/ramani.git
26
+ Description-Content-Type: text/markdown
27
+
28
+ <!-- ramani: README.md -->
29
+ <h1 align="center">ramani</h1>
30
+
31
+ <p align="center">
32
+ <strong>Every file knows where it lives.</strong><br>
33
+ A line at the top of each file says where it sits in your project, and it follows the file when it moves.
34
+ </p>
35
+
36
+ <p align="center">
37
+ <a href="https://www.python.org/"><img alt="Python 3.13+" src="https://img.shields.io/badge/python-3.13%2B-3776AB?logo=python&logoColor=white"></a>
38
+ <a href="https://docs.astral.sh/uv/"><img alt="Built with uv" src="https://img.shields.io/badge/built%20with-uv-DE5FE9"></a>
39
+ <img alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue">
40
+ <img alt="ramani means map in Swahili" src="https://img.shields.io/badge/ramani-Swahili%20for%20%22map%22-006600">
41
+ </p>
42
+
43
+ <p align="center">
44
+ <a href="#install">Install</a> ·
45
+ <a href="#usage">Usage</a> ·
46
+ <a href="#folder-tree">Folder tree</a> ·
47
+ <a href="#configuration">Configuration</a> ·
48
+ <a href="#supported-files">Supported files</a>
49
+ </p>
50
+
51
+ > **ramani** _(ra-MA-ni)_ is Swahili for **"map"**. That is the whole idea: ramani draws a map of your project _inside_ the project. Each file carries one comment with its own path, kept correct as files are renamed and moved, and the same tool can print the entire project as a tree.
52
+
53
+ ```python
54
+ # ramani: src/shop/billing/pay.py
55
+ def pay(): ...
56
+ ```
57
+
58
+ ## Why
59
+
60
+ Files travel without their address. They get pasted into chats, issues, code reviews and AI prompts, and the question "which file is this, again?" comes up every time. With ramani the path is part of the file, so it travels with it.
61
+
62
+ ## Features
63
+
64
+ - 🧭 **Move-aware.** Rename or move a file, run ramani again, and its comment follows. Nothing is duplicated.
65
+ - 🪶 **Careful placement.** The comment goes after shebangs, encoding lines, XML declarations and Markdown front matter, and never turns a docstring into a plain string.
66
+ - 🗂️ **Knows 60+ file types.** Python, JavaScript, Go, Rust, SQL, HTML, CSS, Markdown, Dockerfile and more, each with the right comment syntax. Add your own in one line.
67
+ - 🙈 **Respects your ignores.** Built-in lists for `__pycache__`, `node_modules` and friends, every `.gitignore` it finds (nested ones too), and flags for the rest.
68
+ - 🌳 **Prints a folder tree.** One flag draws your project as a tree, another copies it to the clipboard.
69
+ - 🔍 **CI-friendly.** `--check` exits with code 1 when any comment is missing or stale. `--dry-run` writes nothing.
70
+ - 🧹 **Reversible.** `--remove` strips every comment ramani added.
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ uv tool install ramani # or: pipx install ramani / pip install ramani
76
+ ```
77
+
78
+ Then, inside a project:
79
+
80
+ ```bash
81
+ ramani --dry-run # see what would change
82
+ ramani # do it
83
+ ```
84
+
85
+ ## Usage
86
+
87
+ Point it at a folder (default: the current one) or a single file. Paths in the comments are relative to that folder.
88
+
89
+ ```console
90
+ $ ramani
91
+ added docs/setup.md
92
+ added src/shop/cart.py
93
+ added src/shop/index.html
94
+ added src/shop/pay.py
95
+ added README.md
96
+ 5 added, 1 unsupported
97
+ no comment style for: .json x1
98
+ add one with -c EXT=START[,END] or [tool.ramani.comments] in pyproject.toml
99
+ ```
100
+
101
+ The comment uses each language's own syntax, and sits where it can't break anything:
102
+
103
+ ```python
104
+ # ramani: src/shop/cart.py
105
+ """Cart logic."""
106
+ import json
107
+ ```
108
+
109
+ ```html
110
+ <!-- ramani: src/shop/index.html -->
111
+ <h1>Hi</h1>
112
+ ```
113
+
114
+ ```text
115
+ ---
116
+ title: Setup
117
+ ---
118
+ <!-- ramani: docs/setup.md -->
119
+ # Setup
120
+ ```
121
+
122
+ ### When a file moves
123
+
124
+ Move `pay.py` into a new `billing/` folder and run ramani again. It recognises its own comment, sees the path is out of date, and rewrites it. Untouched files stay untouched.
125
+
126
+ ```console
127
+ $ mkdir src/shop/billing && mv src/shop/pay.py src/shop/billing/
128
+ $ ramani
129
+ updated src/shop/billing/pay.py
130
+ 4 unchanged, 1 unsupported, 1 updated
131
+ ```
132
+
133
+ ```python
134
+ # ramani: src/shop/billing/pay.py
135
+ def pay(): ...
136
+ ```
137
+
138
+ Add `ramani --check` to CI or a pre-commit hook to catch stale comments before they land. It changes nothing and exits with 1 if anything needs updating.
139
+
140
+ ## Folder tree
141
+
142
+ `--tree` prints your project as a tree and writes nothing. It uses the same ignore rules as marking, so you see exactly the files ramani works on. Folders come first.
143
+
144
+ ```console
145
+ $ ramani --tree
146
+ shop/
147
+ ├── docs/
148
+ │ └── setup.md
149
+ ├── src/
150
+ │ └── shop/
151
+ │ ├── billing/
152
+ │ │ └── pay.py
153
+ │ ├── cart.py
154
+ │ └── index.html
155
+ ├── README.md
156
+ └── data.json
157
+ ```
158
+
159
+ Add `--copy` to also put the tree on your clipboard, ready to paste into a chat, an issue or a doc.
160
+
161
+ ```bash
162
+ ramani --copy # print the tree and copy it
163
+ ramani ./src -t -d tests # tree of ./src, leaving out tests
164
+ ```
165
+
166
+ > On Linux, the clipboard needs `xclip`, `xsel` or `wl-clipboard` installed. If none is available the tree is still printed, with a note on stderr and exit code 1.
167
+
168
+ ## Options
169
+
170
+ | Option | What it does |
171
+ | ------------------------------- | ------------------------------------------------------------------- |
172
+ | `PATH` | Folder or file to process (default: current folder) |
173
+ | `-e, --ignore-ext EXT` | Also skip this extension, e.g. `-e .txt` (repeatable) |
174
+ | `-d, --ignore-dir NAME` | Also skip this folder name or glob, e.g. `-d "build*"` (repeatable) |
175
+ | `-c, --comment EXT=START[,END]` | Comment style for an extension or file name (repeatable) |
176
+ | `--no-gitignore` | Ignore `.gitignore` files |
177
+ | `-n, --dry-run` | Show what would change, write nothing |
178
+ | `--check` | Dry run that exits 1 if anything is missing or stale |
179
+ | `--remove` | Strip ramani comments instead of adding them |
180
+ | `-t, --tree` | Print the folder tree instead of marking files |
181
+ | `--copy` | Copy the tree to the clipboard (implies `--tree`) |
182
+ | `-V, --version` | Print the installed version and exit |
183
+ | `-v, --verbose` | Also list unchanged files |
184
+
185
+ ## Configuration
186
+
187
+ Teach ramani a file type on the command line:
188
+
189
+ ```bash
190
+ ramani -c .abc=// # line comment
191
+ ramani -c ".tpl=<!--,-->" # block comment: start,end
192
+ ramani -c Jenkinsfile=// # by exact file name
193
+ ```
194
+
195
+ or once and for all in your `pyproject.toml`:
196
+
197
+ ```toml
198
+ [tool.ramani.comments]
199
+ ".abc" = "//"
200
+ ".tpl" = ["<!--", "-->"]
201
+ ```
202
+
203
+ Flags beat `pyproject.toml`, which beats the built-in styles, so you can override those too.
204
+
205
+ ## Supported files
206
+
207
+ | Comment | Looks like | Files |
208
+ | ---------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
209
+ | `#` | `# ramani: a/b.py` | `.py` `.pyi` `.sh` `.rb` `.pl` `.r` `.jl` `.ex` `.yml` `.yaml` `.toml` `.cfg` `.tf` `.ps1` `.nix` `Dockerfile` `Makefile` `.gitignore` … |
210
+ | `//` | `// ramani: a/b.ts` | `.js` `.mjs` `.jsx` `.ts` `.tsx` `.java` `.kt` `.scala` `.c` `.h` `.cpp` `.cs` `.go` `.rs` `.swift` `.dart` `.scss` `.proto` … |
211
+ | `--` | `-- ramani: a/b.sql` | `.sql` `.lua` `.hs` `.elm` |
212
+ | `<!-- -->` | `<!-- ramani: a/b.html -->` | `.html` `.htm` `.xml` `.svg` `.vue` `.svelte` `.md` `.markdown` |
213
+ | `/* */` | `/* ramani: a/b.css */` | `.css` |
214
+ | `{# #}` | `{# ramani: a/b.j2 #}` | `.j2` `.jinja` `.jinja2` |
215
+ | `{/* */}` | `{/* ramani: a/b.mdx */}` | `.mdx` |
216
+ | `%` | `% ramani: a/b.tex` | `.tex` |
217
+
218
+ Formats with no comment syntax, such as `.json` and `.csv`, are left alone and listed at the end of each run so nothing is skipped silently. The full table lives in `src/ramani/config.py`.
219
+
220
+ ## How it works
221
+
222
+ 1. Skip anything that must stay first: a shebang, an encoding line, an XML declaration, a `# syntax=` line, or front matter in Markdown.
223
+ 2. Look at the next line. If it is a ramani comment with the **same** path, do nothing.
224
+ 3. If it is a ramani comment with a **different** path, the file has moved. Rewrite that one line.
225
+ 4. If it is not a ramani comment, insert one.
226
+
227
+ Line endings (LF or CRLF) and UTF-8 byte-order marks are preserved. Symlinks, files that are not UTF-8, and binary files (anything containing a NUL byte) are never touched.
228
+
229
+ ## Development
230
+
231
+ ```bash
232
+ uv sync
233
+ uv run poe test
234
+ ```
235
+
236
+ Ramani has a single runtime dependency, [`pyperclip`](https://pypi.org/project/pyperclip/), used only for `--copy`.
237
+
238
+ ## License
239
+
240
+ MIT © Kevin Wasike Wakhisi. Use it, change it, ship it; just keep the copyright notice.
@@ -0,0 +1,14 @@
1
+ ramani/__init__.py,sha256=v31xgJoFvaeGeLN1Uqzd_Xu0aR7mQ1g6YLlfMB-TnKQ,242
2
+ ramani/__main__.py,sha256=8maTVmM3eZksbf7iHtNrS532aCYQesydkoLZ4bpGX7I,116
3
+ ramani/cli.py,sha256=2P6zWU_-w6SAxFC_sid1oxponvhhoFG-Q6s4A6g_ies,5510
4
+ ramani/config.py,sha256=6w6l8Aeds96Fv5VoihZA7_zUcutjGK9hADT9PHnS-EE,2280
5
+ ramani/core.py,sha256=FUJhkQd1X0wDLc51ns6P2rJy6txBdPd2m1niker8qyQ,8586
6
+ ramani/gitignore.py,sha256=ghOl88k2SarLhaHkaE6X8y_dVfBSCqnVUrCzaCJXktg,3815
7
+ ramani/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ ramani/settings.py,sha256=jqrZ41XyEYPIB4yzLNJjxHDMItODw1UpNIr41dgSy4s,1915
9
+ ramani/tree.py,sha256=u0fbZeGrXgwd7fPwoHpyPfd30yk_LqwwwiSdPrFtS4s,1846
10
+ ramani-0.1.0a1.dist-info/licenses/LICENSE,sha256=2kw0HM4IL_7KXe_PKsBW4a8r4z9rBib1vGwavs8-j3A,1077
11
+ ramani-0.1.0a1.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
12
+ ramani-0.1.0a1.dist-info/entry_points.txt,sha256=bjmEYJNE67MlmjXyGWYDP5DQwc7yX10HxjrlBUDbKdM,40
13
+ ramani-0.1.0a1.dist-info/METADATA,sha256=d0FDNlzzoQ7IdUQu_qX4cJuwIC-ha3DbCbElxYCcDV8,10880
14
+ ramani-0.1.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ ramani = ramani:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Wasike Wakhisi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.