codetree-cli 0.3.0__tar.gz → 0.4.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.
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/PKG-INFO +5 -3
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/README.md +4 -2
- codetree_cli-0.4.0/codetree/__init__.py +1 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree/cli.py +11 -2
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree/core.py +59 -14
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree/gui.py +27 -8
- codetree_cli-0.4.0/codetree/report.py +223 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree_cli.egg-info/PKG-INFO +5 -3
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree_cli.egg-info/SOURCES.txt +1 -0
- codetree_cli-0.4.0/tests/test_core.py +165 -0
- codetree_cli-0.3.0/codetree/__init__.py +0 -1
- codetree_cli-0.3.0/tests/test_core.py +0 -82
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/LICENSE +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree/__main__.py +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree_cli.egg-info/dependency_links.txt +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree_cli.egg-info/entry_points.txt +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/codetree_cli.egg-info/top_level.txt +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/pyproject.toml +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/setup.cfg +0 -0
- {codetree_cli-0.3.0 → codetree_cli-0.4.0}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codetree-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: See your codebase as a living, animated tree: lines of code, comments and languages per folder and file.
|
|
5
5
|
Home-page: https://github.com/rezamardani01/codetree
|
|
6
6
|
Author: Reza Mardani
|
|
@@ -92,7 +92,7 @@ codetree-gui # same, without a console window on Windows
|
|
|
92
92
|
| **Click a language** | Lights up all leaves written in it |
|
|
93
93
|
| **Click a file in "Largest files"** | Flies the camera to that leaf |
|
|
94
94
|
| **Expand all · Collapse · Fit view** | Overview controls |
|
|
95
|
-
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown |
|
|
95
|
+
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown / standalone HTML |
|
|
96
96
|
|
|
97
97
|
Shortcuts: `F5` rescan · `Ctrl+O` browse · `Ctrl+F` search · `Ctrl+E` export JSON · `Esc` clear search.
|
|
98
98
|
|
|
@@ -111,12 +111,14 @@ codetree --cli --top 10 # also list the 10 largest files
|
|
|
111
111
|
codetree -e py -e js -i "*.min.js" # only these extensions, ignore a pattern
|
|
112
112
|
codetree --json report.json # write reports (use - for stdout)
|
|
113
113
|
codetree --csv report.csv --md report.md
|
|
114
|
+
codetree --html report.html # standalone interactive HTML report
|
|
114
115
|
```
|
|
115
116
|
|
|
116
117
|
| Option | Description |
|
|
117
118
|
|---|---|
|
|
118
119
|
| `--cli` | Print to the terminal instead of opening the GUI |
|
|
119
120
|
| `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
|
|
121
|
+
| `--html FILE` | Export a **standalone interactive HTML report** — summary cards, language donut, searchable collapsible tree. Single file, zero dependencies, opens in any browser, great for sharing or CI artifacts (implies `--cli`) |
|
|
120
122
|
| `-i, --ignore PATTERN` | Glob to ignore, repeatable |
|
|
121
123
|
| `-e, --ext EXT` | Only count these extensions, repeatable |
|
|
122
124
|
| `--hidden` | Include hidden files and folders |
|
|
@@ -144,7 +146,7 @@ for lang in result.languages.values():
|
|
|
144
146
|
|
|
145
147
|
- Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
|
|
146
148
|
- `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
|
|
147
|
-
- Patterns in the project
|
|
149
|
+
- Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
|
|
148
150
|
- Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
|
|
149
151
|
|
|
150
152
|
## Development
|
|
@@ -66,7 +66,7 @@ codetree-gui # same, without a console window on Windows
|
|
|
66
66
|
| **Click a language** | Lights up all leaves written in it |
|
|
67
67
|
| **Click a file in "Largest files"** | Flies the camera to that leaf |
|
|
68
68
|
| **Expand all · Collapse · Fit view** | Overview controls |
|
|
69
|
-
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown |
|
|
69
|
+
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown / standalone HTML |
|
|
70
70
|
|
|
71
71
|
Shortcuts: `F5` rescan · `Ctrl+O` browse · `Ctrl+F` search · `Ctrl+E` export JSON · `Esc` clear search.
|
|
72
72
|
|
|
@@ -85,12 +85,14 @@ codetree --cli --top 10 # also list the 10 largest files
|
|
|
85
85
|
codetree -e py -e js -i "*.min.js" # only these extensions, ignore a pattern
|
|
86
86
|
codetree --json report.json # write reports (use - for stdout)
|
|
87
87
|
codetree --csv report.csv --md report.md
|
|
88
|
+
codetree --html report.html # standalone interactive HTML report
|
|
88
89
|
```
|
|
89
90
|
|
|
90
91
|
| Option | Description |
|
|
91
92
|
|---|---|
|
|
92
93
|
| `--cli` | Print to the terminal instead of opening the GUI |
|
|
93
94
|
| `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
|
|
95
|
+
| `--html FILE` | Export a **standalone interactive HTML report** — summary cards, language donut, searchable collapsible tree. Single file, zero dependencies, opens in any browser, great for sharing or CI artifacts (implies `--cli`) |
|
|
94
96
|
| `-i, --ignore PATTERN` | Glob to ignore, repeatable |
|
|
95
97
|
| `-e, --ext EXT` | Only count these extensions, repeatable |
|
|
96
98
|
| `--hidden` | Include hidden files and folders |
|
|
@@ -118,7 +120,7 @@ for lang in result.languages.values():
|
|
|
118
120
|
|
|
119
121
|
- Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
|
|
120
122
|
- `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
|
|
121
|
-
- Patterns in the project
|
|
123
|
+
- Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
|
|
122
124
|
- Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
|
|
123
125
|
|
|
124
126
|
## Development
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.4.0"
|
|
@@ -7,6 +7,7 @@ import sys
|
|
|
7
7
|
from . import __version__
|
|
8
8
|
from .core import (DirNode, ScanOptions, ScanResult, format_size, scan, sorted_languages,
|
|
9
9
|
to_csv, to_json, to_markdown)
|
|
10
|
+
from .report import to_html
|
|
10
11
|
|
|
11
12
|
SORT_KEYS = {
|
|
12
13
|
"name": lambda n: n.name.lower(),
|
|
@@ -80,6 +81,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
80
81
|
p.add_argument("--json", metavar="FILE", help="write a JSON report ('-' for stdout); implies --cli")
|
|
81
82
|
p.add_argument("--csv", metavar="FILE", help="write a CSV report ('-' for stdout); implies --cli")
|
|
82
83
|
p.add_argument("--md", metavar="FILE", help="write a Markdown report ('-' for stdout); implies --cli")
|
|
84
|
+
p.add_argument("--html", metavar="FILE", help="write a standalone interactive HTML report ('-' for stdout); implies --cli")
|
|
83
85
|
p.add_argument("-i", "--ignore", action="append", default=[], metavar="PATTERN",
|
|
84
86
|
help="glob pattern to ignore (repeatable), e.g. -i '*.min.js' -i tests")
|
|
85
87
|
p.add_argument("-e", "--ext", action="append", default=[], metavar="EXT",
|
|
@@ -106,7 +108,14 @@ def _emit(target: str, text: str) -> None:
|
|
|
106
108
|
|
|
107
109
|
|
|
108
110
|
def main(argv=None) -> int:
|
|
109
|
-
|
|
111
|
+
parser = build_parser()
|
|
112
|
+
args = parser.parse_args(argv)
|
|
113
|
+
if args.depth < 0:
|
|
114
|
+
parser.error("--depth must be >= 0")
|
|
115
|
+
if args.top < 0:
|
|
116
|
+
parser.error("--top must be >= 0")
|
|
117
|
+
if args.max_size < 0:
|
|
118
|
+
parser.error("--max-size must be >= 0")
|
|
110
119
|
path = os.path.abspath(args.path)
|
|
111
120
|
if not os.path.isdir(path):
|
|
112
121
|
print(f"codetree: '{args.path}' is not a directory.", file=sys.stderr)
|
|
@@ -121,7 +130,7 @@ def main(argv=None) -> int:
|
|
|
121
130
|
max_size=int(args.max_size * 1024 * 1024),
|
|
122
131
|
)
|
|
123
132
|
|
|
124
|
-
exports = [(args.json, to_json), (args.csv, to_csv), (args.md, to_markdown)]
|
|
133
|
+
exports = [(args.json, to_json), (args.csv, to_csv), (args.md, to_markdown), (args.html, to_html)]
|
|
125
134
|
wants_cli = args.cli or any(t for t, _ in exports)
|
|
126
135
|
|
|
127
136
|
if not wants_cli:
|
|
@@ -80,6 +80,8 @@ def detect_language(filename: str) -> str:
|
|
|
80
80
|
low = filename.lower()
|
|
81
81
|
if low in _FILENAMES:
|
|
82
82
|
return _FILENAMES[low]
|
|
83
|
+
if low.startswith("dockerfile"): # Dockerfile.dev, Dockerfile.prod, ...
|
|
84
|
+
return "Dockerfile"
|
|
83
85
|
ext = os.path.splitext(low)[1]
|
|
84
86
|
return EXT_TO_LANG.get(ext, "Other")
|
|
85
87
|
|
|
@@ -227,24 +229,60 @@ def analyze_file(path: str) -> Optional[FileStat]:
|
|
|
227
229
|
name = os.path.basename(path)
|
|
228
230
|
lang = detect_language(name)
|
|
229
231
|
lc, bc, _ = LANG_SPECS[lang]
|
|
230
|
-
|
|
232
|
+
# utf-8-sig transparently strips a BOM; without it the BOM character glues
|
|
233
|
+
# itself to the first token and a leading comment on line 1 counts as code.
|
|
234
|
+
with open(path, "r", encoding="utf-8-sig", errors="replace") as fh:
|
|
231
235
|
code, comment, blank = classify_lines(fh, tuple(lc), bc)
|
|
232
236
|
return FileStat(path, name, lang, code, comment, blank, os.path.getsize(path))
|
|
233
237
|
|
|
234
238
|
|
|
235
|
-
def _load_gitignore(directory: str) -> List[str]:
|
|
239
|
+
def _load_gitignore(directory: str) -> List[Tuple[str, bool]]:
|
|
240
|
+
"""Parse one ``.gitignore`` into ordered ``(pattern, negated)`` pairs."""
|
|
236
241
|
patterns = []
|
|
237
242
|
try:
|
|
238
|
-
with open(os.path.join(directory, ".gitignore"), "r", encoding="utf-8",
|
|
243
|
+
with open(os.path.join(directory, ".gitignore"), "r", encoding="utf-8-sig",
|
|
244
|
+
errors="replace") as fh:
|
|
239
245
|
for line in fh:
|
|
240
246
|
line = line.strip()
|
|
241
|
-
if line
|
|
242
|
-
|
|
247
|
+
if not line or line.startswith("#"):
|
|
248
|
+
continue
|
|
249
|
+
negated = line.startswith("!")
|
|
250
|
+
if negated:
|
|
251
|
+
line = line[1:].strip()
|
|
252
|
+
if not line:
|
|
253
|
+
continue
|
|
254
|
+
patterns.append((line.rstrip("/"), negated))
|
|
243
255
|
except OSError:
|
|
244
256
|
pass
|
|
245
257
|
return patterns
|
|
246
258
|
|
|
247
259
|
|
|
260
|
+
def _gitignore_match(name: str, rel: str, stack) -> bool:
|
|
261
|
+
"""Gitignore decision for one entry; the last matching pattern wins.
|
|
262
|
+
|
|
263
|
+
``stack`` holds ``(dir_prefix, patterns)`` pairs ordered from the project
|
|
264
|
+
root down to the current directory, so patterns from deeper ``.gitignore``
|
|
265
|
+
files take precedence, and a ``!`` pattern can re-include a file.
|
|
266
|
+
``rel`` is the entry path relative to the project root with ``/`` separators.
|
|
267
|
+
"""
|
|
268
|
+
ignored = False
|
|
269
|
+
for prefix, patterns in stack:
|
|
270
|
+
if prefix:
|
|
271
|
+
if not rel.startswith(prefix):
|
|
272
|
+
continue
|
|
273
|
+
sub = rel[len(prefix):]
|
|
274
|
+
else:
|
|
275
|
+
sub = rel
|
|
276
|
+
for pat, negated in patterns:
|
|
277
|
+
if "/" in pat: # anchored to the directory holding the .gitignore
|
|
278
|
+
if fnmatch.fnmatch(sub, pat.lstrip("/")) or \
|
|
279
|
+
(pat.startswith("**/") and fnmatch.fnmatch(name, pat[3:])):
|
|
280
|
+
ignored = not negated
|
|
281
|
+
elif fnmatch.fnmatch(name, pat): # unanchored: matches at any depth
|
|
282
|
+
ignored = not negated
|
|
283
|
+
return ignored
|
|
284
|
+
|
|
285
|
+
|
|
248
286
|
def scan(path: str, options: Optional[ScanOptions] = None,
|
|
249
287
|
progress: Optional[Callable[[int, str], None]] = None,
|
|
250
288
|
cancel: Optional[Callable[[], bool]] = None) -> ScanResult:
|
|
@@ -258,12 +296,13 @@ def scan(path: str, options: Optional[ScanOptions] = None,
|
|
|
258
296
|
started = time.perf_counter()
|
|
259
297
|
exts = {e.lower() if e.startswith(".") else "." + e.lower() for e in opts.extensions}
|
|
260
298
|
user_ignore = list(opts.ignore)
|
|
261
|
-
|
|
299
|
+
git_root = _load_gitignore(root_path) if opts.respect_gitignore else []
|
|
300
|
+
git_stack = [("", git_root)] if git_root else []
|
|
262
301
|
|
|
263
302
|
all_files: List[FileStat] = []
|
|
264
303
|
result = ScanResult(DirNode(os.path.basename(root_path) or root_path, root_path), {}, all_files)
|
|
265
304
|
|
|
266
|
-
def ignored(name: str, rel: str, is_dir: bool) -> bool:
|
|
305
|
+
def ignored(name: str, rel: str, is_dir: bool, gi_stack) -> bool:
|
|
267
306
|
if name.startswith(".") and not opts.include_hidden:
|
|
268
307
|
return True
|
|
269
308
|
if opts.use_default_ignores:
|
|
@@ -274,17 +313,18 @@ def scan(path: str, options: Optional[ScanOptions] = None,
|
|
|
274
313
|
elif is_dir and name in (".git", ".hg", ".svn"):
|
|
275
314
|
return True
|
|
276
315
|
rel = rel.replace(os.sep, "/")
|
|
277
|
-
for pat in user_ignore
|
|
316
|
+
for pat in user_ignore:
|
|
278
317
|
if fnmatch.fnmatch(name, pat) or fnmatch.fnmatch(rel, pat):
|
|
279
318
|
return True
|
|
280
|
-
return
|
|
319
|
+
return bool(gi_stack) and _gitignore_match(name, rel, gi_stack)
|
|
281
320
|
|
|
282
|
-
def walk(node: DirNode, rel_dir: str) -> None:
|
|
321
|
+
def walk(node: DirNode, rel_dir: str, gi_stack) -> None:
|
|
283
322
|
if cancel and cancel():
|
|
284
323
|
result.cancelled = True
|
|
285
324
|
return
|
|
286
325
|
try:
|
|
287
|
-
|
|
326
|
+
with os.scandir(node.path) as it: # context manager: close the dir handle promptly
|
|
327
|
+
entries = sorted(it, key=lambda e: e.name.lower())
|
|
288
328
|
except OSError as e:
|
|
289
329
|
result.errors.append(f"{node.path}: {e.strerror or e}")
|
|
290
330
|
return
|
|
@@ -297,12 +337,17 @@ def scan(path: str, options: Optional[ScanOptions] = None,
|
|
|
297
337
|
is_file = entry.is_file()
|
|
298
338
|
except OSError:
|
|
299
339
|
continue
|
|
300
|
-
if not (is_dir or is_file) or ignored(entry.name, rel, is_dir):
|
|
340
|
+
if not (is_dir or is_file) or ignored(entry.name, rel, is_dir, gi_stack):
|
|
301
341
|
continue
|
|
302
342
|
if is_dir:
|
|
343
|
+
child_stack = gi_stack
|
|
344
|
+
if opts.respect_gitignore:
|
|
345
|
+
child_patterns = _load_gitignore(entry.path)
|
|
346
|
+
if child_patterns:
|
|
347
|
+
child_stack = gi_stack + [(rel.replace(os.sep, "/") + "/", child_patterns)]
|
|
303
348
|
child = DirNode(entry.name, entry.path)
|
|
304
349
|
node.dirs.append(child)
|
|
305
|
-
walk(child, rel)
|
|
350
|
+
walk(child, rel, child_stack)
|
|
306
351
|
continue
|
|
307
352
|
if exts and os.path.splitext(entry.name)[1].lower() not in exts:
|
|
308
353
|
continue
|
|
@@ -322,7 +367,7 @@ def scan(path: str, options: Optional[ScanOptions] = None,
|
|
|
322
367
|
if progress:
|
|
323
368
|
progress(len(all_files), entry.path)
|
|
324
369
|
|
|
325
|
-
walk(result.root, "")
|
|
370
|
+
walk(result.root, "", git_stack)
|
|
326
371
|
result.root.finalize()
|
|
327
372
|
|
|
328
373
|
def count_dirs(n: DirNode) -> int:
|
|
@@ -17,6 +17,7 @@ from tkinter import filedialog, messagebox, ttk
|
|
|
17
17
|
from . import __version__
|
|
18
18
|
from .core import (DirNode, FileStat, ScanOptions, ScanResult, format_size, language_color, scan,
|
|
19
19
|
sorted_languages, to_csv, to_json, to_markdown)
|
|
20
|
+
from .report import to_html
|
|
20
21
|
|
|
21
22
|
THEMES = {
|
|
22
23
|
"dark": dict(bg="#0a0e14", panel="#111720", card="#161d29", border="#243041", fg="#e6edf3",
|
|
@@ -44,11 +45,20 @@ def mix(c1: str, c2: str, a: float) -> str:
|
|
|
44
45
|
|
|
45
46
|
|
|
46
47
|
def _load_config() -> dict:
|
|
48
|
+
"""Load ~/.codetree.json; fall back to defaults if it is corrupt."""
|
|
47
49
|
try:
|
|
48
50
|
with open(CONFIG_PATH, "r", encoding="utf-8") as fh:
|
|
49
|
-
|
|
51
|
+
cfg = json.load(fh)
|
|
50
52
|
except (OSError, ValueError):
|
|
51
53
|
return {}
|
|
54
|
+
if not isinstance(cfg, dict):
|
|
55
|
+
return {}
|
|
56
|
+
if not isinstance(cfg.get("recent"), list):
|
|
57
|
+
cfg["recent"] = []
|
|
58
|
+
cfg["recent"] = [p for p in cfg["recent"] if isinstance(p, str)]
|
|
59
|
+
if cfg.get("theme") not in THEMES: # unknown theme names would KeyError later
|
|
60
|
+
cfg.pop("theme", None)
|
|
61
|
+
return cfg
|
|
52
62
|
|
|
53
63
|
|
|
54
64
|
def _save_config(cfg: dict) -> None:
|
|
@@ -78,7 +88,7 @@ class VNode:
|
|
|
78
88
|
"""One animated node of the visual tree (folder, file or '+N more')."""
|
|
79
89
|
__slots__ = ("key", "kind", "data", "name", "parent", "children", "depth", "x", "y", "tx", "ty", "g",
|
|
80
90
|
"delay", "dying", "expanded", "r", "ew", "total", "lang", "e", "gl", "o", "t", "b",
|
|
81
|
-
"cstate", "lab_vis", "shown", "bcount", "anc", "ewc")
|
|
91
|
+
"cstate", "lab_vis", "shown", "bcount", "anc", "ewc", "tname")
|
|
82
92
|
|
|
83
93
|
def __init__(self, key, kind):
|
|
84
94
|
self.key, self.kind = key, kind
|
|
@@ -98,6 +108,7 @@ class VNode:
|
|
|
98
108
|
self.bcount = 0
|
|
99
109
|
self.anc = None
|
|
100
110
|
self.ewc = None
|
|
111
|
+
self.tname = None
|
|
101
112
|
|
|
102
113
|
|
|
103
114
|
class App:
|
|
@@ -185,7 +196,7 @@ class App:
|
|
|
185
196
|
ttk.Button(head, text="◐ Theme", style="Ghost.TButton", command=self.toggle_theme).pack(side="right")
|
|
186
197
|
self.btn_export = ttk.Menubutton(head, text="⭳ Export", style="Ghost.TMenubutton")
|
|
187
198
|
self.export_menu = tk.Menu(self.btn_export, tearoff=0)
|
|
188
|
-
for label, kind in (("JSON…", "json"), ("CSV…", "csv"), ("Markdown…", "md")):
|
|
199
|
+
for label, kind in (("JSON…", "json"), ("CSV…", "csv"), ("Markdown…", "md"), ("HTML report…", "html")):
|
|
189
200
|
self.export_menu.add_command(label=label, command=lambda k=kind: self.export(k))
|
|
190
201
|
self.btn_export["menu"] = self.export_menu
|
|
191
202
|
self.btn_export.pack(side="right", padx=8)
|
|
@@ -285,8 +296,8 @@ class App:
|
|
|
285
296
|
r.bind("<F5>", lambda e: self.start_scan())
|
|
286
297
|
r.bind("<Control-o>", lambda e: self.browse())
|
|
287
298
|
r.bind("<Control-f>", lambda e: (self.search.focus_set(), self.search.select_range(0, "end")))
|
|
288
|
-
r.bind("<Control-e>", lambda e: self.export("json"))
|
|
289
299
|
r.bind("<Escape>", lambda e: (self.var_search.set(""), self.select(None)))
|
|
300
|
+
cv.bind("<Control-e>", lambda e: self.export("json")) # canvas only: keep Ctrl+E usable in text fields
|
|
290
301
|
self.path_box.bind("<Return>", lambda e: self.start_scan())
|
|
291
302
|
self.path_box.bind("<<ComboboxSelected>>", lambda e: self.start_scan())
|
|
292
303
|
self.var_search.trace_add("write", lambda *a: self.on_search())
|
|
@@ -300,6 +311,10 @@ class App:
|
|
|
300
311
|
cv.bind("<MouseWheel>", lambda e: self.zoom_at(e.x, e.y, 1.12 if e.delta > 0 else 1 / 1.12))
|
|
301
312
|
cv.bind("<Button-4>", lambda e: self.zoom_at(e.x, e.y, 1.12))
|
|
302
313
|
cv.bind("<Button-5>", lambda e: self.zoom_at(e.x, e.y, 1 / 1.12))
|
|
314
|
+
for panel in (self.cv_lang, self.cv_top): # the side-panel lists have no scrollbars
|
|
315
|
+
panel.bind("<MouseWheel>", lambda e, w=panel: w.yview_scroll(-1 if e.delta > 0 else 1, "units"))
|
|
316
|
+
panel.bind("<Button-4>", lambda e, w=panel: w.yview_scroll(-2, "units"))
|
|
317
|
+
panel.bind("<Button-5>", lambda e, w=panel: w.yview_scroll(2, "units"))
|
|
303
318
|
self.ctx = tk.Menu(self.root, tearoff=0)
|
|
304
319
|
self.ctx.add_command(label="Open", command=lambda: self.ctx_act("open"))
|
|
305
320
|
self.ctx.add_command(label="Show in folder", command=lambda: self.ctx_act("reveal"))
|
|
@@ -645,8 +660,8 @@ class App:
|
|
|
645
660
|
return
|
|
646
661
|
self.grow_token += 1
|
|
647
662
|
self.expanded = {self.result.root.path}
|
|
648
|
-
frontier
|
|
649
|
-
count = self.visible_count_estimate([self.result.root]) - len(
|
|
663
|
+
frontier = [self.result.root]
|
|
664
|
+
count = self.visible_count_estimate([self.result.root]) - len(self.live_nodes())
|
|
650
665
|
while frontier and count < EXPAND_ALL_CAP:
|
|
651
666
|
nxt = []
|
|
652
667
|
for d in sorted((c for p in frontier for c in p.dirs), key=lambda c: -c.total):
|
|
@@ -933,6 +948,7 @@ class App:
|
|
|
933
948
|
font=self.font(self.cur_fs, n.kind == "dir"), tags="text")
|
|
934
949
|
n.b = cv.create_text(0, 0, text="", font=self.font(max(7, self.cur_fs - 2), True), tags="text")
|
|
935
950
|
n.cstate = None
|
|
951
|
+
n.tname = n.name
|
|
936
952
|
|
|
937
953
|
def node_colors(self, n: VNode):
|
|
938
954
|
t = self.t
|
|
@@ -986,6 +1002,9 @@ class App:
|
|
|
986
1002
|
if n.o is None:
|
|
987
1003
|
self.make_items(n)
|
|
988
1004
|
created = True
|
|
1005
|
+
if n.tname != n.name: # e.g. the "+N more files" counter after a rescan
|
|
1006
|
+
cv.itemconfigure(n.t, text=n.name)
|
|
1007
|
+
n.tname = n.name
|
|
989
1008
|
px, py = n.x * s + ox, n.y * s + oy
|
|
990
1009
|
p = n.parent
|
|
991
1010
|
qx, qy = (p.x * s + ox, p.y * s + oy) if p else (px, py)
|
|
@@ -1249,8 +1268,8 @@ class App:
|
|
|
1249
1268
|
if not self.result:
|
|
1250
1269
|
messagebox.showinfo("CodeTree", "Run a scan first.")
|
|
1251
1270
|
return
|
|
1252
|
-
fn = {"json": to_json, "csv": to_csv, "md": to_markdown}[kind]
|
|
1253
|
-
ext = {"json": ".json", "csv": ".csv", "md": ".md"}[kind]
|
|
1271
|
+
fn = {"json": to_json, "csv": to_csv, "md": to_markdown, "html": to_html}[kind]
|
|
1272
|
+
ext = {"json": ".json", "csv": ".csv", "md": ".md", "html": ".html"}[kind]
|
|
1254
1273
|
path = filedialog.asksaveasfilename(defaultextension=ext, initialfile=f"codetree-report{ext}",
|
|
1255
1274
|
filetypes=[(kind.upper(), f"*{ext}"), ("All files", "*.*")])
|
|
1256
1275
|
if path:
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Standalone interactive HTML report generator for codetree.
|
|
2
|
+
|
|
3
|
+
Produces a single self-contained ``.html`` file (inline CSS/JS, zero external
|
|
4
|
+
assets, zero dependencies) that mirrors the GUI experience: summary cards, a
|
|
5
|
+
language donut chart, a searchable collapsible file tree and the largest
|
|
6
|
+
files. Safe to open from disk, attach to an email or publish as a CI artifact.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import html as _html
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .core import DirNode, ScanResult, format_size, language_color, sorted_languages
|
|
15
|
+
|
|
16
|
+
MAX_TREE_NODES = 2500 # cap rendered tree entries so huge repos stay usable
|
|
17
|
+
MAX_TOP_FILES = 15
|
|
18
|
+
|
|
19
|
+
_CSS = """
|
|
20
|
+
:root{--bg:#0d1117;--panel:#111826;--card:#161d29;--border:#243041;--fg:#e6edf3;
|
|
21
|
+
--muted:#8b949e;--accent:#3b9eff;--code:#3fb950;--comment:#d29922;--blank:#6e7681}
|
|
22
|
+
*{box-sizing:border-box}
|
|
23
|
+
body{margin:0;background:var(--bg);color:var(--fg);
|
|
24
|
+
font:15px/1.55 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
|
|
25
|
+
a{color:var(--accent);text-decoration:none}
|
|
26
|
+
.top{display:flex;flex-wrap:wrap;gap:18px;align-items:flex-end;
|
|
27
|
+
padding:26px 30px 18px;border-bottom:1px solid var(--border)}
|
|
28
|
+
.top h1{margin:0;font-size:clamp(20px,4vw,30px)}
|
|
29
|
+
.sub{margin:4px 0 0;color:var(--muted);font-size:13px}
|
|
30
|
+
.cards{display:flex;flex-wrap:wrap;gap:10px;margin-left:auto}
|
|
31
|
+
.card{background:var(--card);border:1px solid var(--border);border-radius:10px;
|
|
32
|
+
padding:8px 14px;min-width:92px}
|
|
33
|
+
.card b{display:block;font-size:19px}
|
|
34
|
+
.card span{color:var(--muted);font-size:12px}
|
|
35
|
+
main{padding:22px 30px;max-width:1100px;margin:0 auto}
|
|
36
|
+
.row{display:flex;flex-wrap:wrap;gap:18px;margin-bottom:18px}
|
|
37
|
+
.panel{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:18px}
|
|
38
|
+
.donut-panel{flex:0 0 240px;text-align:center}
|
|
39
|
+
.grow{flex:1 1 340px;min-width:0}
|
|
40
|
+
h2{margin:0 0 12px;font-size:16px}
|
|
41
|
+
.muted{color:var(--muted);font-weight:normal;font-size:13px}
|
|
42
|
+
.donut{width:170px;height:170px}
|
|
43
|
+
.donut circle{fill:none;stroke-width:7;stroke-linecap:butt}
|
|
44
|
+
table{width:100%;border-collapse:collapse;font-size:14px}
|
|
45
|
+
.tscroll{overflow-x:auto}
|
|
46
|
+
th{color:var(--muted);text-align:left;font-weight:normal;padding:4px 8px;border-bottom:1px solid var(--border)}
|
|
47
|
+
td{padding:5px 8px;border-bottom:1px solid var(--border);white-space:nowrap}
|
|
48
|
+
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
|
|
49
|
+
.dot{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:7px;vertical-align:-1px}
|
|
50
|
+
.bar{height:8px;background:#0a0e14;border-radius:5px;overflow:hidden;min-width:80px}
|
|
51
|
+
.bar i{display:block;height:100%;border-radius:5px}
|
|
52
|
+
#filter{width:100%;padding:8px 12px;margin:2px 0 14px;border-radius:8px;font-size:14px;
|
|
53
|
+
background:var(--card);border:1px solid var(--border);color:var(--fg)}
|
|
54
|
+
#filter:focus{outline:1px solid var(--accent)}
|
|
55
|
+
#tree{font-size:14px}
|
|
56
|
+
#tree details{margin:2px 0}
|
|
57
|
+
#tree summary{cursor:pointer;padding:3px 6px;border-radius:6px;list-style:none}
|
|
58
|
+
#tree summary::-webkit-details-marker{display:none}
|
|
59
|
+
#tree summary:hover,#tree .file:hover{background:var(--card)}
|
|
60
|
+
#tree .chev{display:inline-block;width:1.1em;color:var(--muted)}
|
|
61
|
+
#tree details[open]>summary .chev::before{content:"▾"}
|
|
62
|
+
#tree details:not([open])>summary .chev::before{content:"▸"}
|
|
63
|
+
#tree .dname{font-weight:600}
|
|
64
|
+
#tree .file{padding:3px 6px 3px 22px;border-radius:6px}
|
|
65
|
+
#tree .cnt{color:var(--muted);font-size:12px;margin-left:8px}
|
|
66
|
+
#tree .trunc{color:var(--muted);font-style:italic;padding:6px}
|
|
67
|
+
.hidden{display:none}
|
|
68
|
+
.tf{display:grid;grid-template-columns:minmax(120px,1fr) 70px 140px;gap:10px;
|
|
69
|
+
align-items:center;padding:4px 0;font-size:14px}
|
|
70
|
+
.tf .path{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
71
|
+
.tf .lines{text-align:right;font-variant-numeric:tabular-nums;color:var(--muted)}
|
|
72
|
+
footer{color:var(--muted);text-align:center;padding:18px;font-size:13px;border-top:1px solid var(--border)}
|
|
73
|
+
@media (max-width:640px){.top,main{padding-left:14px;padding-right:14px}
|
|
74
|
+
.tf{grid-template-columns:1fr 60px 90px}.donut-panel{flex:1 1 100%}}
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
_JS = """
|
|
78
|
+
(function(){
|
|
79
|
+
var box=document.getElementById('filter');
|
|
80
|
+
if(!box) return;
|
|
81
|
+
box.addEventListener('input',function(){
|
|
82
|
+
var q=box.value.trim().toLowerCase();
|
|
83
|
+
var items=document.querySelectorAll('#tree [data-path]');
|
|
84
|
+
items.forEach(function(el){
|
|
85
|
+
el.classList.toggle('hidden',!!q&&el.dataset.path.toLowerCase().indexOf(q)<0);
|
|
86
|
+
});
|
|
87
|
+
document.querySelectorAll('#tree details').forEach(function(d){
|
|
88
|
+
d.open=q?true:d.hasAttribute('data-open');
|
|
89
|
+
});
|
|
90
|
+
if(!q) return;
|
|
91
|
+
items.forEach(function(el){
|
|
92
|
+
if(el.classList.contains('hidden')) return;
|
|
93
|
+
var p=el.parentElement;
|
|
94
|
+
while(p&&p.id!=='tree'){
|
|
95
|
+
if(p.tagName==='DETAILS'){p.classList.remove('hidden');p.open=true;}
|
|
96
|
+
p=p.parentElement;
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
})();
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _esc(s) -> str:
|
|
105
|
+
return _html.escape(str(s), quote=True)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _rel(path: str, root: str) -> str:
|
|
109
|
+
return os.path.relpath(path, root).replace(os.sep, "/")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _donut(langs, total: int) -> str:
|
|
113
|
+
# r=15.915 -> circumference ~= 100 units, so dasharray values are percents.
|
|
114
|
+
parts = ['<svg class="donut" viewBox="0 0 42 42" role="img" aria-label="Languages share">',
|
|
115
|
+
'<circle cx="21" cy="21" r="15.915" stroke="#243041"></circle>']
|
|
116
|
+
offset = 25.0
|
|
117
|
+
for l in langs:
|
|
118
|
+
pct = l.total / total * 100
|
|
119
|
+
parts.append(f'<circle cx="21" cy="21" r="15.915" stroke="{language_color(l.name)}" '
|
|
120
|
+
f'stroke-dasharray="{pct:.3f} {100 - pct:.3f}" stroke-dashoffset="{offset:.3f}"></circle>')
|
|
121
|
+
offset -= pct
|
|
122
|
+
parts.append('<text x="21" y="20" text-anchor="middle" fill="#e6edf3" font-size="5.2" '
|
|
123
|
+
f'font-weight="600">{total:,}</text>')
|
|
124
|
+
parts.append('<text x="21" y="26" text-anchor="middle" fill="#8b949e" font-size="2.6">lines</text>')
|
|
125
|
+
parts.append("</svg>")
|
|
126
|
+
return "".join(parts)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _tree(node: DirNode, root: str, budget: list, depth: int = 0) -> str:
|
|
130
|
+
if budget[0] <= 0:
|
|
131
|
+
return '<div class="trunc">… tree truncated (too many entries) — use the search box or the GUI</div>'
|
|
132
|
+
budget[0] -= 1
|
|
133
|
+
rel = _rel(node.path, root)
|
|
134
|
+
out = [f'<details{" open data-open" if depth <= 1 else ""} data-path="{_esc(rel)}">'
|
|
135
|
+
f'<summary><span class="chev"></span><span class="dname">{_esc(node.name)}/</span>'
|
|
136
|
+
f'<span class="cnt">{node.file_count:,} files · {node.total:,} lines</span></summary>']
|
|
137
|
+
for d in node.dirs:
|
|
138
|
+
out.append(_tree(d, root, budget, depth + 1))
|
|
139
|
+
for f in node.files:
|
|
140
|
+
if budget[0] <= 0:
|
|
141
|
+
out.append('<div class="trunc">… tree truncated (too many entries)</div>')
|
|
142
|
+
break
|
|
143
|
+
budget[0] -= 1
|
|
144
|
+
frel = _rel(f.path, root)
|
|
145
|
+
out.append(f'<div class="file" data-path="{_esc(frel)}"><span class="dot" '
|
|
146
|
+
f'style="background:{language_color(f.language)}"></span>{_esc(f.name)}'
|
|
147
|
+
f'<span class="cnt">{f.total:,} lines</span></div>')
|
|
148
|
+
out.append("</details>")
|
|
149
|
+
return "".join(out)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def to_html(result: ScanResult, title: str = None) -> str:
|
|
153
|
+
"""Render a scan result as one standalone interactive HTML page."""
|
|
154
|
+
r = result.root
|
|
155
|
+
langs = sorted_languages(result)
|
|
156
|
+
total_lines = result.total_lines
|
|
157
|
+
name = title or f"CodeTree report — {r.name or 'project'}"
|
|
158
|
+
top = sorted(result.files, key=lambda f: f.total, reverse=True)[:MAX_TOP_FILES]
|
|
159
|
+
max_lines = top[0].total if top else 0
|
|
160
|
+
|
|
161
|
+
cards = "".join(
|
|
162
|
+
f'<div class="card"><b>{v}</b><span>{label}</span></div>' for label, v in (
|
|
163
|
+
("Files", f"{r.file_count:,}"), ("Folders", f"{result.folder_count:,}"),
|
|
164
|
+
("Lines", f"{total_lines:,}"), ("Code", f"{r.code:,}"),
|
|
165
|
+
("Comments", f"{r.comment:,}"), ("Blank", f"{r.blank:,}"),
|
|
166
|
+
("Size", format_size(r.size)), ("Scan", f"{result.elapsed:.2f}s"),
|
|
167
|
+
))
|
|
168
|
+
|
|
169
|
+
if langs and total_lines:
|
|
170
|
+
lang_rows = []
|
|
171
|
+
for l in langs:
|
|
172
|
+
share = l.total / total_lines
|
|
173
|
+
lang_rows.append(
|
|
174
|
+
f'<tr><td><span class="dot" style="background:{language_color(l.name)}"></span>'
|
|
175
|
+
f'{_esc(l.name)}</td><td class="num">{l.files:,}</td><td class="num">{l.code:,}</td>'
|
|
176
|
+
f'<td class="num">{l.comment:,}</td><td class="num">{l.blank:,}</td>'
|
|
177
|
+
f'<td class="num">{l.total:,}</td><td class="num">{share:.1%}</td>'
|
|
178
|
+
f'<td><div class="bar"><i style="width:{max(share * 100, 0.6):.1f}%;'
|
|
179
|
+
f'background:{language_color(l.name)}"></i></div></td></tr>')
|
|
180
|
+
langs_html = (f'<div class="panel grow"><h2>Languages <span class="muted">'
|
|
181
|
+
f'({len(langs)} detected)</span></h2>'
|
|
182
|
+
f'<div class="tscroll"><table><tr><th>Language</th><th class="num">Files</th>'
|
|
183
|
+
f'<th class="num">Code</th><th class="num">Comments</th><th class="num">Blank</th>'
|
|
184
|
+
f'<th class="num">Lines</th><th class="num">Share</th><th></th></tr>'
|
|
185
|
+
f'{"".join(lang_rows)}</table></div></div>')
|
|
186
|
+
donut_html = f'<div class="panel donut-panel">{_donut(langs, total_lines)}</div>'
|
|
187
|
+
else:
|
|
188
|
+
donut_html = ""
|
|
189
|
+
langs_html = '<div class="panel grow"><h2>Languages</h2><p class="muted">No files counted.</p></div>'
|
|
190
|
+
|
|
191
|
+
budget = [MAX_TREE_NODES]
|
|
192
|
+
tree_html = _tree(r, r.path, budget)
|
|
193
|
+
|
|
194
|
+
top_rows = []
|
|
195
|
+
for f in top:
|
|
196
|
+
rel = _rel(f.path, r.path)
|
|
197
|
+
top_rows.append(
|
|
198
|
+
f'<div class="tf"><span class="path" title="{_esc(rel)}">{_esc(rel)}</span>'
|
|
199
|
+
f'<span class="lines">{f.total:,}</span><div class="bar"><i style="width:'
|
|
200
|
+
f'{(f.total / max_lines * 100) if max_lines else 0:.1f}%;background:'
|
|
201
|
+
f'{language_color(f.language)}"></i></div></div>')
|
|
202
|
+
top_html = ("" if not top_rows else
|
|
203
|
+
f'<section class="panel" style="margin-top:18px"><h2>Largest files</h2>'
|
|
204
|
+
f'{"".join(top_rows)}</section>')
|
|
205
|
+
|
|
206
|
+
return (
|
|
207
|
+
f'<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n'
|
|
208
|
+
f'<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
|
209
|
+
f'<title>{_esc(name)}</title>\n<style>{_CSS}</style>\n</head>\n<body>\n'
|
|
210
|
+
f'<header class="top"><div><h1>🌳 {_esc(r.name or "project")}</h1>'
|
|
211
|
+
f'<p class="sub">CodeTree report · generated {time.strftime("%Y-%m-%d %H:%M")} · '
|
|
212
|
+
f'{_esc("cancelled early" if result.cancelled else f"{result.elapsed:.2f}s scan")}'
|
|
213
|
+
f'</p></div><div class="cards">{cards}</div></header>\n<main>\n'
|
|
214
|
+
f'<section class="row">{donut_html}{langs_html}</section>\n'
|
|
215
|
+
f'<section class="panel"><h2>Files <span class="muted">({r.file_count:,} files, '
|
|
216
|
+
f'{result.folder_count:,} folders)</span></h2>'
|
|
217
|
+
f'<input id="filter" type="search" placeholder="Filter files and folders…" '
|
|
218
|
+
f'aria-label="Filter files and folders">\n<div id="tree">{tree_html}</div></section>\n'
|
|
219
|
+
f'{top_html}\n</main>\n'
|
|
220
|
+
f'<footer>Generated by <a href="https://github.com/rezamardani01/codetree" '
|
|
221
|
+
f'target="_blank" rel="noopener">CodeTree v{_esc(__version__)}</a> — a living tree of your code.</footer>\n'
|
|
222
|
+
f'<script>{_JS}</script>\n</body>\n</html>\n'
|
|
223
|
+
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codetree-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: See your codebase as a living, animated tree: lines of code, comments and languages per folder and file.
|
|
5
5
|
Home-page: https://github.com/rezamardani01/codetree
|
|
6
6
|
Author: Reza Mardani
|
|
@@ -92,7 +92,7 @@ codetree-gui # same, without a console window on Windows
|
|
|
92
92
|
| **Click a language** | Lights up all leaves written in it |
|
|
93
93
|
| **Click a file in "Largest files"** | Flies the camera to that leaf |
|
|
94
94
|
| **Expand all · Collapse · Fit view** | Overview controls |
|
|
95
|
-
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown |
|
|
95
|
+
| **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown / standalone HTML |
|
|
96
96
|
|
|
97
97
|
Shortcuts: `F5` rescan · `Ctrl+O` browse · `Ctrl+F` search · `Ctrl+E` export JSON · `Esc` clear search.
|
|
98
98
|
|
|
@@ -111,12 +111,14 @@ codetree --cli --top 10 # also list the 10 largest files
|
|
|
111
111
|
codetree -e py -e js -i "*.min.js" # only these extensions, ignore a pattern
|
|
112
112
|
codetree --json report.json # write reports (use - for stdout)
|
|
113
113
|
codetree --csv report.csv --md report.md
|
|
114
|
+
codetree --html report.html # standalone interactive HTML report
|
|
114
115
|
```
|
|
115
116
|
|
|
116
117
|
| Option | Description |
|
|
117
118
|
|---|---|
|
|
118
119
|
| `--cli` | Print to the terminal instead of opening the GUI |
|
|
119
120
|
| `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
|
|
121
|
+
| `--html FILE` | Export a **standalone interactive HTML report** — summary cards, language donut, searchable collapsible tree. Single file, zero dependencies, opens in any browser, great for sharing or CI artifacts (implies `--cli`) |
|
|
120
122
|
| `-i, --ignore PATTERN` | Glob to ignore, repeatable |
|
|
121
123
|
| `-e, --ext EXT` | Only count these extensions, repeatable |
|
|
122
124
|
| `--hidden` | Include hidden files and folders |
|
|
@@ -144,7 +146,7 @@ for lang in result.languages.values():
|
|
|
144
146
|
|
|
145
147
|
- Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
|
|
146
148
|
- `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
|
|
147
|
-
- Patterns in the project
|
|
149
|
+
- Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
|
|
148
150
|
- Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
|
|
149
151
|
|
|
150
152
|
## Development
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
from codetree.cli import main
|
|
7
|
+
from codetree.core import ScanOptions, classify_lines, detect_language, format_size, scan, to_csv, to_json
|
|
8
|
+
from codetree.report import to_html
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def write(root, rel, text="", mode="w"):
|
|
12
|
+
p = os.path.join(root, rel)
|
|
13
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
14
|
+
with open(p, mode, **({"encoding": "utf-8"} if "b" not in mode else {})) as fh:
|
|
15
|
+
fh.write(text)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ClassifyTests(unittest.TestCase):
|
|
19
|
+
def test_python(self):
|
|
20
|
+
src = ["# c\n", "\n", "x = 1\n", '"""doc\n', "more\n", '"""\n', "y = 2 # t\n"]
|
|
21
|
+
self.assertEqual(classify_lines(src, ("#",), (('"""', '"""'),)), (2, 4, 1))
|
|
22
|
+
|
|
23
|
+
def test_c_block(self):
|
|
24
|
+
src = ["/* a\n", " b */\n", "int x; /* open\n", "still */\n", "// z\n"]
|
|
25
|
+
self.assertEqual(classify_lines(src, ("//",), (("/*", "*/"),)), (1, 4, 0))
|
|
26
|
+
|
|
27
|
+
def test_language(self):
|
|
28
|
+
self.assertEqual(detect_language("a.PY"), "Python")
|
|
29
|
+
self.assertEqual(detect_language("Dockerfile"), "Dockerfile")
|
|
30
|
+
self.assertEqual(detect_language("dockerfile.prod"), "Dockerfile")
|
|
31
|
+
self.assertEqual(detect_language("Dockerfile.dev"), "Dockerfile")
|
|
32
|
+
self.assertEqual(detect_language("x.unknown"), "Other")
|
|
33
|
+
|
|
34
|
+
def test_format_size(self):
|
|
35
|
+
self.assertEqual(format_size(0), "0 B")
|
|
36
|
+
self.assertEqual(format_size(1023), "1023 B")
|
|
37
|
+
self.assertEqual(format_size(1024), "1.0 KB")
|
|
38
|
+
self.assertEqual(format_size(5 * 1024 * 1024), "5.0 MB")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ScanTests(unittest.TestCase):
|
|
42
|
+
def setUp(self):
|
|
43
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
44
|
+
self.root = self.tmp.name
|
|
45
|
+
write(self.root, "a.py", "x = 1\n# c\n\n")
|
|
46
|
+
write(self.root, "sub/b.js", "let a;\n")
|
|
47
|
+
write(self.root, "node_modules/pkg/i.js", "ignored\n")
|
|
48
|
+
write(self.root, ".hidden/h.py", "hidden\n")
|
|
49
|
+
write(self.root, ".secret.py", "hidden\n")
|
|
50
|
+
write(self.root, "bin.dat", b"\x00\x01\x02", "wb")
|
|
51
|
+
write(self.root, "latin.txt", "caf\xe9\n".encode("latin-1"), "wb")
|
|
52
|
+
|
|
53
|
+
def tearDown(self):
|
|
54
|
+
self.tmp.cleanup()
|
|
55
|
+
|
|
56
|
+
def test_basic(self):
|
|
57
|
+
r = scan(self.root)
|
|
58
|
+
names = sorted(f.name for f in r.files)
|
|
59
|
+
self.assertEqual(names, ["a.py", "b.js", "latin.txt"]) # latin-1 text still counted
|
|
60
|
+
self.assertEqual(r.skipped_binary, 1)
|
|
61
|
+
self.assertEqual((r.root.code, r.root.comment, r.root.blank), (3, 1, 1))
|
|
62
|
+
self.assertEqual(r.total_files, 3)
|
|
63
|
+
|
|
64
|
+
def test_current_dir_root_files_counted(self):
|
|
65
|
+
old = os.getcwd()
|
|
66
|
+
os.chdir(self.root)
|
|
67
|
+
try:
|
|
68
|
+
self.assertEqual(scan(".").total_files, 3)
|
|
69
|
+
finally:
|
|
70
|
+
os.chdir(old)
|
|
71
|
+
|
|
72
|
+
def test_options(self):
|
|
73
|
+
self.assertEqual(scan(self.root, ScanOptions(include_hidden=True)).total_files, 5)
|
|
74
|
+
self.assertEqual(scan(self.root, ScanOptions(use_default_ignores=False)).total_files, 4)
|
|
75
|
+
self.assertEqual(scan(self.root, ScanOptions(extensions=["py"])).total_files, 1)
|
|
76
|
+
self.assertEqual(scan(self.root, ScanOptions(ignore=["sub"])).total_files, 2)
|
|
77
|
+
|
|
78
|
+
def test_gitignore(self):
|
|
79
|
+
write(self.root, ".gitignore", "*.js\n")
|
|
80
|
+
self.assertEqual(scan(self.root).total_files, 2)
|
|
81
|
+
|
|
82
|
+
def test_gitignore_negation(self):
|
|
83
|
+
write(self.root, ".gitignore", "*.log\n!keep.log\n")
|
|
84
|
+
write(self.root, "drop.log", "x\n")
|
|
85
|
+
write(self.root, "keep.log", "x\n")
|
|
86
|
+
names = sorted(f.name for f in scan(self.root).files)
|
|
87
|
+
self.assertIn("keep.log", names)
|
|
88
|
+
self.assertNotIn("drop.log", names)
|
|
89
|
+
|
|
90
|
+
def test_nested_gitignore(self):
|
|
91
|
+
write(self.root, "sub/.gitignore", "tmp\n")
|
|
92
|
+
write(self.root, "sub/tmp/x.txt", "x\n")
|
|
93
|
+
write(self.root, "tmp/y.txt", "x\n")
|
|
94
|
+
names = sorted(f.name for f in scan(self.root).files)
|
|
95
|
+
self.assertIn("y.txt", names) # the sub/.gitignore rule must not leak to the root
|
|
96
|
+
self.assertNotIn("x.txt", names) # ...but it must apply inside sub/
|
|
97
|
+
|
|
98
|
+
def test_anchored_gitignore(self):
|
|
99
|
+
write(self.root, ".gitignore", "/logs\n")
|
|
100
|
+
write(self.root, "logs/a.txt", "x\n")
|
|
101
|
+
write(self.root, "sub/logs/b.txt", "x\n")
|
|
102
|
+
names = [f.name for f in scan(self.root).files]
|
|
103
|
+
self.assertNotIn("a.txt", names) # '/logs' anchors to the project root only
|
|
104
|
+
self.assertIn("b.txt", names) # ...so sub/logs must survive
|
|
105
|
+
|
|
106
|
+
def test_bom_first_line(self):
|
|
107
|
+
write(self.root, "bom.py", "\ufeff# comment\nx = 1\n")
|
|
108
|
+
names = {f.name: (f.code, f.comment) for f in scan(self.root).files}
|
|
109
|
+
self.assertEqual(names["bom.py"], (1, 1))
|
|
110
|
+
|
|
111
|
+
def test_exports(self):
|
|
112
|
+
r = scan(self.root)
|
|
113
|
+
self.assertEqual(json.loads(to_json(r))["summary"]["files"], 3)
|
|
114
|
+
self.assertEqual(len(to_csv(r).strip().splitlines()), 4)
|
|
115
|
+
|
|
116
|
+
def test_html_report(self):
|
|
117
|
+
h = to_html(scan(self.root))
|
|
118
|
+
low = h.lower()
|
|
119
|
+
self.assertIn("<!doctype html", low)
|
|
120
|
+
self.assertIn("</html>", low)
|
|
121
|
+
self.assertIn("a.py", h) # tree entry
|
|
122
|
+
self.assertIn("Python", h) # language legend
|
|
123
|
+
self.assertIn("largest files", low)
|
|
124
|
+
self.assertIn('id="filter"', h) # search box
|
|
125
|
+
self.assertIn('id="tree"', h)
|
|
126
|
+
|
|
127
|
+
def test_html_report_escapes_names(self):
|
|
128
|
+
write(self.root, "weird<&>.py", "x = 1\n")
|
|
129
|
+
h = to_html(scan(self.root))
|
|
130
|
+
self.assertIn("weird<&>.py", h)
|
|
131
|
+
self.assertNotIn("weird<&>", h)
|
|
132
|
+
|
|
133
|
+
def test_html_report_empty_project(self):
|
|
134
|
+
with tempfile.TemporaryDirectory() as d:
|
|
135
|
+
h = to_html(scan(d))
|
|
136
|
+
self.assertIn("No files counted", h)
|
|
137
|
+
|
|
138
|
+
def test_cancel(self):
|
|
139
|
+
self.assertTrue(scan(self.root, cancel=lambda: True).cancelled)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class CliTests(unittest.TestCase):
|
|
143
|
+
def setUp(self):
|
|
144
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
145
|
+
self.root = self.tmp.name
|
|
146
|
+
write(self.root, "a.py", "x = 1\n")
|
|
147
|
+
|
|
148
|
+
def tearDown(self):
|
|
149
|
+
self.tmp.cleanup()
|
|
150
|
+
|
|
151
|
+
def test_negative_options_rejected(self):
|
|
152
|
+
for flag in ("--top", "--depth", "--max-size"):
|
|
153
|
+
with self.assertRaises(SystemExit, msg=flag) as cm:
|
|
154
|
+
main([flag, "-1", "."])
|
|
155
|
+
self.assertEqual(cm.exception.code, 2)
|
|
156
|
+
|
|
157
|
+
def test_html_export(self):
|
|
158
|
+
out = os.path.join(self.root, "report.html")
|
|
159
|
+
self.assertEqual(main(["--html", out, self.root]), 0)
|
|
160
|
+
with open(out, encoding="utf-8") as fh:
|
|
161
|
+
self.assertIn("<!doctype html", fh.read().lower())
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
unittest.main()
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.3.0"
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
import os
|
|
3
|
-
import tempfile
|
|
4
|
-
import unittest
|
|
5
|
-
|
|
6
|
-
from codetree.core import ScanOptions, classify_lines, detect_language, scan, to_csv, to_json
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def write(root, rel, text="", mode="w"):
|
|
10
|
-
p = os.path.join(root, rel)
|
|
11
|
-
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
12
|
-
with open(p, mode, **({"encoding": "utf-8"} if "b" not in mode else {})) as fh:
|
|
13
|
-
fh.write(text)
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
class ClassifyTests(unittest.TestCase):
|
|
17
|
-
def test_python(self):
|
|
18
|
-
src = ["# c\n", "\n", "x = 1\n", '"""doc\n', "more\n", '"""\n', "y = 2 # t\n"]
|
|
19
|
-
self.assertEqual(classify_lines(src, ("#",), (('"""', '"""'),)), (2, 4, 1))
|
|
20
|
-
|
|
21
|
-
def test_c_block(self):
|
|
22
|
-
src = ["/* a\n", " b */\n", "int x; /* open\n", "still */\n", "// z\n"]
|
|
23
|
-
self.assertEqual(classify_lines(src, ("//",), (("/*", "*/"),)), (1, 4, 0))
|
|
24
|
-
|
|
25
|
-
def test_language(self):
|
|
26
|
-
self.assertEqual(detect_language("a.PY"), "Python")
|
|
27
|
-
self.assertEqual(detect_language("Dockerfile"), "Dockerfile")
|
|
28
|
-
self.assertEqual(detect_language("x.unknown"), "Other")
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
class ScanTests(unittest.TestCase):
|
|
32
|
-
def setUp(self):
|
|
33
|
-
self.tmp = tempfile.TemporaryDirectory()
|
|
34
|
-
self.root = self.tmp.name
|
|
35
|
-
write(self.root, "a.py", "x = 1\n# c\n\n")
|
|
36
|
-
write(self.root, "sub/b.js", "let a;\n")
|
|
37
|
-
write(self.root, "node_modules/pkg/i.js", "ignored\n")
|
|
38
|
-
write(self.root, ".hidden/h.py", "hidden\n")
|
|
39
|
-
write(self.root, ".secret.py", "hidden\n")
|
|
40
|
-
write(self.root, "bin.dat", b"\x00\x01\x02", "wb")
|
|
41
|
-
write(self.root, "latin.txt", "caf\xe9\n".encode("latin-1"), "wb")
|
|
42
|
-
|
|
43
|
-
def tearDown(self):
|
|
44
|
-
self.tmp.cleanup()
|
|
45
|
-
|
|
46
|
-
def test_basic(self):
|
|
47
|
-
r = scan(self.root)
|
|
48
|
-
names = sorted(f.name for f in r.files)
|
|
49
|
-
self.assertEqual(names, ["a.py", "b.js", "latin.txt"]) # latin-1 text still counted
|
|
50
|
-
self.assertEqual(r.skipped_binary, 1)
|
|
51
|
-
self.assertEqual((r.root.code, r.root.comment, r.root.blank), (3, 1, 1))
|
|
52
|
-
self.assertEqual(r.total_files, 3)
|
|
53
|
-
|
|
54
|
-
def test_current_dir_root_files_counted(self):
|
|
55
|
-
old = os.getcwd()
|
|
56
|
-
os.chdir(self.root)
|
|
57
|
-
try:
|
|
58
|
-
self.assertEqual(scan(".").total_files, 3)
|
|
59
|
-
finally:
|
|
60
|
-
os.chdir(old)
|
|
61
|
-
|
|
62
|
-
def test_options(self):
|
|
63
|
-
self.assertEqual(scan(self.root, ScanOptions(include_hidden=True)).total_files, 5)
|
|
64
|
-
self.assertEqual(scan(self.root, ScanOptions(use_default_ignores=False)).total_files, 4)
|
|
65
|
-
self.assertEqual(scan(self.root, ScanOptions(extensions=["py"])).total_files, 1)
|
|
66
|
-
self.assertEqual(scan(self.root, ScanOptions(ignore=["sub"])).total_files, 2)
|
|
67
|
-
|
|
68
|
-
def test_gitignore(self):
|
|
69
|
-
write(self.root, ".gitignore", "*.js\n")
|
|
70
|
-
self.assertEqual(scan(self.root).total_files, 2)
|
|
71
|
-
|
|
72
|
-
def test_exports(self):
|
|
73
|
-
r = scan(self.root)
|
|
74
|
-
self.assertEqual(json.loads(to_json(r))["summary"]["files"], 3)
|
|
75
|
-
self.assertEqual(len(to_csv(r).strip().splitlines()), 4)
|
|
76
|
-
|
|
77
|
-
def test_cancel(self):
|
|
78
|
-
self.assertTrue(scan(self.root, cancel=lambda: True).cancelled)
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if __name__ == "__main__":
|
|
82
|
-
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|