anix-ctx 0.1.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.
- anix_ctx-0.1.0/PKG-INFO +144 -0
- anix_ctx-0.1.0/README.md +121 -0
- anix_ctx-0.1.0/pyproject.toml +38 -0
- anix_ctx-0.1.0/src/anix_ctx/__init__.py +7 -0
- anix_ctx-0.1.0/src/anix_ctx/cli.py +118 -0
- anix_ctx-0.1.0/src/anix_ctx/formatter.py +251 -0
- anix_ctx-0.1.0/src/anix_ctx/scanner.py +204 -0
- anix_ctx-0.1.0/src/anix_ctx/tui.py +408 -0
anix_ctx-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: anix-ctx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Interactive context packager for LLMs with dark neon TUI (ANIX ecosystem)
|
|
5
|
+
Author: ANIX Team
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: cli,context,developer-tools,llm,markdown,textual,tui
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
17
|
+
Classifier: Topic :: Utilities
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: pathspec>=0.12.0
|
|
20
|
+
Requires-Dist: pyperclip>=1.8.0
|
|
21
|
+
Requires-Dist: textual>=0.40.0
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# ⚡ anix-ctx
|
|
25
|
+
|
|
26
|
+
> Интерактивный упаковщик контекста проекта для LLM (Gemini, ChatGPT, Claude) в тёмном неоновом стиле экосистемы **ANIX**.
|
|
27
|
+
|
|
28
|
+
Одной командой открывает быстрый TUI, где можно визуально выбрать нужные файлы проекта, увидеть реальный расход токенов и скопировать всё в буфер обмена в идеальном Markdown-формате с ASCII-деревом файлов.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## ✨ Возможности
|
|
33
|
+
|
|
34
|
+
- **🚀 Мгновенный запуск**: `anix-ctx` в любой папке открывает интерактивный TUI.
|
|
35
|
+
- **🛡 Умная фильтрация**: автоматически игнорирует `.git`, `node_modules`, `__pycache__`, `.venv`, лок-файлы (`package-lock.json`, `poetry.lock`, `uv.lock` и др.), бинарные файлы и любые правила из `.gitignore` / `.ignore`.
|
|
36
|
+
- **⚡ Кэшированная статистика**: переключение чекбоксов не нагружает диск — токены и символы пересчитываются мгновенно из оперативной памяти.
|
|
37
|
+
- **📊 Живая аналитика**: точный подсчёт символов, оценка токенов (`chars // 4`), Top-5 самых тяжёлых файлов и превью ASCII-дерева в реальном времени.
|
|
38
|
+
- **🔒 Защита разметки**: адаптивный динамический fence (минимум ` ```` `) гарантирует, что вложенные блоки кода и `.md` файлы не сломают Markdown.
|
|
39
|
+
- **🌐 Безопасная кодировка**: чтение файлов с `utf-8` и заменой некорректных символов (`errors="replace"`), полная кроссплатформенность (Windows, Linux, macOS).
|
|
40
|
+
- **⚡ Быстрый режим (Headless)**: флаги `--copy` (`-c`) и `-o context.md` для мгновенной сборки контекста без открытия интерфейса.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## 📦 Установка
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
# Клонирование или установка в режиме разработки
|
|
48
|
+
git clone https://github.com/anix/anix-ctx.git
|
|
49
|
+
cd anix-ctx
|
|
50
|
+
pip install -e .
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Либо сборка стандартного wheel:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
python -m build
|
|
57
|
+
pip install dist/anix_ctx-*.whl
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 🎮 Использование
|
|
63
|
+
|
|
64
|
+
### 1. Интерактивный TUI (по умолчанию)
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Открыть TUI для текущей директории
|
|
68
|
+
anix-ctx
|
|
69
|
+
|
|
70
|
+
# Открыть TUI для конкретной папки
|
|
71
|
+
anix-ctx /path/to/project
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
#### Горячие клавиши в TUI:
|
|
75
|
+
| Клавиша | Действие |
|
|
76
|
+
| :--- | :--- |
|
|
77
|
+
| `Space` | Переключить выбор текущего файла или всей папки |
|
|
78
|
+
| `Enter` / Клик | Раскрыть/свернуть папку или переключить файл |
|
|
79
|
+
| `a` | Выбрать все / Снять выбор со всех файлов |
|
|
80
|
+
| `c` | Скопировать готовый Markdown-контекст в буфер обмена |
|
|
81
|
+
| `s` | Сохранить контекст в файл `context.md` |
|
|
82
|
+
| `q` | Выйти из программы |
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
### 2. Быстрый headless-режим (без TUI)
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
# Упаковать текущий проект и сразу скопировать в буфер обмена
|
|
90
|
+
anix-ctx --copy
|
|
91
|
+
anix-ctx -c
|
|
92
|
+
|
|
93
|
+
# Упаковать проект в файл context.md
|
|
94
|
+
anix-ctx -o context.md
|
|
95
|
+
|
|
96
|
+
# Упаковать конкретную подпапку сразу в буфер
|
|
97
|
+
anix-ctx src/ --copy
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## 📋 Формат вывода Markdown
|
|
103
|
+
|
|
104
|
+
Контекст упаковывается в чистую и готовую для промпта структуру:
|
|
105
|
+
|
|
106
|
+
````markdown
|
|
107
|
+
# Project Context
|
|
108
|
+
|
|
109
|
+
## File Tree
|
|
110
|
+
````
|
|
111
|
+
anix-ctx
|
|
112
|
+
├── src/
|
|
113
|
+
│ └── anix_ctx/
|
|
114
|
+
│ ├── __init__.py
|
|
115
|
+
│ ├── cli.py
|
|
116
|
+
│ ├── formatter.py
|
|
117
|
+
│ ├── scanner.py
|
|
118
|
+
│ └── tui.py
|
|
119
|
+
├── pyproject.toml
|
|
120
|
+
└── README.md
|
|
121
|
+
````
|
|
122
|
+
|
|
123
|
+
## Files
|
|
124
|
+
|
|
125
|
+
### `pyproject.toml`
|
|
126
|
+
````toml
|
|
127
|
+
...
|
|
128
|
+
````
|
|
129
|
+
|
|
130
|
+
### `src/anix_ctx/cli.py`
|
|
131
|
+
````python
|
|
132
|
+
...
|
|
133
|
+
````
|
|
134
|
+
````
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## 🛠 Стек
|
|
139
|
+
|
|
140
|
+
- **Python**: 3.10+
|
|
141
|
+
- **TUI Framework**: [Textual](https://github.com/Textualize/textual)
|
|
142
|
+
- **Gitignore Engine**: [PathSpec](https://github.com/cpburnz/python-pathspec)
|
|
143
|
+
- **Clipboard**: [Pyperclip](https://github.com/asweigart/pyperclip)
|
|
144
|
+
- **Лицензия**: MIT (ANIX Ecosystem)
|
anix_ctx-0.1.0/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# ⚡ anix-ctx
|
|
2
|
+
|
|
3
|
+
> Интерактивный упаковщик контекста проекта для LLM (Gemini, ChatGPT, Claude) в тёмном неоновом стиле экосистемы **ANIX**.
|
|
4
|
+
|
|
5
|
+
Одной командой открывает быстрый TUI, где можно визуально выбрать нужные файлы проекта, увидеть реальный расход токенов и скопировать всё в буфер обмена в идеальном Markdown-формате с ASCII-деревом файлов.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## ✨ Возможности
|
|
10
|
+
|
|
11
|
+
- **🚀 Мгновенный запуск**: `anix-ctx` в любой папке открывает интерактивный TUI.
|
|
12
|
+
- **🛡 Умная фильтрация**: автоматически игнорирует `.git`, `node_modules`, `__pycache__`, `.venv`, лок-файлы (`package-lock.json`, `poetry.lock`, `uv.lock` и др.), бинарные файлы и любые правила из `.gitignore` / `.ignore`.
|
|
13
|
+
- **⚡ Кэшированная статистика**: переключение чекбоксов не нагружает диск — токены и символы пересчитываются мгновенно из оперативной памяти.
|
|
14
|
+
- **📊 Живая аналитика**: точный подсчёт символов, оценка токенов (`chars // 4`), Top-5 самых тяжёлых файлов и превью ASCII-дерева в реальном времени.
|
|
15
|
+
- **🔒 Защита разметки**: адаптивный динамический fence (минимум ` ```` `) гарантирует, что вложенные блоки кода и `.md` файлы не сломают Markdown.
|
|
16
|
+
- **🌐 Безопасная кодировка**: чтение файлов с `utf-8` и заменой некорректных символов (`errors="replace"`), полная кроссплатформенность (Windows, Linux, macOS).
|
|
17
|
+
- **⚡ Быстрый режим (Headless)**: флаги `--copy` (`-c`) и `-o context.md` для мгновенной сборки контекста без открытия интерфейса.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 📦 Установка
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Клонирование или установка в режиме разработки
|
|
25
|
+
git clone https://github.com/anix/anix-ctx.git
|
|
26
|
+
cd anix-ctx
|
|
27
|
+
pip install -e .
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Либо сборка стандартного wheel:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
python -m build
|
|
34
|
+
pip install dist/anix_ctx-*.whl
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 🎮 Использование
|
|
40
|
+
|
|
41
|
+
### 1. Интерактивный TUI (по умолчанию)
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
# Открыть TUI для текущей директории
|
|
45
|
+
anix-ctx
|
|
46
|
+
|
|
47
|
+
# Открыть TUI для конкретной папки
|
|
48
|
+
anix-ctx /path/to/project
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
#### Горячие клавиши в TUI:
|
|
52
|
+
| Клавиша | Действие |
|
|
53
|
+
| :--- | :--- |
|
|
54
|
+
| `Space` | Переключить выбор текущего файла или всей папки |
|
|
55
|
+
| `Enter` / Клик | Раскрыть/свернуть папку или переключить файл |
|
|
56
|
+
| `a` | Выбрать все / Снять выбор со всех файлов |
|
|
57
|
+
| `c` | Скопировать готовый Markdown-контекст в буфер обмена |
|
|
58
|
+
| `s` | Сохранить контекст в файл `context.md` |
|
|
59
|
+
| `q` | Выйти из программы |
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
### 2. Быстрый headless-режим (без TUI)
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Упаковать текущий проект и сразу скопировать в буфер обмена
|
|
67
|
+
anix-ctx --copy
|
|
68
|
+
anix-ctx -c
|
|
69
|
+
|
|
70
|
+
# Упаковать проект в файл context.md
|
|
71
|
+
anix-ctx -o context.md
|
|
72
|
+
|
|
73
|
+
# Упаковать конкретную подпапку сразу в буфер
|
|
74
|
+
anix-ctx src/ --copy
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 📋 Формат вывода Markdown
|
|
80
|
+
|
|
81
|
+
Контекст упаковывается в чистую и готовую для промпта структуру:
|
|
82
|
+
|
|
83
|
+
````markdown
|
|
84
|
+
# Project Context
|
|
85
|
+
|
|
86
|
+
## File Tree
|
|
87
|
+
````
|
|
88
|
+
anix-ctx
|
|
89
|
+
├── src/
|
|
90
|
+
│ └── anix_ctx/
|
|
91
|
+
│ ├── __init__.py
|
|
92
|
+
│ ├── cli.py
|
|
93
|
+
│ ├── formatter.py
|
|
94
|
+
│ ├── scanner.py
|
|
95
|
+
│ └── tui.py
|
|
96
|
+
├── pyproject.toml
|
|
97
|
+
└── README.md
|
|
98
|
+
````
|
|
99
|
+
|
|
100
|
+
## Files
|
|
101
|
+
|
|
102
|
+
### `pyproject.toml`
|
|
103
|
+
````toml
|
|
104
|
+
...
|
|
105
|
+
````
|
|
106
|
+
|
|
107
|
+
### `src/anix_ctx/cli.py`
|
|
108
|
+
````python
|
|
109
|
+
...
|
|
110
|
+
````
|
|
111
|
+
````
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## 🛠 Стек
|
|
116
|
+
|
|
117
|
+
- **Python**: 3.10+
|
|
118
|
+
- **TUI Framework**: [Textual](https://github.com/Textualize/textual)
|
|
119
|
+
- **Gitignore Engine**: [PathSpec](https://github.com/cpburnz/python-pathspec)
|
|
120
|
+
- **Clipboard**: [Pyperclip](https://github.com/asweigart/pyperclip)
|
|
121
|
+
- **Лицензия**: MIT (ANIX Ecosystem)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "anix-ctx"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Interactive context packager for LLMs with dark neon TUI (ANIX ecosystem)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "ANIX Team" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["llm", "context", "tui", "cli", "markdown", "textual", "developer-tools"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Environment :: Console",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Software Development :: Build Tools",
|
|
26
|
+
"Topic :: Utilities",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"textual>=0.40.0",
|
|
30
|
+
"pathspec>=0.12.0",
|
|
31
|
+
"pyperclip>=1.8.0",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
anix-ctx = "anix_ctx.cli:main"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/anix_ctx"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI entry point for anix-ctx.
|
|
3
|
+
Handles command line arguments, headless packaging (--copy, -o), and TUI launching.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import pyperclip
|
|
13
|
+
|
|
14
|
+
from anix_ctx import __version__
|
|
15
|
+
from anix_ctx.formatter import calculate_stats, format_context
|
|
16
|
+
from anix_ctx.scanner import scan_directory
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def create_parser() -> argparse.ArgumentParser:
|
|
20
|
+
"""Create command line arguments parser."""
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="anix-ctx",
|
|
23
|
+
description="Interactive context packager for LLMs with dark neon TUI (ANIX ecosystem).",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"path",
|
|
27
|
+
nargs="?",
|
|
28
|
+
default=".",
|
|
29
|
+
help="Path to project directory (default: current directory).",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"-c",
|
|
33
|
+
"--copy",
|
|
34
|
+
action="store_true",
|
|
35
|
+
help="Headless mode: pack project context and copy directly to clipboard without opening TUI.",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"-o",
|
|
39
|
+
"--output",
|
|
40
|
+
metavar="FILE",
|
|
41
|
+
help="Headless mode: pack project context and save directly to file without opening TUI.",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"-v",
|
|
45
|
+
"--version",
|
|
46
|
+
action="version",
|
|
47
|
+
version=f"%(prog)s {__version__}",
|
|
48
|
+
help="Show program version and exit.",
|
|
49
|
+
)
|
|
50
|
+
return parser
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def run_headless(target_dir: Path, copy_to_clipboard: bool, output_file: str | None) -> int:
|
|
54
|
+
"""Run non-interactive context generation and copy or write output."""
|
|
55
|
+
files = scan_directory(target_dir)
|
|
56
|
+
if not files:
|
|
57
|
+
print(f"⚡ [ANIX CTX] No matching files found in: {target_dir}", file=sys.stderr)
|
|
58
|
+
return 1
|
|
59
|
+
|
|
60
|
+
stats = calculate_stats(files)
|
|
61
|
+
formatted = format_context(files, root_name=target_dir.name)
|
|
62
|
+
|
|
63
|
+
if copy_to_clipboard:
|
|
64
|
+
try:
|
|
65
|
+
pyperclip.copy(formatted)
|
|
66
|
+
print(
|
|
67
|
+
f"⚡ [ANIX CTX] Copied {stats.file_count} files "
|
|
68
|
+
f"(~{stats.approx_tokens:,} tokens, {stats.char_count:,} chars) to clipboard!"
|
|
69
|
+
)
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
print(f"⚡ [ANIX CTX] Clipboard error: {exc}", file=sys.stderr)
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
if output_file:
|
|
75
|
+
out_path = Path(output_file).resolve()
|
|
76
|
+
try:
|
|
77
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
with open(out_path, "w", encoding="utf-8", errors="replace") as f:
|
|
79
|
+
f.write(formatted)
|
|
80
|
+
print(
|
|
81
|
+
f"⚡ [ANIX CTX] Saved {stats.file_count} files "
|
|
82
|
+
f"(~{stats.approx_tokens:,} tokens) to: {out_path.name}"
|
|
83
|
+
)
|
|
84
|
+
except Exception as exc:
|
|
85
|
+
print(f"⚡ [ANIX CTX] File write error: {exc}", file=sys.stderr)
|
|
86
|
+
return 1
|
|
87
|
+
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def main() -> None:
|
|
92
|
+
"""Main CLI entry point."""
|
|
93
|
+
parser = create_parser()
|
|
94
|
+
args = parser.parse_args()
|
|
95
|
+
|
|
96
|
+
target_dir = Path(args.path).resolve()
|
|
97
|
+
if not target_dir.exists():
|
|
98
|
+
print(f"⚡ [ANIX CTX] Error: Directory does not exist: {target_dir}", file=sys.stderr)
|
|
99
|
+
sys.exit(1)
|
|
100
|
+
|
|
101
|
+
if not target_dir.is_dir():
|
|
102
|
+
print(f"⚡ [ANIX CTX] Error: Path is not a directory: {target_dir}", file=sys.stderr)
|
|
103
|
+
sys.exit(1)
|
|
104
|
+
|
|
105
|
+
# Check for headless execution
|
|
106
|
+
if args.copy or args.output:
|
|
107
|
+
code = run_headless(target_dir, copy_to_clipboard=args.copy, output_file=args.output)
|
|
108
|
+
sys.exit(code)
|
|
109
|
+
|
|
110
|
+
# Interactive TUI mode
|
|
111
|
+
from anix_ctx.tui import AnixCtxApp
|
|
112
|
+
|
|
113
|
+
app = AnixCtxApp(target_dir)
|
|
114
|
+
app.run()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
if __name__ == "__main__":
|
|
118
|
+
main()
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Formatter module for anix-ctx.
|
|
3
|
+
Builds ASCII directory trees, estimates tokens, handles dynamic Markdown fences,
|
|
4
|
+
and formats the final LLM prompt context.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Sequence
|
|
12
|
+
|
|
13
|
+
from anix_ctx.scanner import ScannedFile
|
|
14
|
+
|
|
15
|
+
# Extension to Markdown syntax highlighting identifier
|
|
16
|
+
LANGUAGE_MAP: dict[str, str] = {
|
|
17
|
+
# Python
|
|
18
|
+
".py": "python",
|
|
19
|
+
".pyw": "python",
|
|
20
|
+
".pyi": "python",
|
|
21
|
+
# Web / JS / TS
|
|
22
|
+
".js": "javascript",
|
|
23
|
+
".mjs": "javascript",
|
|
24
|
+
".cjs": "javascript",
|
|
25
|
+
".jsx": "jsx",
|
|
26
|
+
".ts": "typescript",
|
|
27
|
+
".mts": "typescript",
|
|
28
|
+
".cts": "typescript",
|
|
29
|
+
".tsx": "tsx",
|
|
30
|
+
".html": "html",
|
|
31
|
+
".htm": "html",
|
|
32
|
+
".css": "css",
|
|
33
|
+
".scss": "scss",
|
|
34
|
+
".sass": "sass",
|
|
35
|
+
".less": "less",
|
|
36
|
+
".vue": "vue",
|
|
37
|
+
".svelte": "svelte",
|
|
38
|
+
# Systems & Compiled
|
|
39
|
+
".rs": "rust",
|
|
40
|
+
".go": "go",
|
|
41
|
+
".c": "c",
|
|
42
|
+
".h": "c",
|
|
43
|
+
".cpp": "cpp",
|
|
44
|
+
".cc": "cpp",
|
|
45
|
+
".cxx": "cpp",
|
|
46
|
+
".hpp": "cpp",
|
|
47
|
+
".hh": "cpp",
|
|
48
|
+
".cs": "csharp",
|
|
49
|
+
".java": "java",
|
|
50
|
+
".kt": "kotlin",
|
|
51
|
+
".kts": "kotlin",
|
|
52
|
+
".swift": "swift",
|
|
53
|
+
".dart": "dart",
|
|
54
|
+
# Scripting & Shell
|
|
55
|
+
".sh": "bash",
|
|
56
|
+
".bash": "bash",
|
|
57
|
+
".zsh": "bash",
|
|
58
|
+
".ps1": "powershell",
|
|
59
|
+
".psm1": "powershell",
|
|
60
|
+
".bat": "bat",
|
|
61
|
+
".cmd": "cmd",
|
|
62
|
+
".rb": "ruby",
|
|
63
|
+
".php": "php",
|
|
64
|
+
".lua": "lua",
|
|
65
|
+
# Config & Data
|
|
66
|
+
".json": "json",
|
|
67
|
+
".json5": "json5",
|
|
68
|
+
".yaml": "yaml",
|
|
69
|
+
".yml": "yaml",
|
|
70
|
+
".toml": "toml",
|
|
71
|
+
".ini": "ini",
|
|
72
|
+
".cfg": "ini",
|
|
73
|
+
".env": "ini",
|
|
74
|
+
".xml": "xml",
|
|
75
|
+
".sql": "sql",
|
|
76
|
+
".graphql": "graphql",
|
|
77
|
+
".gql": "graphql",
|
|
78
|
+
# Markup & Docs
|
|
79
|
+
".md": "markdown",
|
|
80
|
+
".markdown": "markdown",
|
|
81
|
+
".rst": "rst",
|
|
82
|
+
".tex": "latex",
|
|
83
|
+
".txt": "text",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
# Special filename mappings
|
|
87
|
+
FILENAME_LANGUAGE_MAP: dict[str, str] = {
|
|
88
|
+
"dockerfile": "dockerfile",
|
|
89
|
+
"containerfile": "dockerfile",
|
|
90
|
+
"makefile": "makefile",
|
|
91
|
+
"gemfile": "ruby",
|
|
92
|
+
"rakefile": "ruby",
|
|
93
|
+
".gitignore": "gitignore",
|
|
94
|
+
".ignore": "gitignore",
|
|
95
|
+
".dockerignore": "dockerignore",
|
|
96
|
+
"cmakelists.txt": "cmake",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass
|
|
101
|
+
class ContextStats:
|
|
102
|
+
"""Statistics for the selected context files."""
|
|
103
|
+
file_count: int
|
|
104
|
+
char_count: int
|
|
105
|
+
approx_tokens: int
|
|
106
|
+
top_files: list[tuple[str, int]] # (rel_path, char_count)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class TreeNode:
|
|
110
|
+
"""Node representing a directory or file in the ASCII tree."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, name: str, is_dir: bool = False):
|
|
113
|
+
self.name = name
|
|
114
|
+
self.is_dir = is_dir
|
|
115
|
+
self.children: dict[str, TreeNode] = {}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def get_language(path: Path) -> str:
|
|
119
|
+
"""Detect language identifier for Markdown code block."""
|
|
120
|
+
lower_name = path.name.lower()
|
|
121
|
+
if lower_name in FILENAME_LANGUAGE_MAP:
|
|
122
|
+
return FILENAME_LANGUAGE_MAP[lower_name]
|
|
123
|
+
return LANGUAGE_MAP.get(path.suffix.lower(), "")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def get_dynamic_fence(content: str) -> str:
|
|
127
|
+
"""
|
|
128
|
+
Generate a dynamic backtick fence to prevent nested code blocks
|
|
129
|
+
from breaking the Markdown output. Minimum 4 backticks.
|
|
130
|
+
"""
|
|
131
|
+
count = 4
|
|
132
|
+
while ("`" * count) in content:
|
|
133
|
+
count += 1
|
|
134
|
+
return "`" * count
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def read_file_safe(path: Path) -> str:
|
|
138
|
+
"""
|
|
139
|
+
Safely read text file contents with UTF-8 encoding and character replacement.
|
|
140
|
+
"""
|
|
141
|
+
try:
|
|
142
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
143
|
+
return f.read()
|
|
144
|
+
except Exception as exc:
|
|
145
|
+
return f"[Error reading file: {exc}]"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def estimate_tokens(char_count: int) -> int:
|
|
149
|
+
"""Estimate token count from character count (approx 4 chars per token)."""
|
|
150
|
+
return char_count // 4
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def build_ascii_tree(rel_paths: Sequence[str], root_name: str = ".") -> str:
|
|
154
|
+
"""
|
|
155
|
+
Build a clean ASCII hierarchy tree for the given relative paths.
|
|
156
|
+
"""
|
|
157
|
+
if not rel_paths:
|
|
158
|
+
return f"{root_name}\n(no files selected)"
|
|
159
|
+
|
|
160
|
+
root = TreeNode(root_name, is_dir=True)
|
|
161
|
+
|
|
162
|
+
for rel_path in sorted(rel_paths):
|
|
163
|
+
parts = [p for p in Path(rel_path).as_posix().split("/") if p and p != "."]
|
|
164
|
+
curr = root
|
|
165
|
+
for i, part in enumerate(parts):
|
|
166
|
+
is_file = (i == len(parts) - 1)
|
|
167
|
+
if part not in curr.children:
|
|
168
|
+
curr.children[part] = TreeNode(part, is_dir=not is_file)
|
|
169
|
+
curr = curr.children[part]
|
|
170
|
+
|
|
171
|
+
lines: list[str] = [root.name]
|
|
172
|
+
|
|
173
|
+
def _render(node: TreeNode, prefix: str = "") -> None:
|
|
174
|
+
# Directories first, then alphabetical by name
|
|
175
|
+
sorted_keys = sorted(
|
|
176
|
+
node.children.keys(),
|
|
177
|
+
key=lambda k: (not node.children[k].is_dir, k.lower()),
|
|
178
|
+
)
|
|
179
|
+
for i, key in enumerate(sorted_keys):
|
|
180
|
+
child = node.children[key]
|
|
181
|
+
is_last = (i == len(sorted_keys) - 1)
|
|
182
|
+
connector = "└── " if is_last else "├── "
|
|
183
|
+
display_name = f"{child.name}/" if child.is_dir else child.name
|
|
184
|
+
lines.append(f"{prefix}{connector}{display_name}")
|
|
185
|
+
|
|
186
|
+
next_prefix = prefix + (" " if is_last else "│ ")
|
|
187
|
+
_render(child, next_prefix)
|
|
188
|
+
|
|
189
|
+
_render(root)
|
|
190
|
+
return "\n".join(lines)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def calculate_stats(files: Sequence[ScannedFile]) -> ContextStats:
|
|
194
|
+
"""
|
|
195
|
+
Calculate file count, total characters, estimated tokens, and top-5 heaviest files.
|
|
196
|
+
"""
|
|
197
|
+
total_chars = 0
|
|
198
|
+
file_weights: list[tuple[str, int]] = []
|
|
199
|
+
|
|
200
|
+
for f in files:
|
|
201
|
+
content = read_file_safe(f.path)
|
|
202
|
+
c_len = len(content)
|
|
203
|
+
total_chars += c_len
|
|
204
|
+
file_weights.append((f.rel_path, c_len))
|
|
205
|
+
|
|
206
|
+
file_weights.sort(key=lambda item: item[1], reverse=True)
|
|
207
|
+
top_5 = file_weights[:5]
|
|
208
|
+
|
|
209
|
+
return ContextStats(
|
|
210
|
+
file_count=len(files),
|
|
211
|
+
char_count=total_chars,
|
|
212
|
+
approx_tokens=estimate_tokens(total_chars),
|
|
213
|
+
top_files=top_5,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def format_context(files: Sequence[ScannedFile], root_name: str = ".") -> str:
|
|
218
|
+
"""
|
|
219
|
+
Format selected files into an LLM-ready Markdown string with ASCII tree and safe code blocks.
|
|
220
|
+
"""
|
|
221
|
+
if not files:
|
|
222
|
+
return "# Project Context\n\n*(No files selected)*\n"
|
|
223
|
+
|
|
224
|
+
rel_paths = [f.rel_path for f in files]
|
|
225
|
+
tree_text = build_ascii_tree(rel_paths, root_name=root_name)
|
|
226
|
+
tree_fence = get_dynamic_fence(tree_text)
|
|
227
|
+
|
|
228
|
+
sections: list[str] = [
|
|
229
|
+
"# Project Context",
|
|
230
|
+
"",
|
|
231
|
+
"## File Tree",
|
|
232
|
+
f"{tree_fence}",
|
|
233
|
+
tree_text,
|
|
234
|
+
f"{tree_fence}",
|
|
235
|
+
"",
|
|
236
|
+
"## Files",
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
for f in sorted(files, key=lambda x: x.rel_path.lower()):
|
|
240
|
+
content = read_file_safe(f.path)
|
|
241
|
+
lang = get_language(f.path)
|
|
242
|
+
fence = get_dynamic_fence(content)
|
|
243
|
+
|
|
244
|
+
sections.append("")
|
|
245
|
+
sections.append(f"### `{f.rel_path}`")
|
|
246
|
+
sections.append(f"{fence}{lang}")
|
|
247
|
+
sections.append(content)
|
|
248
|
+
sections.append(f"{fence}")
|
|
249
|
+
|
|
250
|
+
sections.append("")
|
|
251
|
+
return "\n".join(sections)
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Scanner module for anix-ctx.
|
|
3
|
+
Handles file discovery, .gitignore matching, ignore rules, and binary file filtering.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Iterable, Sequence
|
|
12
|
+
|
|
13
|
+
import pathspec
|
|
14
|
+
|
|
15
|
+
# Max file size: 500 KB to avoid wasting LLM context tokens
|
|
16
|
+
MAX_FILE_SIZE = 500 * 1024
|
|
17
|
+
|
|
18
|
+
# Default ignore patterns (directories, caches, lockfiles, minified assets)
|
|
19
|
+
DEFAULT_IGNORE_PATTERNS: list[str] = [
|
|
20
|
+
# VCS & IDEs
|
|
21
|
+
".git",
|
|
22
|
+
".git/**",
|
|
23
|
+
".hg",
|
|
24
|
+
".svn",
|
|
25
|
+
".idea",
|
|
26
|
+
".vscode",
|
|
27
|
+
# Build & Virtual Environments
|
|
28
|
+
"node_modules",
|
|
29
|
+
"__pycache__",
|
|
30
|
+
".venv",
|
|
31
|
+
"venv",
|
|
32
|
+
"env",
|
|
33
|
+
".env",
|
|
34
|
+
"dist",
|
|
35
|
+
"build",
|
|
36
|
+
"out",
|
|
37
|
+
"target",
|
|
38
|
+
"*.egg-info",
|
|
39
|
+
".next",
|
|
40
|
+
".nuxt",
|
|
41
|
+
".cache",
|
|
42
|
+
".pytest_cache",
|
|
43
|
+
".mypy_cache",
|
|
44
|
+
".ruff_cache",
|
|
45
|
+
".tox",
|
|
46
|
+
# Lockfiles & Minified Assets
|
|
47
|
+
"package-lock.json",
|
|
48
|
+
"yarn.lock",
|
|
49
|
+
"pnpm-lock.yaml",
|
|
50
|
+
"poetry.lock",
|
|
51
|
+
"uv.lock",
|
|
52
|
+
"Cargo.lock",
|
|
53
|
+
"composer.lock",
|
|
54
|
+
"*.min.js",
|
|
55
|
+
"*.min.css",
|
|
56
|
+
"*.map",
|
|
57
|
+
# Temporary & OS files
|
|
58
|
+
".DS_Store",
|
|
59
|
+
"Thumbs.db",
|
|
60
|
+
"desktop.ini",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
# Common binary file extensions for fast short-circuit check
|
|
64
|
+
BINARY_EXTENSIONS: set[str] = {
|
|
65
|
+
# Images
|
|
66
|
+
".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".bmp", ".tiff", ".psd", ".raw",
|
|
67
|
+
# Binaries & Libraries
|
|
68
|
+
".exe", ".dll", ".so", ".dylib", ".bin", ".pyc", ".pyd", ".class", ".o", ".obj",
|
|
69
|
+
# Archives & Compressed
|
|
70
|
+
".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".iso", ".dmg",
|
|
71
|
+
# Documents & Media
|
|
72
|
+
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
|
|
73
|
+
".mp3", ".mp4", ".wav", ".avi", ".mov", ".mkv", ".flac", ".ogg",
|
|
74
|
+
# Fonts
|
|
75
|
+
".woff", ".woff2", ".ttf", ".otf", ".eot",
|
|
76
|
+
# Databases
|
|
77
|
+
".sqlite", ".sqlite3", ".db",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class ScannedFile:
|
|
83
|
+
"""Represents a discovered project file."""
|
|
84
|
+
path: Path
|
|
85
|
+
rel_path: str
|
|
86
|
+
size: int
|
|
87
|
+
is_text: bool = True
|
|
88
|
+
|
|
89
|
+
def __lt__(self, other: ScannedFile) -> bool:
|
|
90
|
+
return self.rel_path.lower() < other.rel_path.lower()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_binary_file(file_path: Path) -> bool:
|
|
94
|
+
"""
|
|
95
|
+
Check if a file is binary using extension lookup and null-byte heuristic.
|
|
96
|
+
"""
|
|
97
|
+
if file_path.suffix.lower() in BINARY_EXTENSIONS:
|
|
98
|
+
return True
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
with open(file_path, "rb") as f:
|
|
102
|
+
chunk = f.read(1024)
|
|
103
|
+
if b"\x00" in chunk:
|
|
104
|
+
return True
|
|
105
|
+
except (OSError, PermissionError):
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_ignore_spec(root_path: Path, extra_patterns: Sequence[str] | None = None) -> pathspec.PathSpec:
|
|
112
|
+
"""
|
|
113
|
+
Compile a PathSpec matcher from default patterns and local .gitignore/.ignore files.
|
|
114
|
+
"""
|
|
115
|
+
patterns: list[str] = list(DEFAULT_IGNORE_PATTERNS)
|
|
116
|
+
|
|
117
|
+
if extra_patterns:
|
|
118
|
+
patterns.extend(extra_patterns)
|
|
119
|
+
|
|
120
|
+
# Read .gitignore if present in root
|
|
121
|
+
gitignore_path = root_path / ".gitignore"
|
|
122
|
+
if gitignore_path.is_file():
|
|
123
|
+
try:
|
|
124
|
+
with open(gitignore_path, "r", encoding="utf-8", errors="replace") as f:
|
|
125
|
+
patterns.extend(f.read().splitlines())
|
|
126
|
+
except (OSError, PermissionError):
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
# Read .ignore if present in root
|
|
130
|
+
ignore_path = root_path / ".ignore"
|
|
131
|
+
if ignore_path.is_file():
|
|
132
|
+
try:
|
|
133
|
+
with open(ignore_path, "r", encoding="utf-8", errors="replace") as f:
|
|
134
|
+
patterns.extend(f.read().splitlines())
|
|
135
|
+
except (OSError, PermissionError):
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
return pathspec.PathSpec.from_lines("gitwildmatch", patterns)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def scan_directory(
|
|
142
|
+
root_path: Path,
|
|
143
|
+
extra_patterns: Sequence[str] | None = None,
|
|
144
|
+
max_file_size: int = MAX_FILE_SIZE,
|
|
145
|
+
) -> list[ScannedFile]:
|
|
146
|
+
"""
|
|
147
|
+
Scan the target directory recursively, filtering out ignored, binary,
|
|
148
|
+
and oversized files. Early-prunes ignored directories for high performance.
|
|
149
|
+
"""
|
|
150
|
+
root_path = root_path.resolve()
|
|
151
|
+
if not root_path.exists() or not root_path.is_dir():
|
|
152
|
+
return []
|
|
153
|
+
|
|
154
|
+
spec = load_ignore_spec(root_path, extra_patterns=extra_patterns)
|
|
155
|
+
scanned_files: list[ScannedFile] = []
|
|
156
|
+
|
|
157
|
+
for dirpath, dirnames, filenames in os.walk(root_path, topdown=True):
|
|
158
|
+
current_dir = Path(dirpath)
|
|
159
|
+
rel_dir = current_dir.relative_to(root_path).as_posix()
|
|
160
|
+
|
|
161
|
+
# Prune ignored directories in-place to skip descending into them
|
|
162
|
+
pruned_dirs: list[str] = []
|
|
163
|
+
for d in dirnames:
|
|
164
|
+
rel_subdir = f"{rel_dir}/{d}" if rel_dir != "." else d
|
|
165
|
+
# Match both as directory and generic pattern
|
|
166
|
+
if spec.match_file(rel_subdir) or spec.match_file(f"{rel_subdir}/"):
|
|
167
|
+
continue
|
|
168
|
+
pruned_dirs.append(d)
|
|
169
|
+
dirnames[:] = pruned_dirs
|
|
170
|
+
|
|
171
|
+
# Process files in current directory
|
|
172
|
+
for filename in filenames:
|
|
173
|
+
file_path = current_dir / filename
|
|
174
|
+
rel_file = f"{rel_dir}/{filename}" if rel_dir != "." else filename
|
|
175
|
+
|
|
176
|
+
# Check ignore rules
|
|
177
|
+
if spec.match_file(rel_file):
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
stat = file_path.stat()
|
|
182
|
+
file_size = stat.st_size
|
|
183
|
+
except (OSError, PermissionError):
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
# Skip oversized files
|
|
187
|
+
if file_size > max_file_size:
|
|
188
|
+
continue
|
|
189
|
+
|
|
190
|
+
# Skip binary files
|
|
191
|
+
if is_binary_file(file_path):
|
|
192
|
+
continue
|
|
193
|
+
|
|
194
|
+
scanned_files.append(
|
|
195
|
+
ScannedFile(
|
|
196
|
+
path=file_path,
|
|
197
|
+
rel_path=rel_file,
|
|
198
|
+
size=file_size,
|
|
199
|
+
is_text=True,
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
scanned_files.sort()
|
|
204
|
+
return scanned_files
|
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TUI module for anix-ctx.
|
|
3
|
+
Provides an interactive terminal user interface built with Textual in ANIX dark neon style.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import pyperclip
|
|
12
|
+
from textual.app import App, ComposeResult
|
|
13
|
+
from textual.binding import Binding
|
|
14
|
+
from textual.containers import Container, Horizontal, Vertical, VerticalScroll
|
|
15
|
+
from textual.widgets import Footer, Header, Static, Tree
|
|
16
|
+
from textual.widgets.tree import TreeNode
|
|
17
|
+
|
|
18
|
+
from anix_ctx.formatter import (
|
|
19
|
+
build_ascii_tree,
|
|
20
|
+
estimate_tokens,
|
|
21
|
+
format_context,
|
|
22
|
+
read_file_safe,
|
|
23
|
+
)
|
|
24
|
+
from anix_ctx.scanner import ScannedFile, scan_directory
|
|
25
|
+
|
|
26
|
+
TUI_CSS = """
|
|
27
|
+
Screen {
|
|
28
|
+
background: #0d1117;
|
|
29
|
+
color: #e6edf3;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
Header {
|
|
33
|
+
background: #161b22;
|
|
34
|
+
color: #00e5ff;
|
|
35
|
+
dock: top;
|
|
36
|
+
height: 1;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
Footer {
|
|
40
|
+
background: #161b22;
|
|
41
|
+
color: #8b949e;
|
|
42
|
+
dock: bottom;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
#main-container {
|
|
46
|
+
layout: horizontal;
|
|
47
|
+
height: 1fr;
|
|
48
|
+
background: #0d1117;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#tree-pane {
|
|
52
|
+
width: 52%;
|
|
53
|
+
height: 100%;
|
|
54
|
+
border-right: solid #30363d;
|
|
55
|
+
padding: 0 1;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
#info-pane {
|
|
59
|
+
width: 48%;
|
|
60
|
+
height: 100%;
|
|
61
|
+
padding: 0 1;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
Tree {
|
|
65
|
+
background: #0d1117;
|
|
66
|
+
color: #e6edf3;
|
|
67
|
+
padding: 0;
|
|
68
|
+
scrollbar-color: #00e5ff;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
Tree:focus {
|
|
72
|
+
border: none;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
.panel-title {
|
|
76
|
+
color: #00e5ff;
|
|
77
|
+
text-style: bold;
|
|
78
|
+
padding: 0 0 1 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
.stats-card {
|
|
82
|
+
background: #161b22;
|
|
83
|
+
border: round #30363d;
|
|
84
|
+
padding: 1;
|
|
85
|
+
margin-bottom: 1;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
.stat-row {
|
|
89
|
+
margin-bottom: 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
.stat-label {
|
|
93
|
+
color: #8b949e;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
.stat-value {
|
|
97
|
+
color: #00e5ff;
|
|
98
|
+
text-style: bold;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
.stat-highlight {
|
|
102
|
+
color: #58a6ff;
|
|
103
|
+
text-style: bold;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#tree-preview {
|
|
107
|
+
background: #161b22;
|
|
108
|
+
border: round #30363d;
|
|
109
|
+
padding: 1;
|
|
110
|
+
height: 1fr;
|
|
111
|
+
color: #8b949e;
|
|
112
|
+
overflow-y: auto;
|
|
113
|
+
}
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def format_bytes(size: int) -> str:
|
|
118
|
+
"""Format file size into human-readable string."""
|
|
119
|
+
if size < 1024:
|
|
120
|
+
return f"{size} B"
|
|
121
|
+
elif size < 1024 * 1024:
|
|
122
|
+
return f"{size / 1024:.1f} KB"
|
|
123
|
+
return f"{size / (1024 * 1024):.1f} MB"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class AnixCtxApp(App[None]):
|
|
127
|
+
"""Main Textual application for interactive context packaging."""
|
|
128
|
+
|
|
129
|
+
TITLE = "ANIX // CTX"
|
|
130
|
+
SUB_TITLE = "Context Packager"
|
|
131
|
+
CSS = TUI_CSS
|
|
132
|
+
|
|
133
|
+
BINDINGS = [
|
|
134
|
+
Binding("space", "toggle_node", "Toggle", priority=True),
|
|
135
|
+
Binding("a", "toggle_all", "Select/Deselect All"),
|
|
136
|
+
Binding("c", "copy_context", "Copy Clipboard"),
|
|
137
|
+
Binding("s", "save_context", "Save context.md"),
|
|
138
|
+
Binding("q", "quit", "Quit"),
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
def __init__(self, target_dir: Path) -> None:
|
|
142
|
+
super().__init__()
|
|
143
|
+
self.target_dir = target_dir.resolve()
|
|
144
|
+
self.scanned_files: list[ScannedFile] = []
|
|
145
|
+
# Pre-cached character counts to avoid disk reads on every toggle
|
|
146
|
+
self.char_cache: dict[Path, int] = {}
|
|
147
|
+
# Selection state: mapping from ScannedFile to bool
|
|
148
|
+
self.selection_map: dict[ScannedFile, bool] = {}
|
|
149
|
+
# Mapping from Tree node ID to node data
|
|
150
|
+
self.node_file_map: dict[int, ScannedFile] = {}
|
|
151
|
+
|
|
152
|
+
def compose(self) -> ComposeResult:
|
|
153
|
+
yield Header(show_clock=True)
|
|
154
|
+
with Horizontal(id="main-container"):
|
|
155
|
+
with Vertical(id="tree-pane"):
|
|
156
|
+
yield Static("📁 PROJECT FILES", classes="panel-title")
|
|
157
|
+
yield Tree(self.target_dir.name, id="file-tree")
|
|
158
|
+
with Vertical(id="info-pane"):
|
|
159
|
+
yield Static("⚡ LIVE STATS", classes="panel-title")
|
|
160
|
+
with Vertical(classes="stats-card", id="stats-widget"):
|
|
161
|
+
yield Static("", id="stat-files")
|
|
162
|
+
yield Static("", id="stat-chars")
|
|
163
|
+
yield Static("", id="stat-tokens")
|
|
164
|
+
yield Static("", id="stat-top5")
|
|
165
|
+
yield Static("🌳 ASCII TREE PREVIEW", classes="panel-title")
|
|
166
|
+
yield VerticalScroll(Static("", id="preview-content"), id="tree-preview")
|
|
167
|
+
yield Footer()
|
|
168
|
+
|
|
169
|
+
def on_mount(self) -> None:
|
|
170
|
+
"""Scan directory, cache sizes, build tree, and compute initial stats."""
|
|
171
|
+
self.scanned_files = scan_directory(self.target_dir)
|
|
172
|
+
|
|
173
|
+
# Pre-cache characters for fast, zero-I/O live stat calculations
|
|
174
|
+
for f in self.scanned_files:
|
|
175
|
+
content = read_file_safe(f.path)
|
|
176
|
+
self.char_cache[f.path] = len(content)
|
|
177
|
+
self.selection_map[f] = True # Selected by default
|
|
178
|
+
|
|
179
|
+
self._populate_tree()
|
|
180
|
+
self._refresh_stats()
|
|
181
|
+
|
|
182
|
+
def _populate_tree(self) -> None:
|
|
183
|
+
"""Construct the hierarchical file tree with checkbox states."""
|
|
184
|
+
tree: Tree[Any] = self.query_one("#file-tree", Tree)
|
|
185
|
+
tree.root.expand()
|
|
186
|
+
|
|
187
|
+
dir_nodes: dict[str, TreeNode[Any]] = {"": tree.root}
|
|
188
|
+
|
|
189
|
+
for f in self.scanned_files:
|
|
190
|
+
parts = f.rel_path.split("/")
|
|
191
|
+
# Create directory nodes along the path
|
|
192
|
+
curr_dir = ""
|
|
193
|
+
for part in parts[:-1]:
|
|
194
|
+
parent_dir = curr_dir
|
|
195
|
+
curr_dir = f"{curr_dir}/{part}" if curr_dir else part
|
|
196
|
+
if curr_dir not in dir_nodes:
|
|
197
|
+
parent_node = dir_nodes[parent_dir]
|
|
198
|
+
dir_nodes[curr_dir] = parent_node.add(
|
|
199
|
+
f"📁 [bold]{part}/[/]",
|
|
200
|
+
expand=True,
|
|
201
|
+
data={"type": "dir", "path": curr_dir},
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
# Add file leaf
|
|
205
|
+
file_name = parts[-1]
|
|
206
|
+
parent_node = dir_nodes[curr_dir]
|
|
207
|
+
is_selected = self.selection_map.get(f, True)
|
|
208
|
+
chars = self.char_cache.get(f.path, f.size)
|
|
209
|
+
|
|
210
|
+
checkbox = "[bold #00e5ff]\[x][/]" if is_selected else "[dim #8b949e]\[ ][/]"
|
|
211
|
+
label = f"{checkbox} {file_name} [dim #8b949e]({format_bytes(f.size)} / ~{chars // 4} tok)[/]"
|
|
212
|
+
|
|
213
|
+
leaf = parent_node.add_leaf(
|
|
214
|
+
label,
|
|
215
|
+
data={"type": "file", "file": f},
|
|
216
|
+
)
|
|
217
|
+
self.node_file_map[leaf.id] = f
|
|
218
|
+
|
|
219
|
+
self._update_all_dir_labels(tree.root)
|
|
220
|
+
|
|
221
|
+
def _update_file_label(self, node: TreeNode[Any], scanned_file: ScannedFile) -> None:
|
|
222
|
+
"""Update checkbox label for a single file node."""
|
|
223
|
+
is_selected = self.selection_map.get(scanned_file, True)
|
|
224
|
+
file_name = scanned_file.path.name
|
|
225
|
+
chars = self.char_cache.get(scanned_file.path, scanned_file.size)
|
|
226
|
+
|
|
227
|
+
checkbox = "[bold #00e5ff]\[x][/]" if is_selected else "[dim #8b949e]\[ ][/]"
|
|
228
|
+
node.set_label(
|
|
229
|
+
f"{checkbox} {file_name} [dim #8b949e]({format_bytes(scanned_file.size)} / ~{chars // 4} tok)[/]"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def _get_files_under_node(self, node: TreeNode[Any]) -> list[ScannedFile]:
|
|
233
|
+
"""Collect all ScannedFile instances under a tree branch."""
|
|
234
|
+
files: list[ScannedFile] = []
|
|
235
|
+
if node.data and node.data.get("type") == "file":
|
|
236
|
+
files.append(node.data["file"])
|
|
237
|
+
for child in node.children:
|
|
238
|
+
files.extend(self._get_files_under_node(child))
|
|
239
|
+
return files
|
|
240
|
+
|
|
241
|
+
def _update_all_dir_labels(self, node: TreeNode[Any]) -> tuple[int, int]:
|
|
242
|
+
"""
|
|
243
|
+
Recursively update directory labels with child selection ratios.
|
|
244
|
+
Returns (selected_count, total_count).
|
|
245
|
+
"""
|
|
246
|
+
if node.data and node.data.get("type") == "file":
|
|
247
|
+
f = node.data["file"]
|
|
248
|
+
is_sel = 1 if self.selection_map.get(f, False) else 0
|
|
249
|
+
return is_sel, 1
|
|
250
|
+
|
|
251
|
+
selected_sub = 0
|
|
252
|
+
total_sub = 0
|
|
253
|
+
|
|
254
|
+
for child in node.children:
|
|
255
|
+
sel, tot = self._update_all_dir_labels(child)
|
|
256
|
+
selected_sub += sel
|
|
257
|
+
total_sub += tot
|
|
258
|
+
|
|
259
|
+
if node != self.query_one("#file-tree", Tree).root and node.data and node.data.get("type") == "dir":
|
|
260
|
+
dir_name = node.data["path"].split("/")[-1]
|
|
261
|
+
if selected_sub == total_sub and total_sub > 0:
|
|
262
|
+
box = "[bold #00e5ff]\[x][/]"
|
|
263
|
+
elif selected_sub == 0:
|
|
264
|
+
box = "[dim #8b949e]\[ ][/]"
|
|
265
|
+
else:
|
|
266
|
+
box = "[bold #00e5ff]\[-][/]"
|
|
267
|
+
node.set_label(f"{box} 📁 [bold]{dir_name}/[/] [dim #8b949e]({selected_sub}/{total_sub})[/]")
|
|
268
|
+
|
|
269
|
+
return selected_sub, total_sub
|
|
270
|
+
|
|
271
|
+
def _refresh_stats(self) -> None:
|
|
272
|
+
"""Update the live statistics and ASCII tree preview using in-memory cache."""
|
|
273
|
+
selected_files = [f for f, sel in self.selection_map.items() if sel]
|
|
274
|
+
total_files = len(self.scanned_files)
|
|
275
|
+
total_selected = len(selected_files)
|
|
276
|
+
|
|
277
|
+
total_chars = sum(self.char_cache.get(f.path, 0) for f in selected_files)
|
|
278
|
+
total_tokens = estimate_tokens(total_chars)
|
|
279
|
+
|
|
280
|
+
# Update stats widgets
|
|
281
|
+
self.query_one("#stat-files", Static).update(
|
|
282
|
+
f"[#8b949e]Selected Files:[/] [bold #00e5ff]{total_selected}[/] / {total_files}"
|
|
283
|
+
)
|
|
284
|
+
self.query_one("#stat-chars", Static).update(
|
|
285
|
+
f"[#8b949e]Total Characters:[/] [bold #58a6ff]{total_chars:,}[/]"
|
|
286
|
+
)
|
|
287
|
+
self.query_one("#stat-tokens", Static).update(
|
|
288
|
+
f"[#8b949e]Estimated Tokens:[/] [bold #00e5ff]~{total_tokens:,}[/] [dim](chars // 4)[/]"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
# Top 5 heaviest files
|
|
292
|
+
file_weights = [(f.rel_path, self.char_cache.get(f.path, 0)) for f in selected_files]
|
|
293
|
+
file_weights.sort(key=lambda x: x[1], reverse=True)
|
|
294
|
+
top5 = file_weights[:5]
|
|
295
|
+
|
|
296
|
+
if top5:
|
|
297
|
+
top5_lines = ["[#8b949e]Top Heaviest Files:[/][dim]"]
|
|
298
|
+
for path, chars in top5:
|
|
299
|
+
top5_lines.append(f" • [white]{path}[/] (~{chars // 4:,} tok)")
|
|
300
|
+
top5_lines.append("[/dim]")
|
|
301
|
+
self.query_one("#stat-top5", Static).update("\n".join(top5_lines))
|
|
302
|
+
else:
|
|
303
|
+
self.query_one("#stat-top5", Static).update("[dim #8b949e]No files selected[/]")
|
|
304
|
+
|
|
305
|
+
# ASCII tree preview
|
|
306
|
+
rel_paths = [f.rel_path for f in selected_files]
|
|
307
|
+
tree_text = build_ascii_tree(rel_paths, root_name=self.target_dir.name)
|
|
308
|
+
self.query_one("#preview-content", Static).update(tree_text)
|
|
309
|
+
|
|
310
|
+
def action_toggle_node(self) -> None:
|
|
311
|
+
"""Toggle checkbox of the currently highlighted node (file or directory)."""
|
|
312
|
+
tree: Tree[Any] = self.query_one("#file-tree", Tree)
|
|
313
|
+
node = tree.cursor_node
|
|
314
|
+
if not node or not node.data:
|
|
315
|
+
return
|
|
316
|
+
|
|
317
|
+
node_data = node.data
|
|
318
|
+
if node_data.get("type") == "file":
|
|
319
|
+
f = node_data["file"]
|
|
320
|
+
self.selection_map[f] = not self.selection_map.get(f, True)
|
|
321
|
+
self._update_file_label(node, f)
|
|
322
|
+
elif node_data.get("type") == "dir" or node == tree.root:
|
|
323
|
+
sub_files = self._get_files_under_node(node)
|
|
324
|
+
all_selected = all(self.selection_map.get(f, False) for f in sub_files)
|
|
325
|
+
new_state = not all_selected
|
|
326
|
+
for f in sub_files:
|
|
327
|
+
self.selection_map[f] = new_state
|
|
328
|
+
|
|
329
|
+
# Refresh labels of all descendants
|
|
330
|
+
def _refresh_sub(n: TreeNode[Any]) -> None:
|
|
331
|
+
if n.data and n.data.get("type") == "file":
|
|
332
|
+
self._update_file_label(n, n.data["file"])
|
|
333
|
+
for ch in n.children:
|
|
334
|
+
_refresh_sub(ch)
|
|
335
|
+
|
|
336
|
+
_refresh_sub(node)
|
|
337
|
+
|
|
338
|
+
self._update_all_dir_labels(tree.root)
|
|
339
|
+
self._refresh_stats()
|
|
340
|
+
|
|
341
|
+
def on_tree_node_selected(self, event: Tree.NodeSelected[Any]) -> None:
|
|
342
|
+
"""Handle Enter key or click on tree node."""
|
|
343
|
+
node = event.node
|
|
344
|
+
if node.data and node.data.get("type") == "file":
|
|
345
|
+
self.action_toggle_node()
|
|
346
|
+
else:
|
|
347
|
+
node.toggle()
|
|
348
|
+
|
|
349
|
+
def action_toggle_all(self) -> None:
|
|
350
|
+
"""Toggle all files: select all if any deselected, otherwise deselect all."""
|
|
351
|
+
tree: Tree[Any] = self.query_one("#file-tree", Tree)
|
|
352
|
+
any_unselected = any(not sel for sel in self.selection_map.values())
|
|
353
|
+
new_state = any_unselected
|
|
354
|
+
|
|
355
|
+
for f in self.scanned_files:
|
|
356
|
+
self.selection_map[f] = new_state
|
|
357
|
+
|
|
358
|
+
def _refresh_all(node: TreeNode[Any]) -> None:
|
|
359
|
+
if node.data and node.data.get("type") == "file":
|
|
360
|
+
self._update_file_label(node, node.data["file"])
|
|
361
|
+
for ch in node.children:
|
|
362
|
+
_refresh_all(ch)
|
|
363
|
+
|
|
364
|
+
_refresh_all(tree.root)
|
|
365
|
+
self._update_all_dir_labels(tree.root)
|
|
366
|
+
self._refresh_stats()
|
|
367
|
+
|
|
368
|
+
msg = "All files selected" if new_state else "All files deselected"
|
|
369
|
+
self.notify(msg, title="ANIX CTX")
|
|
370
|
+
|
|
371
|
+
def action_copy_context(self) -> None:
|
|
372
|
+
"""Pack selected files and copy to clipboard."""
|
|
373
|
+
selected_files = [f for f, sel in self.selection_map.items() if sel]
|
|
374
|
+
if not selected_files:
|
|
375
|
+
self.notify("No files selected to copy!", title="ANIX CTX", severity="warning")
|
|
376
|
+
return
|
|
377
|
+
|
|
378
|
+
formatted = format_context(selected_files, root_name=self.target_dir.name)
|
|
379
|
+
try:
|
|
380
|
+
pyperclip.copy(formatted)
|
|
381
|
+
tokens = estimate_tokens(sum(self.char_cache.get(f.path, 0) for f in selected_files))
|
|
382
|
+
self.notify(
|
|
383
|
+
f"Copied {len(selected_files)} files (~{tokens:,} tokens) to clipboard!",
|
|
384
|
+
title="ANIX CTX",
|
|
385
|
+
)
|
|
386
|
+
except Exception as exc:
|
|
387
|
+
self.notify(f"Clipboard error: {exc}", title="ANIX CTX", severity="error")
|
|
388
|
+
|
|
389
|
+
def action_save_context(self) -> None:
|
|
390
|
+
"""Pack selected files and save to context.md in target directory."""
|
|
391
|
+
selected_files = [f for f, sel in self.selection_map.items() if sel]
|
|
392
|
+
if not selected_files:
|
|
393
|
+
self.notify("No files selected to save!", title="ANIX CTX", severity="warning")
|
|
394
|
+
return
|
|
395
|
+
|
|
396
|
+
out_path = self.target_dir / "context.md"
|
|
397
|
+
formatted = format_context(selected_files, root_name=self.target_dir.name)
|
|
398
|
+
try:
|
|
399
|
+
with open(out_path, "w", encoding="utf-8", errors="replace") as f:
|
|
400
|
+
f.write(formatted)
|
|
401
|
+
tokens = estimate_tokens(sum(self.char_cache.get(f.path, 0) for f in selected_files))
|
|
402
|
+
self.notify(
|
|
403
|
+
f"Saved {len(selected_files)} files (~{tokens:,} tokens) to context.md",
|
|
404
|
+
title="ANIX CTX",
|
|
405
|
+
)
|
|
406
|
+
except Exception as exc:
|
|
407
|
+
self.notify(f"File save error: {exc}", title="ANIX CTX", severity="error")
|
|
408
|
+
|