codetree-cli 0.4.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.4.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
@@ -112,13 +112,19 @@ codetree -e py -e js -i "*.min.js" # only these extensions, ignore a patter
112
112
  codetree --json report.json # write reports (use - for stdout)
113
113
  codetree --csv report.csv --md report.md
114
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
115
117
  ```
116
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
+
117
122
  | Option | Description |
118
123
  |---|---|
119
124
  | `--cli` | Print to the terminal instead of opening the GUI |
120
125
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
121
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`) |
122
128
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
123
129
  | `-e, --ext EXT` | Only count these extensions, repeatable |
124
130
  | `--hidden` | Include hidden files and folders |
@@ -86,13 +86,19 @@ codetree -e py -e js -i "*.min.js" # only these extensions, ignore a patter
86
86
  codetree --json report.json # write reports (use - for stdout)
87
87
  codetree --csv report.csv --md report.md
88
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
89
91
  ```
90
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
+
91
96
  | Option | Description |
92
97
  |---|---|
93
98
  | `--cli` | Print to the terminal instead of opening the GUI |
94
99
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
95
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`) |
96
102
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
97
103
  | `-e, --ext EXT` | Only count these extensions, repeatable |
98
104
  | `--hidden` | Include hidden files and folders |
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -1,8 +1,11 @@
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,
@@ -82,6 +85,9 @@ def build_parser() -> argparse.ArgumentParser:
82
85
  p.add_argument("--csv", metavar="FILE", help="write a CSV report ('-' for stdout); implies --cli")
83
86
  p.add_argument("--md", metavar="FILE", help="write a Markdown report ('-' for stdout); implies --cli")
84
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")
85
91
  p.add_argument("-i", "--ignore", action="append", default=[], metavar="PATTERN",
86
92
  help="glob pattern to ignore (repeatable), e.g. -i '*.min.js' -i tests")
87
93
  p.add_argument("-e", "--ext", action="append", default=[], metavar="EXT",
@@ -107,6 +113,39 @@ def _emit(target: str, text: str) -> None:
107
113
  print(f"Saved {target}", file=sys.stderr)
108
114
 
109
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
+
110
149
  def main(argv=None) -> int:
111
150
  parser = build_parser()
112
151
  args = parser.parse_args(argv)
@@ -116,6 +155,8 @@ def main(argv=None) -> int:
116
155
  parser.error("--top must be >= 0")
117
156
  if args.max_size < 0:
118
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")
119
160
  path = os.path.abspath(args.path)
120
161
  if not os.path.isdir(path):
121
162
  print(f"codetree: '{args.path}' is not a directory.", file=sys.stderr)
@@ -131,7 +172,7 @@ def main(argv=None) -> int:
131
172
  )
132
173
 
133
174
  exports = [(args.json, to_json), (args.csv, to_csv), (args.md, to_markdown), (args.html, to_html)]
134
- wants_cli = args.cli or any(t for t, _ in exports)
175
+ wants_cli = args.cli or args.watch is not None or any(t for t, _ in exports)
135
176
 
136
177
  if not wants_cli:
137
178
  try:
@@ -156,10 +197,18 @@ def main(argv=None) -> int:
156
197
  for target, fn in exports:
157
198
  if target:
158
199
  _emit(target, fn(result))
159
- if not stdout_taken:
160
- color = not args.no_color and sys.stdout.isatty() and "NO_COLOR" not in os.environ
161
- 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):
162
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
163
212
  _print_report(result, args, _Style(color))
164
213
  return 0
165
214
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codetree-cli
3
- Version: 0.4.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
@@ -112,13 +112,19 @@ codetree -e py -e js -i "*.min.js" # only these extensions, ignore a patter
112
112
  codetree --json report.json # write reports (use - for stdout)
113
113
  codetree --csv report.csv --md report.md
114
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
115
117
  ```
116
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
+
117
122
  | Option | Description |
118
123
  |---|---|
119
124
  | `--cli` | Print to the terminal instead of opening the GUI |
120
125
  | `--json / --csv / --md FILE` | Export a report (implies `--cli`) |
121
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`) |
122
128
  | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
123
129
  | `-e, --ext EXT` | Only count these extensions, repeatable |
124
130
  | `--hidden` | Include hidden files and folders |
@@ -1,9 +1,12 @@
1
+ import io
1
2
  import json
2
3
  import os
3
4
  import tempfile
4
5
  import unittest
6
+ from contextlib import redirect_stderr, redirect_stdout
7
+ from unittest.mock import patch
5
8
 
6
- from codetree.cli import main
9
+ from codetree.cli import _result_signature, build_parser, main
7
10
  from codetree.core import ScanOptions, classify_lines, detect_language, format_size, scan, to_csv, to_json
8
11
  from codetree.report import to_html
9
12
 
@@ -125,8 +128,12 @@ class ScanTests(unittest.TestCase):
125
128
  self.assertIn('id="tree"', h)
126
129
 
127
130
  def test_html_report_escapes_names(self):
128
- write(self.root, "weird<&>.py", "x = 1\n")
129
- h = to_html(scan(self.root))
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)
130
137
  self.assertIn("weird&lt;&amp;&gt;.py", h)
131
138
  self.assertNotIn("weird<&>", h)
132
139
 
@@ -161,5 +168,64 @@ class CliTests(unittest.TestCase):
161
168
  self.assertIn("<!doctype html", fh.read().lower())
162
169
 
163
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
+
164
230
  if __name__ == "__main__":
165
231
  unittest.main()
@@ -1 +0,0 @@
1
- __version__ = "0.4.0"
File without changes
File without changes
File without changes