-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
225 lines (188 loc) · 7.71 KB
/
Copy pathreport.py
File metadata and controls
225 lines (188 loc) · 7.71 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""Generate a basic HTML report from FolderVisualizer scan JSON."""
from __future__ import annotations
import html
import json
from pathlib import Path
from typing import Any
PROJECT_DIR = Path(__file__).resolve().parent
INPUT_PATH = PROJECT_DIR / "outputs" / "scan-result.json"
OUTPUT_PATH = PROJECT_DIR / "outputs" / "report.html"
MAX_ITEMS = 20
def _format_size(size: int) -> str:
units = ("B", "KB", "MB", "GB", "TB")
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{int(value)} {unit}" if unit == "B" else f"{value:.2f} {unit}"
value /= 1024
return f"{size} B"
def _node_size(node: dict[str, Any]) -> int:
size = node.get("size", 0)
return size if isinstance(size, int) and not isinstance(size, bool) else 0
def _collect_nodes(root: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
files: list[dict[str, Any]] = []
directories: list[dict[str, Any]] = []
pending = [root]
while pending:
node = pending.pop()
node_type = node.get("type")
if node_type == "file":
files.append(node)
elif node_type == "directory":
directories.append(node)
children = node.get("children", [])
if isinstance(children, list):
pending.extend(child for child in children if isinstance(child, dict))
sort_key = lambda node: (-_node_size(node), str(node.get("path", "")).casefold())
files.sort(key=sort_key)
directories.sort(key=sort_key)
return files, directories
def _render_rows(nodes: list[dict[str, Any]], empty_message: str) -> str:
if not nodes:
return f'<tr><td colspan="3" class="empty">{html.escape(empty_message)}</td></tr>'
rows = []
for index, node in enumerate(nodes[:MAX_ITEMS], start=1):
path = html.escape(str(node.get("path", "")), quote=True)
size = _node_size(node)
rows.append(
"<tr>"
f'<td class="rank">{index}</td>'
f'<td class="path" title="{path}">{path}</td>'
f'<td class="size">{_format_size(size)}'
f'<span>{size:,} 字节</span></td>'
"</tr>"
)
return "\n".join(rows)
def load_scan_result(path: Path = INPUT_PATH) -> dict[str, Any]:
"""Load and minimally validate a scan result JSON file."""
with path.open("r", encoding="utf-8") as input_file:
data = json.load(input_file)
if not isinstance(data, dict) or not isinstance(data.get("root"), dict):
raise ValueError("JSON 中缺少有效的 root 节点")
return data
def generate_html(data: dict[str, Any]) -> str:
"""Build a standalone HTML report from scan result data."""
root = data["root"]
files, directories = _collect_nodes(root)
errors = data.get("errors", [])
error_count = len(errors) if isinstance(errors, list) else 0
scan_path = html.escape(str(root.get("path", "")), quote=True)
total_size = data.get("total_size", 0)
total_size = total_size if isinstance(total_size, int) else 0
file_count = data.get("file_count", 0)
directory_count = data.get("directory_count", 0)
file_rows = _render_rows(files, "没有扫描到文件")
directory_rows = _render_rows(directories, "没有扫描到目录")
return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FolderVisualizer 扫描报告</title>
<style>
:root {{
color-scheme: light;
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
color: #172033;
background: #f3f6fa;
}}
* {{ box-sizing: border-box; }}
body {{ margin: 0; background: #f3f6fa; }}
main {{ width: min(1120px, calc(100% - 32px)); margin: 40px auto; }}
header {{ margin-bottom: 24px; }}
h1 {{ margin: 0 0 10px; font-size: 30px; }}
.scan-path {{ margin: 0; color: #596579; overflow-wrap: anywhere; }}
.cards {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 14px;
margin-bottom: 24px;
}}
.card, section {{
background: #ffffff;
border: 1px solid #e1e7ef;
border-radius: 12px;
box-shadow: 0 5px 18px rgba(32, 48, 72, 0.05);
}}
.card {{ padding: 18px; }}
.card .label {{ color: #6a7588; font-size: 14px; }}
.card .value {{ margin-top: 7px; font-size: 23px; font-weight: 650; }}
section {{ margin-bottom: 20px; overflow: hidden; }}
h2 {{ margin: 0; padding: 18px 20px; font-size: 19px; border-bottom: 1px solid #e7ecf2; }}
.table-wrap {{ overflow-x: auto; }}
table {{ width: 100%; border-collapse: collapse; }}
th, td {{ padding: 13px 16px; border-bottom: 1px solid #edf0f4; text-align: left; }}
th {{ color: #606c80; background: #fafbfd; font-size: 13px; }}
tbody tr:last-child td {{ border-bottom: 0; }}
tbody tr:hover {{ background: #f8faff; }}
.rank {{ width: 64px; color: #7a8598; text-align: center; }}
.path {{ min-width: 360px; overflow-wrap: anywhere; }}
.size {{ width: 150px; white-space: nowrap; font-weight: 600; }}
.size span {{ display: block; margin-top: 3px; color: #7a8598; font-size: 12px; font-weight: 400; }}
.empty {{ padding: 28px; color: #7a8598; text-align: center; }}
footer {{ padding: 4px 0 20px; color: #7a8598; font-size: 13px; text-align: center; }}
@media (max-width: 600px) {{
main {{ width: min(100% - 20px, 1120px); margin-top: 22px; }}
h1 {{ font-size: 25px; }}
th, td {{ padding: 11px 12px; }}
}}
</style>
</head>
<body>
<main>
<header>
<h1>FolderVisualizer 扫描报告</h1>
<p class="scan-path"><strong>扫描路径:</strong>{scan_path}</p>
</header>
<div class="cards">
<div class="card"><div class="label">总大小</div><div class="value">{_format_size(total_size)}</div></div>
<div class="card"><div class="label">文件数量</div><div class="value">{html.escape(str(file_count))}</div></div>
<div class="card"><div class="label">目录数量</div><div class="value">{html.escape(str(directory_count))}</div></div>
<div class="card"><div class="label">错误数量</div><div class="value">{error_count}</div></div>
</div>
<section>
<h2>最大的文件(前 {MAX_ITEMS})</h2>
<div class="table-wrap">
<table>
<thead><tr><th class="rank">排名</th><th>文件路径</th><th>大小</th></tr></thead>
<tbody>{file_rows}</tbody>
</table>
</div>
</section>
<section>
<h2>最大的目录(前 {MAX_ITEMS})</h2>
<div class="table-wrap">
<table>
<thead><tr><th class="rank">排名</th><th>目录路径</th><th>累计大小</th></tr></thead>
<tbody>{directory_rows}</tbody>
</table>
</div>
</section>
<footer>由 FolderVisualizer v0.2.0 生成</footer>
</main>
</body>
</html>
"""
def save_report(data: dict[str, Any], path: Path = OUTPUT_PATH) -> Path:
"""Write the generated report as UTF-8 HTML."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(generate_html(data), encoding="utf-8")
return path
def main() -> int:
try:
data = load_scan_result()
output_path = save_report(data)
except FileNotFoundError:
print(f'错误: 找不到扫描结果 "{INPUT_PATH}",请先运行 main.py。')
return 1
except json.JSONDecodeError as error:
print(f"错误: scan-result.json 格式无效: {error}")
return 1
except (OSError, ValueError) as error:
print(f"错误: 无法生成报告: {error}")
return 1
print("HTML 报告生成完成")
print(f"报告文件: {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())