-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscanner.py
More file actions
175 lines (154 loc) · 5.82 KB
/
scanner.py
File metadata and controls
175 lines (154 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import os
import pathlib
from pathlib import Path
READABLE = {
# Docs
'.md', '.markdown', '.txt', '.rst', '.adoc',
# Code
'.py', '.js', '.ts', '.jsx', '.tsx', '.sh', '.bash',
'.zsh', '.ps1', '.rb', '.go', '.rs', '.cpp', '.c',
'.h', '.java', '.kt', '.swift', '.php', '.lua',
# Config / data
'.json', '.yaml', '.yml', '.toml', '.ini', '.env',
'.cfg', '.conf', '.xml', '.csv',
# Web
'.html', '.css', '.scss', '.svg',
}
SKIP = {
# Binaries / executables
'.exe', '.dll', '.so', '.dylib', '.bin', '.dat',
# Archives
'.zip', '.tar', '.gz', '.rar', '.7z', '.bz2',
# Media
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico',
'.mp3', '.mp4', '.wav', '.avi', '.mov',
# Compiled
'.pyc', '.pyo', '.class', '.o', '.a',
# Misc binary
'.pdf', '.doc', '.docx', '.xls', '.xlsx',
'.sqlite', '.db', '.lock',
}
SKIP_DIRS = {
'node_modules', '.git', '__pycache__', '.venv',
'venv', 'env', 'dist', 'build', '.next', '.nuxt',
}
def generate_tree(dir_path: Path, prefix: str = "", is_last: bool = True, is_root: bool = True) -> str:
if not dir_path.is_dir():
return ""
tree = ""
if is_root:
tree += f"{dir_path.name}/\n"
try:
items = list(dir_path.iterdir())
valid_items = []
for item in items:
if item.is_dir() and item.name in SKIP_DIRS:
continue
valid_items.append(item)
valid_items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))
for i, item in enumerate(valid_items):
last = (i == len(valid_items) - 1)
marker = "└── " if last else "├── "
if item.is_dir():
tree += f"{prefix}{marker}{item.name}/\n"
new_prefix = prefix + (" " if last else "│ ")
tree += generate_tree(item, new_prefix, last, is_root=False)
else:
tree += f"{prefix}{marker}{item.name}\n"
except Exception:
pass
return tree
def scan(path: str) -> dict:
target = Path(path).resolve()
result = {
"input_type": "folder" if target.is_dir() else "file",
"name": target.name,
"total_files_found": 0,
"readable_files": 0,
"skipped_files": 0,
"file_tree": "",
"files": [],
"skipped": []
}
if target.is_dir():
result["file_tree"] = generate_tree(target).strip()
else:
result["file_tree"] = target.name
def process_file(file_path: Path, rel_path: str):
result["total_files_found"] += 1
# Check explicit skip lists
ext = file_path.suffix.lower()
if ext in SKIP:
result["skipped_files"] += 1
result["skipped"].append({
"relative_path": rel_path,
"reason": f"binary file ({ext})"
})
return
if ext and ext not in READABLE:
pass # Try to read anyway if not in skip, but if string decode fails it will be skipped
try:
size_bytes = file_path.stat().st_size
if size_bytes > 50 * 1024:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read(8000)
content += f"\n... [TRUNCATED — file is {size_bytes//1024}kb, showing first 8000 chars]"
truncated = True
else:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
truncated = False
result["readable_files"] += 1
result["files"].append({
"relative_path": rel_path,
"extension": ext,
"size_bytes": size_bytes,
"content": content,
"truncated": truncated
})
except UnicodeDecodeError:
try:
# Fallback to latin-1
if size_bytes > 50 * 1024:
with open(file_path, 'r', encoding='latin-1') as f:
content = f.read(8000)
content += f"\n... [TRUNCATED — file is {size_bytes//1024}kb, showing first 8000 chars]"
truncated = True
else:
with open(file_path, 'r', encoding='latin-1') as f:
content = f.read()
truncated = False
result["readable_files"] += 1
result["files"].append({
"relative_path": rel_path,
"extension": ext,
"size_bytes": size_bytes,
"content": content,
"truncated": truncated
})
except Exception as e:
result["skipped_files"] += 1
result["skipped"].append({
"relative_path": rel_path,
"reason": f"encoding error / unreadable: {str(e)}"
})
except Exception as e:
result["skipped_files"] += 1
result["skipped"].append({
"relative_path": rel_path,
"reason": str(e)
})
if target.is_file():
process_file(target, target.name)
elif target.is_dir():
for root, dirs, files in os.walk(target):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith('.git')]
root_path = Path(root)
for file in files:
file_path = root_path / file
try:
rel_path = str(file_path.relative_to(target)).replace('\\', '/')
except ValueError:
rel_path = file_path.name
process_file(file_path, rel_path)
return result