codetree-cli 0.2.2__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Reza Mardani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: codetree-cli
3
+ Version: 0.4.0
4
+ Summary: See your codebase as a living, animated tree: lines of code, comments and languages per folder and file.
5
+ Home-page: https://github.com/rezamardani01/codetree
6
+ Author: Reza Mardani
7
+ Author-email: mardanireza30@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Environment :: X11 Applications
12
+ Classifier: Environment :: Win32 (MS Windows)
13
+ Classifier: Topic :: Software Development
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-python
25
+ Dynamic: summary
26
+
27
+ <div align="center">
28
+
29
+ # 🌳 CodeTree
30
+
31
+ **See your codebase as a living, animated tree.**
32
+
33
+ Folders grow into branches, files bloom as leaves — sized by lines of code, colored by language.
34
+
35
+ [![PyPI](https://img.shields.io/pypi/v/codetree-cli?color=3b9eff&label=PyPI)](https://pypi.org/project/codetree-cli/)
36
+ [![Python](https://img.shields.io/badge/python-3.8%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
37
+ [![License: MIT](https://img.shields.io/badge/license-MIT-3fb950)](LICENSE)
38
+ [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-8b949e)](#installation)
39
+ [![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen)](#why-codetree)
40
+
41
+ <img src="https://raw.githubusercontent.com/rezamardani01/codetree/main/docs/screenshot.png" alt="CodeTree showing the Python standard library as a radial tree" width="900">
42
+
43
+ </div>
44
+
45
+ ---
46
+
47
+ ## Why CodeTree?
48
+
49
+ Line counters give you a table. CodeTree gives you a **map**: you instantly see which folders are heavy, which files dominate, and how comments, blank lines and code are balanced — and you can explore it by clicking, zooming and searching.
50
+
51
+ - 🌱 **A tree, not a table** — an animated radial tree that grows from the trunk outward.
52
+ - 🎨 **Language-aware** — 40+ languages detected, every line classified as *code*, *comment* or *blank*.
53
+ - ⚡ **Fast** — scans thousands of files in a couple of seconds, in the background, with a live progress view.
54
+ - 🧰 **Zero dependencies** — pure Python standard library (Tkinter for the GUI).
55
+ - 🖥️ **GUI by default, terminal when you need it** — scriptable with JSON / CSV / Markdown export.
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ pip install codetree-cli
61
+ ```
62
+
63
+ From source:
64
+
65
+ ```bash
66
+ git clone https://github.com/rezamardani01/codetree.git
67
+ cd codetree
68
+ pip install .
69
+ ```
70
+
71
+ > Requires Python 3.8+. The GUI uses Tkinter, which ships with the official Python installers
72
+ > (on some Linux distributions install it with e.g. `sudo apt install python3-tk`).
73
+
74
+ ## Usage
75
+
76
+ ```bash
77
+ codetree # open the GUI on the current folder
78
+ codetree path/to/project # open the GUI on a specific folder
79
+ codetree-gui # same, without a console window on Windows
80
+ ```
81
+
82
+ ### In the window
83
+
84
+ | Action | What it does |
85
+ |---|---|
86
+ | **Click a folder** | Grow or fold its branch (animated) |
87
+ | **Drag / mouse wheel** | Pan / zoom |
88
+ | **Hover a node** | Highlights its path to the trunk and shows lines, code/comment/blank split, size and share of the project |
89
+ | **Double-click a file** | Opens it in your default editor |
90
+ | **Right-click** | Open, show in folder, copy path |
91
+ | **Search box** | Prunes the tree to matching files and folders |
92
+ | **Click a language** | Lights up all leaves written in it |
93
+ | **Click a file in "Largest files"** | Flies the camera to that leaf |
94
+ | **Expand all · Collapse · Fit view** | Overview controls |
95
+ | **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown / standalone HTML |
96
+
97
+ Shortcuts: `F5` rescan · `Ctrl+O` browse · `Ctrl+F` search · `Ctrl+E` export JSON · `Esc` clear search.
98
+
99
+ ### Reading the tree
100
+
101
+ - **Trunk** (center) = the project root.
102
+ - **Branches / green nodes** = folders. Thicker branch = more lines. The number on a folded node is how many items it hides.
103
+ - **Leaves** = files, arranged in a sunflower pattern at the end of their branch. **Bigger leaf = more lines. Color = language.**
104
+
105
+ ### Terminal mode
106
+
107
+ ```bash
108
+ codetree --cli # tree + language table + summary
109
+ codetree --cli --depth 2 --sort lines # limit depth, biggest first
110
+ codetree --cli --top 10 # also list the 10 largest files
111
+ codetree -e py -e js -i "*.min.js" # only these extensions, ignore a pattern
112
+ codetree --json report.json # write reports (use - for stdout)
113
+ codetree --csv report.csv --md report.md
114
+ codetree --html report.html # standalone interactive HTML report
115
+ ```
116
+
117
+ | Option | Description |
118
+ |---|---|
119
+ | `--cli` | Print to the terminal instead of opening the GUI |
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`) |
122
+ | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
123
+ | `-e, --ext EXT` | Only count these extensions, repeatable |
124
+ | `--hidden` | Include hidden files and folders |
125
+ | `--no-gitignore` | Do not read `.gitignore` |
126
+ | `--no-default-ignores` | Do not skip `node_modules`, `venv`, `build`, … |
127
+ | `--max-size MB` | Skip files larger than this (default 5) |
128
+ | `--sort name\|lines\|code`, `--depth N`, `--top N` | Terminal tree options |
129
+ | `--no-color` | Disable colors |
130
+ | `-V, --version` | Show the version |
131
+
132
+ If the GUI cannot start (for example over SSH without a display), CodeTree automatically falls back to terminal output.
133
+
134
+ ### Use it as a library
135
+
136
+ ```python
137
+ from codetree.core import scan, ScanOptions
138
+
139
+ result = scan(".", ScanOptions(extensions=["py"], ignore=["tests"]))
140
+ print(result.total_files, result.total_lines)
141
+ for lang in result.languages.values():
142
+ print(lang.name, lang.code, lang.comment, lang.blank)
143
+ ```
144
+
145
+ ## What gets counted
146
+
147
+ - Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
148
+ - `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
149
+ - Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
150
+ - Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
151
+
152
+ ## Development
153
+
154
+ ```bash
155
+ git clone https://github.com/rezamardani01/codetree.git
156
+ cd codetree
157
+ python -m unittest discover -s tests -t .
158
+ python -m codetree . # run from source
159
+ ```
160
+
161
+ Project layout:
162
+
163
+ ```
164
+ codetree/
165
+ ├── core.py # scanner, language table, line classification, exporters
166
+ ├── cli.py # command line interface
167
+ ├── gui.py # animated Tkinter tree
168
+ └── tests/
169
+ ```
170
+
171
+ ## Contributing
172
+
173
+ Contributions are welcome! Fork the repository, create a branch, add tests for your change and open a pull request. Ideas, bug reports and new language definitions are all appreciated — please open an issue first for larger changes.
174
+
175
+ ## License
176
+
177
+ Released under the [MIT License](LICENSE) © Reza Mardani.
@@ -0,0 +1,151 @@
1
+ <div align="center">
2
+
3
+ # 🌳 CodeTree
4
+
5
+ **See your codebase as a living, animated tree.**
6
+
7
+ Folders grow into branches, files bloom as leaves — sized by lines of code, colored by language.
8
+
9
+ [![PyPI](https://img.shields.io/pypi/v/codetree-cli?color=3b9eff&label=PyPI)](https://pypi.org/project/codetree-cli/)
10
+ [![Python](https://img.shields.io/badge/python-3.8%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-3fb950)](LICENSE)
12
+ [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-8b949e)](#installation)
13
+ [![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen)](#why-codetree)
14
+
15
+ <img src="https://raw.githubusercontent.com/rezamardani01/codetree/main/docs/screenshot.png" alt="CodeTree showing the Python standard library as a radial tree" width="900">
16
+
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## Why CodeTree?
22
+
23
+ Line counters give you a table. CodeTree gives you a **map**: you instantly see which folders are heavy, which files dominate, and how comments, blank lines and code are balanced — and you can explore it by clicking, zooming and searching.
24
+
25
+ - 🌱 **A tree, not a table** — an animated radial tree that grows from the trunk outward.
26
+ - 🎨 **Language-aware** — 40+ languages detected, every line classified as *code*, *comment* or *blank*.
27
+ - ⚡ **Fast** — scans thousands of files in a couple of seconds, in the background, with a live progress view.
28
+ - 🧰 **Zero dependencies** — pure Python standard library (Tkinter for the GUI).
29
+ - 🖥️ **GUI by default, terminal when you need it** — scriptable with JSON / CSV / Markdown export.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install codetree-cli
35
+ ```
36
+
37
+ From source:
38
+
39
+ ```bash
40
+ git clone https://github.com/rezamardani01/codetree.git
41
+ cd codetree
42
+ pip install .
43
+ ```
44
+
45
+ > Requires Python 3.8+. The GUI uses Tkinter, which ships with the official Python installers
46
+ > (on some Linux distributions install it with e.g. `sudo apt install python3-tk`).
47
+
48
+ ## Usage
49
+
50
+ ```bash
51
+ codetree # open the GUI on the current folder
52
+ codetree path/to/project # open the GUI on a specific folder
53
+ codetree-gui # same, without a console window on Windows
54
+ ```
55
+
56
+ ### In the window
57
+
58
+ | Action | What it does |
59
+ |---|---|
60
+ | **Click a folder** | Grow or fold its branch (animated) |
61
+ | **Drag / mouse wheel** | Pan / zoom |
62
+ | **Hover a node** | Highlights its path to the trunk and shows lines, code/comment/blank split, size and share of the project |
63
+ | **Double-click a file** | Opens it in your default editor |
64
+ | **Right-click** | Open, show in folder, copy path |
65
+ | **Search box** | Prunes the tree to matching files and folders |
66
+ | **Click a language** | Lights up all leaves written in it |
67
+ | **Click a file in "Largest files"** | Flies the camera to that leaf |
68
+ | **Expand all · Collapse · Fit view** | Overview controls |
69
+ | **Theme · Export** | Dark/light theme, export JSON / CSV / Markdown / standalone HTML |
70
+
71
+ Shortcuts: `F5` rescan · `Ctrl+O` browse · `Ctrl+F` search · `Ctrl+E` export JSON · `Esc` clear search.
72
+
73
+ ### Reading the tree
74
+
75
+ - **Trunk** (center) = the project root.
76
+ - **Branches / green nodes** = folders. Thicker branch = more lines. The number on a folded node is how many items it hides.
77
+ - **Leaves** = files, arranged in a sunflower pattern at the end of their branch. **Bigger leaf = more lines. Color = language.**
78
+
79
+ ### Terminal mode
80
+
81
+ ```bash
82
+ codetree --cli # tree + language table + summary
83
+ codetree --cli --depth 2 --sort lines # limit depth, biggest first
84
+ codetree --cli --top 10 # also list the 10 largest files
85
+ codetree -e py -e js -i "*.min.js" # only these extensions, ignore a pattern
86
+ codetree --json report.json # write reports (use - for stdout)
87
+ codetree --csv report.csv --md report.md
88
+ codetree --html report.html # standalone interactive HTML report
89
+ ```
90
+
91
+ | Option | Description |
92
+ |---|---|
93
+ | `--cli` | Print to the terminal instead of opening the GUI |
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`) |
96
+ | `-i, --ignore PATTERN` | Glob to ignore, repeatable |
97
+ | `-e, --ext EXT` | Only count these extensions, repeatable |
98
+ | `--hidden` | Include hidden files and folders |
99
+ | `--no-gitignore` | Do not read `.gitignore` |
100
+ | `--no-default-ignores` | Do not skip `node_modules`, `venv`, `build`, … |
101
+ | `--max-size MB` | Skip files larger than this (default 5) |
102
+ | `--sort name\|lines\|code`, `--depth N`, `--top N` | Terminal tree options |
103
+ | `--no-color` | Disable colors |
104
+ | `-V, --version` | Show the version |
105
+
106
+ If the GUI cannot start (for example over SSH without a display), CodeTree automatically falls back to terminal output.
107
+
108
+ ### Use it as a library
109
+
110
+ ```python
111
+ from codetree.core import scan, ScanOptions
112
+
113
+ result = scan(".", ScanOptions(extensions=["py"], ignore=["tests"]))
114
+ print(result.total_files, result.total_lines)
115
+ for lang in result.languages.values():
116
+ print(lang.name, lang.code, lang.comment, lang.blank)
117
+ ```
118
+
119
+ ## What gets counted
120
+
121
+ - Hidden files and folders are skipped (enable with `--hidden` / the *Hidden files* checkbox).
122
+ - `node_modules`, `venv`, `__pycache__`, `dist`, `build`, `.git`, lock files and similar noise are skipped by default.
123
+ - Patterns in `.gitignore` files — in the project root and in subfolders — are respected, including `!` negations.
124
+ - Binary files and files over 5 MB are skipped; everything else is read as UTF‑8 with a lenient fallback.
125
+
126
+ ## Development
127
+
128
+ ```bash
129
+ git clone https://github.com/rezamardani01/codetree.git
130
+ cd codetree
131
+ python -m unittest discover -s tests -t .
132
+ python -m codetree . # run from source
133
+ ```
134
+
135
+ Project layout:
136
+
137
+ ```
138
+ codetree/
139
+ ├── core.py # scanner, language table, line classification, exporters
140
+ ├── cli.py # command line interface
141
+ ├── gui.py # animated Tkinter tree
142
+ └── tests/
143
+ ```
144
+
145
+ ## Contributing
146
+
147
+ Contributions are welcome! Fork the repository, create a branch, add tests for your change and open a pull request. Ideas, bug reports and new language definitions are all appreciated — please open an issue first for larger changes.
148
+
149
+ ## License
150
+
151
+ Released under the [MIT License](LICENSE) © Reza Mardani.
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,173 @@
1
+ """Command line entry point. Opens the GUI by default; ``--cli`` prints to the terminal."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .core import (DirNode, ScanOptions, ScanResult, format_size, scan, sorted_languages,
9
+ to_csv, to_json, to_markdown)
10
+ from .report import to_html
11
+
12
+ SORT_KEYS = {
13
+ "name": lambda n: n.name.lower(),
14
+ "lines": lambda n: -n.total,
15
+ "code": lambda n: -n.code,
16
+ }
17
+
18
+
19
+ class _Style:
20
+ def __init__(self, enabled: bool):
21
+ self.on = enabled
22
+
23
+ def __call__(self, text, code):
24
+ return f"\033[{code}m{text}\033[0m" if self.on else str(text)
25
+
26
+
27
+ def _print_tree(node: DirNode, c: _Style, sort: str, depth: int, prefix: str = "", level: int = 0) -> None:
28
+ key = SORT_KEYS[sort]
29
+ items = [("d", d) for d in sorted(node.dirs, key=key)] + [("f", f) for f in sorted(node.files, key=key)]
30
+ for i, (kind, item) in enumerate(items):
31
+ last = i == len(items) - 1
32
+ branch = "└── " if last else "├── "
33
+ if kind == "d":
34
+ print(f"{prefix}{branch}{c(item.name + '/', '1;34')} {c(f'{item.total:,} lines', '90')}")
35
+ if depth <= 0 or level + 1 < depth:
36
+ _print_tree(item, c, sort, depth, prefix + (" " if last else "│ "), level + 1)
37
+ else:
38
+ print(f"{prefix}{branch}{item.name} {c(f'{item.total:,} lines', '32')}"
39
+ f" {c('(' + item.language + ')', '90')}")
40
+
41
+
42
+ def _print_report(result: ScanResult, args, c: _Style) -> None:
43
+ print(c(f"\n{result.root.name}/", "1;36"))
44
+ _print_tree(result.root, c, args.sort, args.depth)
45
+
46
+ langs = sorted_languages(result)
47
+ if langs:
48
+ print(c("\nLanguages", "1"))
49
+ width = max(len(l.name) for l in langs)
50
+ total = result.total_lines or 1
51
+ print(f" {'Language'.ljust(width)} {'Files':>6} {'Code':>9} {'Comment':>9} {'Blank':>9} {'Share':>7}")
52
+ for l in langs:
53
+ bar = "█" * max(1, round(l.total / total * 20))
54
+ print(f" {l.name.ljust(width)} {l.files:>6} {l.code:>9,} {l.comment:>9,} {l.blank:>9,} "
55
+ f"{l.total / total:>6.1%} {c(bar, '36')}")
56
+
57
+ if args.top:
58
+ print(c(f"\nTop {args.top} largest files", "1"))
59
+ for f in sorted(result.files, key=lambda f: f.total, reverse=True)[: args.top]:
60
+ print(f" {f.total:>8,} {os.path.relpath(f.path, result.root.path)}")
61
+
62
+ r = result.root
63
+ print(c("\nSummary", "1"))
64
+ print(f" Files: {r.file_count:,}")
65
+ print(f" Folders: {result.folder_count:,}")
66
+ print(f" Lines: {r.total:,} (code {r.code:,} · comments {r.comment:,} · blank {r.blank:,})")
67
+ print(f" Size: {format_size(r.size)}")
68
+ print(f" Time: {result.elapsed:.2f}s")
69
+ if result.skipped_binary or result.skipped_large:
70
+ print(c(f" Skipped: {result.skipped_binary} binary, {result.skipped_large} too large", "90"))
71
+ for err in result.errors[:5]:
72
+ print(c(f" ! {err}", "33"), file=sys.stderr)
73
+
74
+
75
+ def build_parser() -> argparse.ArgumentParser:
76
+ p = argparse.ArgumentParser(
77
+ prog="codetree",
78
+ description="Analyze a project's lines of code. Opens a graphical window by default.")
79
+ p.add_argument("path", nargs="?", default=".", help="project directory (default: current directory)")
80
+ p.add_argument("--cli", action="store_true", help="print the report in the terminal instead of opening the GUI")
81
+ p.add_argument("--json", metavar="FILE", help="write a JSON report ('-' for stdout); implies --cli")
82
+ p.add_argument("--csv", metavar="FILE", help="write a CSV report ('-' for stdout); implies --cli")
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")
85
+ p.add_argument("-i", "--ignore", action="append", default=[], metavar="PATTERN",
86
+ help="glob pattern to ignore (repeatable), e.g. -i '*.min.js' -i tests")
87
+ p.add_argument("-e", "--ext", action="append", default=[], metavar="EXT",
88
+ help="only count these extensions (repeatable), e.g. -e py -e js")
89
+ p.add_argument("--hidden", action="store_true", help="include hidden files and folders")
90
+ p.add_argument("--no-gitignore", action="store_true", help="do not read .gitignore")
91
+ p.add_argument("--no-default-ignores", action="store_true", help="do not skip node_modules, venv, build, ...")
92
+ p.add_argument("--max-size", type=float, default=5, metavar="MB", help="skip files larger than this (default 5)")
93
+ p.add_argument("--sort", choices=sorted(SORT_KEYS), default="name", help="tree sort order (CLI)")
94
+ p.add_argument("--depth", type=int, default=0, help="limit tree depth, 0 = unlimited (CLI)")
95
+ p.add_argument("--top", type=int, default=0, metavar="N", help="list the N largest files (CLI)")
96
+ p.add_argument("--no-color", action="store_true", help="disable colored output")
97
+ p.add_argument("-V", "--version", action="version", version=f"codetree {__version__}")
98
+ return p
99
+
100
+
101
+ def _emit(target: str, text: str) -> None:
102
+ if target == "-":
103
+ sys.stdout.write(text)
104
+ else:
105
+ with open(target, "w", encoding="utf-8", newline="") as fh:
106
+ fh.write(text)
107
+ print(f"Saved {target}", file=sys.stderr)
108
+
109
+
110
+ def main(argv=None) -> int:
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")
119
+ path = os.path.abspath(args.path)
120
+ if not os.path.isdir(path):
121
+ print(f"codetree: '{args.path}' is not a directory.", file=sys.stderr)
122
+ return 2
123
+
124
+ options = ScanOptions(
125
+ include_hidden=args.hidden,
126
+ use_default_ignores=not args.no_default_ignores,
127
+ respect_gitignore=not args.no_gitignore,
128
+ ignore=args.ignore,
129
+ extensions=args.ext,
130
+ max_size=int(args.max_size * 1024 * 1024),
131
+ )
132
+
133
+ 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)
135
+
136
+ if not wants_cli:
137
+ try:
138
+ from .gui import run_gui
139
+ except ImportError as e:
140
+ print(f"codetree: GUI unavailable ({e}); falling back to terminal output.", file=sys.stderr)
141
+ else:
142
+ try:
143
+ run_gui(path, options)
144
+ return 0
145
+ except Exception as e: # e.g. no display
146
+ print(f"codetree: could not open the GUI ({e}); falling back to terminal output.", file=sys.stderr)
147
+
148
+ for stream in (sys.stdout, sys.stderr):
149
+ if hasattr(stream, "reconfigure"):
150
+ stream.reconfigure(encoding="utf-8", errors="replace")
151
+ try:
152
+ result = scan(path, options)
153
+ except KeyboardInterrupt:
154
+ return 130
155
+ stdout_taken = any(t == "-" for t, _ in exports)
156
+ for target, fn in exports:
157
+ if target:
158
+ _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":
162
+ os.system("") # enable ANSI escapes on Windows consoles
163
+ _print_report(result, args, _Style(color))
164
+ return 0
165
+
166
+
167
+ def main_gui() -> int:
168
+ """Entry point for the ``codetree-gui`` launcher (no console window on Windows)."""
169
+ return main(sys.argv[1:] if len(sys.argv) > 1 else ["."])
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())