codetree-cli 0.3.0__tar.gz → 0.5.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codetree-cli
3
- Version: 0.3.0
3
+ Version: 0.5.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,20 @@ 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
115
+ codetree --watch # live dashboard: re-renders when the project changes
116
+ codetree --watch 5 # same, checking every 5 seconds
114
117
  ```
115
118
 
119
+ In watch mode, export flags write the initial snapshot once. If an export goes
120
+ to stdout (`-`), the live dashboard goes to stderr.
121
+
116
122
  | Option | Description |
117
123
  |---|---|
118
124
  | `--cli` | Print to the terminal instead of opening the GUI |
119
125
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
126
+ | `--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`) |
127
+ | `--watch [SEC]` | **Live terminal dashboard** — keeps re-scanning and re-renders only when the project actually changes (default every 2s). Line counts move as you code; `Ctrl+C` to stop (implies `--cli`) |
120
128
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
121
129
  | `-e, --ext EXT` | Only count these extensions, repeatable |
122
130
  | `--hidden` | Include hidden files and folders |
@@ -144,7 +152,7 @@ for lang in result.languages.values():
144
152
 
145
153
  - Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
146
154
  - `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
147
- - Patterns in the project's root `.gitignore` are respected.
155
+ - Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
148
156
  - Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
149
157
 
150
158
  ## 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,20 @@ 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
89
+ codetree --watch # live dashboard: re-renders when the project changes
90
+ codetree --watch 5 # same, checking every 5 seconds
88
91
  ```
89
92
 
93
+ In watch mode, export flags write the initial snapshot once. If an export goes
94
+ to stdout (`-`), the live dashboard goes to stderr.
95
+
90
96
  | Option | Description |
91
97
  |---|---|
92
98
  | `--cli` | Print to the terminal instead of opening the GUI |
93
99
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
100
+ | `--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`) |
101
+ | `--watch [SEC]` | **Live terminal dashboard** — keeps re-scanning and re-renders only when the project actually changes (default every 2s). Line counts move as you code; `Ctrl+C` to stop (implies `--cli`) |
94
102
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
95
103
  | `-e, --ext EXT` | Only count these extensions, repeatable |
96
104
  | `--hidden` | Include hidden files and folders |
@@ -118,7 +126,7 @@ for lang in result.languages.values():
118
126
 
119
127
  - Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
120
128
  - `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
121
- - Patterns in the project's root `.gitignore` are respected.
129
+ - Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
122
130
  - Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
123
131
 
124
132
  ## Development
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -1,12 +1,16 @@
1
1
  """Command line entry point. Opens the GUI by default; ``--cli`` prints to the terminal."""
2
2
 
3
3
  import argparse
4
+ from contextlib import redirect_stdout
5
+ import math
4
6
  import os
5
7
  import sys
8
+ import time
6
9
 
7
10
  from . import __version__
8
11
  from .core import (DirNode, ScanOptions, ScanResult, format_size, scan, sorted_languages,
9
12
  to_csv, to_json, to_markdown)
13
+ from .report import to_html
10
14
 
11
15
  SORT_KEYS = {
12
16
  "name": lambda n: n.name.lower(),
@@ -80,6 +84,10 @@ def build_parser() -> argparse.ArgumentParser:
80
84
  p.add_argument("--json", metavar="FILE", help="write a JSON report ('-' for stdout); implies --cli")
81
85
  p.add_argument("--csv", metavar="FILE", help="write a CSV report ('-' for stdout); implies --cli")
82
86
  p.add_argument("--md", metavar="FILE", help="write a Markdown report ('-' for stdout); implies --cli")
87
+ p.add_argument("--html", metavar="FILE", help="write a standalone interactive HTML report ('-' for stdout); implies --cli")
88
+ p.add_argument("--watch", nargs="?", const=2.0, default=None, type=float, metavar="SEC",
89
+ help="live terminal dashboard: re-render whenever the project changes "
90
+ "(optional interval in seconds, default 2); implies --cli")
83
91
  p.add_argument("-i", "--ignore", action="append", default=[], metavar="PATTERN",
84
92
  help="glob pattern to ignore (repeatable), e.g. -i '*.min.js' -i tests")
85
93
  p.add_argument("-e", "--ext", action="append", default=[], metavar="EXT",
@@ -105,8 +113,50 @@ def _emit(target: str, text: str) -> None:
105
113
  print(f"Saved {target}", file=sys.stderr)
106
114
 
107
115
 
116
+ def _result_signature(result: ScanResult) -> tuple:
117
+ """Cheap fingerprint of a scan, so ``--watch`` only re-renders on real change."""
118
+ # scan() returns fresh FileStat objects in deterministic traversal order.
119
+ # Their dataclass equality includes the per-file code/comment/blank counts.
120
+ return (result.files, result.folder_count, result.skipped_binary,
121
+ result.skipped_large, result.errors)
122
+
123
+
124
+ def _render(result: ScanResult, args, color: bool, interval: float) -> None:
125
+ if sys.stdout.isatty():
126
+ sys.stdout.write("\033[2J\033[H") # clear screen, home cursor
127
+ _print_report(result, args, _Style(color))
128
+ stamp = time.strftime("%H:%M:%S")
129
+ footer = f"watching every {interval:g}s · updated {stamp} · Ctrl+C to exit"
130
+ print(_Style(color)(f"\n{footer}", "90"))
131
+ sys.stdout.flush()
132
+
133
+
134
+ def _watch_loop(result: ScanResult, path: str, options: ScanOptions, args, color: bool) -> None:
135
+ """Re-scan periodically and re-render the report only when something changed."""
136
+ interval = args.watch
137
+ previous = _result_signature(result)
138
+ _render(result, args, color, interval)
139
+ while True:
140
+ time.sleep(interval)
141
+ fresh = scan(path, options)
142
+ current = _result_signature(fresh)
143
+ if current == previous:
144
+ continue
145
+ previous = current
146
+ _render(fresh, args, color, interval)
147
+
148
+
108
149
  def main(argv=None) -> int:
109
- args = build_parser().parse_args(argv)
150
+ parser = build_parser()
151
+ args = parser.parse_args(argv)
152
+ if args.depth < 0:
153
+ parser.error("--depth must be >= 0")
154
+ if args.top < 0:
155
+ parser.error("--top must be >= 0")
156
+ if args.max_size < 0:
157
+ parser.error("--max-size must be >= 0")
158
+ if args.watch is not None and (not math.isfinite(args.watch) or args.watch < 0.5):
159
+ parser.error("--watch interval must be finite and >= 0.5 seconds")
110
160
  path = os.path.abspath(args.path)
111
161
  if not os.path.isdir(path):
112
162
  print(f"codetree: '{args.path}' is not a directory.", file=sys.stderr)
@@ -121,8 +171,8 @@ def main(argv=None) -> int:
121
171
  max_size=int(args.max_size * 1024 * 1024),
122
172
  )
123
173
 
124
- exports = [(args.json, to_json), (args.csv, to_csv), (args.md, to_markdown)]
125
- wants_cli = args.cli or any(t for t, _ in exports)
174
+ exports = [(args.json, to_json), (args.csv, to_csv), (args.md, to_markdown), (args.html, to_html)]
175
+ wants_cli = args.cli or args.watch is not None or any(t for t, _ in exports)
126
176
 
127
177
  if not wants_cli:
128
178
  try:
@@ -147,10 +197,18 @@ def main(argv=None) -> int:
147
197
  for target, fn in exports:
148
198
  if target:
149
199
  _emit(target, fn(result))
150
- if not stdout_taken:
151
- color = not args.no_color and sys.stdout.isatty() and "NO_COLOR" not in os.environ
152
- if color and os.name == "nt":
200
+ if args.watch is not None or not stdout_taken:
201
+ stream = sys.stderr if stdout_taken else sys.stdout
202
+ color = not args.no_color and stream.isatty() and "NO_COLOR" not in os.environ
203
+ if stream.isatty() and os.name == "nt" and (color or args.watch is not None):
153
204
  os.system("") # enable ANSI escapes on Windows consoles
205
+ if args.watch is not None:
206
+ try:
207
+ with redirect_stdout(stream):
208
+ _watch_loop(result, path, options, args, color)
209
+ except KeyboardInterrupt:
210
+ pass # Ctrl+C is the normal way out of watch mode
211
+ return 0
154
212
  _print_report(result, args, _Style(color))
155
213
  return 0
156
214
 
@@ -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
- with open(path, "r", encoding="utf-8", errors="replace") as fh:
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", errors="replace") as fh:
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 and not line.startswith(("#", "!")):
242
- patterns.append(line.rstrip("/").lstrip("/"))
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
- git_patterns = _load_gitignore(root_path) if opts.respect_gitignore else []
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 + git_patterns:
316
+ for pat in user_ignore:
278
317
  if fnmatch.fnmatch(name, pat) or fnmatch.fnmatch(rel, pat):
279
318
  return True
280
- return False
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
- entries = sorted(os.scandir(node.path), key=lambda e: e.name.lower())
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
- return json.load(fh)
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, count = [self.result.root], 0
649
- count = self.visible_count_estimate([self.result.root]) - len([n for n in self.vnodes.values() if not n.dying])
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.0
3
+ Version: 0.5.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,20 @@ 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
115
+ codetree --watch # live dashboard: re-renders when the project changes
116
+ codetree --watch 5 # same, checking every 5 seconds
114
117
  ```
115
118
 
119
+ In watch mode, export flags write the initial snapshot once. If an export goes
120
+ to stdout (`-`), the live dashboard goes to stderr.
121
+
116
122
  | Option | Description |
117
123
  |---|---|
118
124
  | `--cli` | Print to the terminal instead of opening the GUI |
119
125
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
126
+ | `--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`) |
127
+ | `--watch [SEC]` | **Live terminal dashboard** — keeps re-scanning and re-renders only when the project actually changes (default every 2s). Line counts move as you code; `Ctrl+C` to stop (implies `--cli`) |
120
128
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
121
129
  | `-e, --ext EXT` | Only count these extensions, repeatable |
122
130
  | `--hidden` | Include hidden files and folders |
@@ -144,7 +152,7 @@ for lang in result.languages.values():
144
152
 
145
153
  - Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
146
154
  - `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
147
- - Patterns in the project's root `.gitignore` are respected.
155
+ - Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
148
156
  - Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
149
157
 
150
158
  ## Development
@@ -7,6 +7,7 @@ codetree/__main__.py
7
7
  codetree/cli.py
8
8
  codetree/core.py
9
9
  codetree/gui.py
10
+ codetree/report.py
10
11
  codetree_cli.egg-info/PKG-INFO
11
12
  codetree_cli.egg-info/SOURCES.txt
12
13
  codetree_cli.egg-info/dependency_links.txt
@@ -0,0 +1,231 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import tempfile
5
+ import unittest
6
+ from contextlib import redirect_stderr, redirect_stdout
7
+ from unittest.mock import patch
8
+
9
+ from codetree.cli import _result_signature, build_parser, main
10
+ from codetree.core import ScanOptions, classify_lines, detect_language, format_size, scan, to_csv, to_json
11
+ from codetree.report import to_html
12
+
13
+
14
+ def write(root, rel, text="", mode="w"):
15
+ p = os.path.join(root, rel)
16
+ os.makedirs(os.path.dirname(p), exist_ok=True)
17
+ with open(p, mode, **({"encoding": "utf-8"} if "b" not in mode else {})) as fh:
18
+ fh.write(text)
19
+
20
+
21
+ class ClassifyTests(unittest.TestCase):
22
+ def test_python(self):
23
+ src = ["# c\n", "\n", "x = 1\n", '"""doc\n', "more\n", '"""\n', "y = 2 # t\n"]
24
+ self.assertEqual(classify_lines(src, ("#",), (('"""', '"""'),)), (2, 4, 1))
25
+
26
+ def test_c_block(self):
27
+ src = ["/* a\n", " b */\n", "int x; /* open\n", "still */\n", "// z\n"]
28
+ self.assertEqual(classify_lines(src, ("//",), (("/*", "*/"),)), (1, 4, 0))
29
+
30
+ def test_language(self):
31
+ self.assertEqual(detect_language("a.PY"), "Python")
32
+ self.assertEqual(detect_language("Dockerfile"), "Dockerfile")
33
+ self.assertEqual(detect_language("dockerfile.prod"), "Dockerfile")
34
+ self.assertEqual(detect_language("Dockerfile.dev"), "Dockerfile")
35
+ self.assertEqual(detect_language("x.unknown"), "Other")
36
+
37
+ def test_format_size(self):
38
+ self.assertEqual(format_size(0), "0 B")
39
+ self.assertEqual(format_size(1023), "1023 B")
40
+ self.assertEqual(format_size(1024), "1.0 KB")
41
+ self.assertEqual(format_size(5 * 1024 * 1024), "5.0 MB")
42
+
43
+
44
+ class ScanTests(unittest.TestCase):
45
+ def setUp(self):
46
+ self.tmp = tempfile.TemporaryDirectory()
47
+ self.root = self.tmp.name
48
+ write(self.root, "a.py", "x = 1\n# c\n\n")
49
+ write(self.root, "sub/b.js", "let a;\n")
50
+ write(self.root, "node_modules/pkg/i.js", "ignored\n")
51
+ write(self.root, ".hidden/h.py", "hidden\n")
52
+ write(self.root, ".secret.py", "hidden\n")
53
+ write(self.root, "bin.dat", b"\x00\x01\x02", "wb")
54
+ write(self.root, "latin.txt", "caf\xe9\n".encode("latin-1"), "wb")
55
+
56
+ def tearDown(self):
57
+ self.tmp.cleanup()
58
+
59
+ def test_basic(self):
60
+ r = scan(self.root)
61
+ names = sorted(f.name for f in r.files)
62
+ self.assertEqual(names, ["a.py", "b.js", "latin.txt"]) # latin-1 text still counted
63
+ self.assertEqual(r.skipped_binary, 1)
64
+ self.assertEqual((r.root.code, r.root.comment, r.root.blank), (3, 1, 1))
65
+ self.assertEqual(r.total_files, 3)
66
+
67
+ def test_current_dir_root_files_counted(self):
68
+ old = os.getcwd()
69
+ os.chdir(self.root)
70
+ try:
71
+ self.assertEqual(scan(".").total_files, 3)
72
+ finally:
73
+ os.chdir(old)
74
+
75
+ def test_options(self):
76
+ self.assertEqual(scan(self.root, ScanOptions(include_hidden=True)).total_files, 5)
77
+ self.assertEqual(scan(self.root, ScanOptions(use_default_ignores=False)).total_files, 4)
78
+ self.assertEqual(scan(self.root, ScanOptions(extensions=["py"])).total_files, 1)
79
+ self.assertEqual(scan(self.root, ScanOptions(ignore=["sub"])).total_files, 2)
80
+
81
+ def test_gitignore(self):
82
+ write(self.root, ".gitignore", "*.js\n")
83
+ self.assertEqual(scan(self.root).total_files, 2)
84
+
85
+ def test_gitignore_negation(self):
86
+ write(self.root, ".gitignore", "*.log\n!keep.log\n")
87
+ write(self.root, "drop.log", "x\n")
88
+ write(self.root, "keep.log", "x\n")
89
+ names = sorted(f.name for f in scan(self.root).files)
90
+ self.assertIn("keep.log", names)
91
+ self.assertNotIn("drop.log", names)
92
+
93
+ def test_nested_gitignore(self):
94
+ write(self.root, "sub/.gitignore", "tmp\n")
95
+ write(self.root, "sub/tmp/x.txt", "x\n")
96
+ write(self.root, "tmp/y.txt", "x\n")
97
+ names = sorted(f.name for f in scan(self.root).files)
98
+ self.assertIn("y.txt", names) # the sub/.gitignore rule must not leak to the root
99
+ self.assertNotIn("x.txt", names) # ...but it must apply inside sub/
100
+
101
+ def test_anchored_gitignore(self):
102
+ write(self.root, ".gitignore", "/logs\n")
103
+ write(self.root, "logs/a.txt", "x\n")
104
+ write(self.root, "sub/logs/b.txt", "x\n")
105
+ names = [f.name for f in scan(self.root).files]
106
+ self.assertNotIn("a.txt", names) # '/logs' anchors to the project root only
107
+ self.assertIn("b.txt", names) # ...so sub/logs must survive
108
+
109
+ def test_bom_first_line(self):
110
+ write(self.root, "bom.py", "\ufeff# comment\nx = 1\n")
111
+ names = {f.name: (f.code, f.comment) for f in scan(self.root).files}
112
+ self.assertEqual(names["bom.py"], (1, 1))
113
+
114
+ def test_exports(self):
115
+ r = scan(self.root)
116
+ self.assertEqual(json.loads(to_json(r))["summary"]["files"], 3)
117
+ self.assertEqual(len(to_csv(r).strip().splitlines()), 4)
118
+
119
+ def test_html_report(self):
120
+ h = to_html(scan(self.root))
121
+ low = h.lower()
122
+ self.assertIn("<!doctype html", low)
123
+ self.assertIn("</html>", low)
124
+ self.assertIn("a.py", h) # tree entry
125
+ self.assertIn("Python", h) # language legend
126
+ self.assertIn("largest files", low)
127
+ self.assertIn('id="filter"', h) # search box
128
+ self.assertIn('id="tree"', h)
129
+
130
+ def test_html_report_escapes_names(self):
131
+ result = scan(self.root)
132
+ # Exercise HTML metacharacters even on filesystems that forbid them.
133
+ file = next(f for f in result.files if f.name == "a.py")
134
+ file.name = "weird<&>.py"
135
+ file.path = os.path.join(self.root, file.name)
136
+ h = to_html(result)
137
+ self.assertIn("weird&lt;&amp;&gt;.py", h)
138
+ self.assertNotIn("weird<&>", h)
139
+
140
+ def test_html_report_empty_project(self):
141
+ with tempfile.TemporaryDirectory() as d:
142
+ h = to_html(scan(d))
143
+ self.assertIn("No files counted", h)
144
+
145
+ def test_cancel(self):
146
+ self.assertTrue(scan(self.root, cancel=lambda: True).cancelled)
147
+
148
+
149
+ class CliTests(unittest.TestCase):
150
+ def setUp(self):
151
+ self.tmp = tempfile.TemporaryDirectory()
152
+ self.root = self.tmp.name
153
+ write(self.root, "a.py", "x = 1\n")
154
+
155
+ def tearDown(self):
156
+ self.tmp.cleanup()
157
+
158
+ def test_negative_options_rejected(self):
159
+ for flag in ("--top", "--depth", "--max-size"):
160
+ with self.assertRaises(SystemExit, msg=flag) as cm:
161
+ main([flag, "-1", "."])
162
+ self.assertEqual(cm.exception.code, 2)
163
+
164
+ def test_html_export(self):
165
+ out = os.path.join(self.root, "report.html")
166
+ self.assertEqual(main(["--html", out, self.root]), 0)
167
+ with open(out, encoding="utf-8") as fh:
168
+ self.assertIn("<!doctype html", fh.read().lower())
169
+
170
+
171
+ class WatchTests(unittest.TestCase):
172
+ def setUp(self):
173
+ self.tmp = tempfile.TemporaryDirectory()
174
+ self.root = self.tmp.name
175
+ write(self.root, "a.py", "x = 1\n")
176
+
177
+ def tearDown(self):
178
+ self.tmp.cleanup()
179
+
180
+ def test_watch_flag_parsing(self):
181
+ p = build_parser()
182
+ self.assertIsNone(p.parse_args([]).watch)
183
+ self.assertEqual(p.parse_args(["--watch"]).watch, 2.0)
184
+ self.assertEqual(p.parse_args(["--watch", "5"]).watch, 5.0)
185
+
186
+ def test_watch_interval_validated(self):
187
+ for value in ("0.1", "nan", "inf"):
188
+ with self.subTest(value=value), self.assertRaises(SystemExit) as cm:
189
+ main(["--watch", value, self.root])
190
+ self.assertEqual(cm.exception.code, 2)
191
+
192
+ def test_signature_stable_when_unchanged(self):
193
+ sig1 = _result_signature(scan(self.root))
194
+ sig2 = _result_signature(scan(self.root))
195
+ self.assertEqual(sig1, sig2)
196
+
197
+ def test_signature_detects_edits_and_new_files(self):
198
+ sig_before = _result_signature(scan(self.root))
199
+ write(self.root, "a.py", "x = 2\n# new comment\n")
200
+ sig_edited = _result_signature(scan(self.root))
201
+ self.assertNotEqual(sig_before, sig_edited)
202
+ write(self.root, "new.js", "let a;\n")
203
+ self.assertNotEqual(sig_edited, _result_signature(scan(self.root)))
204
+
205
+ def test_watch_refreshes_only_on_report_changes(self):
206
+ write(self.root, "a.py", "#x\n")
207
+ write(self.root, "b.js", "xx\n")
208
+ def ticks():
209
+ yield # first rescan is unchanged
210
+ write(self.root, "a.py", "xx\n")
211
+ write(self.root, "b.js", "//\n")
212
+ yield # per-language counts change, totals and sizes stay the same
213
+ raise KeyboardInterrupt
214
+
215
+ output = io.StringIO()
216
+ with redirect_stdout(output), patch("codetree.cli.time.sleep", side_effect=ticks()):
217
+ self.assertEqual(main([self.root, "--watch"]), 0)
218
+ self.assertEqual(output.getvalue().count("watching every"), 2)
219
+ self.assertNotIn("\033", output.getvalue())
220
+
221
+ def test_watch_keeps_stdout_export_parseable(self):
222
+ output, dashboard = io.StringIO(), io.StringIO()
223
+ with redirect_stdout(output), redirect_stderr(dashboard), \
224
+ patch("codetree.cli.time.sleep", side_effect=KeyboardInterrupt):
225
+ self.assertEqual(main([self.root, "--watch", "--json", "-"]), 0)
226
+ self.assertEqual(json.loads(output.getvalue())["summary"]["files"], 1)
227
+ self.assertIn("watching every", dashboard.getvalue())
228
+
229
+
230
+ if __name__ == "__main__":
231
+ 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