-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlarge_visual_export.py
More file actions
981 lines (884 loc) · 26.9 KB
/
Copy pathlarge_visual_export.py
File metadata and controls
981 lines (884 loc) · 26.9 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
"""Export a compact SVG overview from a large FolderVisualizer SQLite index."""
from __future__ import annotations
import argparse
import math
import os
import re
import sqlite3
import time
import unicodedata
import xml.etree.ElementTree as ET
from contextlib import closing
from dataclasses import dataclass
from pathlib import Path
from typing import Any
PROJECT_DIR = Path(__file__).resolve().parent
DEFAULT_DATABASE_PATH = PROJECT_DIR / "outputs" / "folder-index.db"
DEFAULT_OUTPUT_DIR = PROJECT_DIR / "outputs" / "exports"
DEFAULT_OVERVIEW_LIMIT = 60
MAX_OVERVIEW_LIMIT = 100
SVG_NAMESPACE = "http://www.w3.org/2000/svg"
FONT_FAMILY = "Segoe UI, Microsoft YaHei, Noto Sans CJK SC, sans-serif"
INVALID_FILENAME_CHARACTERS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
REQUIRED_NODE_COLUMNS = {
"id",
"parent_id",
"name",
"path",
"node_type",
"size",
"depth",
"order_index",
"child_count",
}
CANVAS_WIDTH = 1600
CANVAS_PADDING = 48
ROOT_CARD_WIDTH = CANVAS_WIDTH - CANVAS_PADDING * 2
ROOT_CARD_MIN_HEIGHT = 176
SECTION_GAP = 78
CARD_COLUMNS = 3
CARD_GAP_X = 22
CARD_GAP_Y = 20
CARD_WIDTH = (
ROOT_CARD_WIDTH - CARD_GAP_X * (CARD_COLUMNS - 1)
) // CARD_COLUMNS
CARD_HEIGHT = 174
CARD_NAME_MAX_UNITS = 36
ROOT_PATH_MAX_UNITS = 112
ET.register_namespace("", SVG_NAMESPACE)
class ExportError(RuntimeError):
"""A user-facing large-directory SVG export error."""
@dataclass(frozen=True)
class DirectorySummary:
id: int | None
name: str
path: str
size: int
file_count: int
directory_count: int
child_count: int
order_index: int
aggregated_directories: int = 1
@dataclass(frozen=True)
class OverviewData:
root_id: int
root_name: str
root_path: str
total_size: int
node_count: int
file_count: int
directory_count: int
direct_file_count: int
direct_directory_count: int
directories: tuple[DirectorySummary, ...]
omitted_directory_count: int
@dataclass(frozen=True)
class ExportResult:
output_path: Path
elapsed_seconds: float
query_seconds: float
svg_size: int
width: int
height: int
database_node_count: int
file_count: int
directory_count: int
direct_directory_count: int
rendered_directory_cards: int
omitted_directory_count: int
svg_element_count: int
def _svg_tag(name: str) -> str:
return f"{{{SVG_NAMESPACE}}}{name}"
def _safe_filename(value: str) -> str:
cleaned = INVALID_FILENAME_CHARACTERS.sub("_", value).strip(" .")
return cleaned or "folder"
def _readonly_connection(database_path: Path) -> sqlite3.Connection:
resolved_path = database_path.resolve()
if not resolved_path.is_file():
raise ExportError(f"SQLite 索引不存在:{resolved_path}")
try:
connection = sqlite3.connect(
f"{resolved_path.as_uri()}?mode=ro&immutable=1",
uri=True,
timeout=30,
)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA query_only = ON")
except sqlite3.Error as error:
raise ExportError(f"无法以只读模式打开 SQLite:{error}") from error
if connection.execute("PRAGMA query_only").fetchone()[0] != 1:
connection.close()
raise ExportError("SQLite 连接未进入只读模式")
return connection
def _validate_schema(connection: sqlite3.Connection) -> None:
columns = {
row["name"]
for row in connection.execute("PRAGMA table_info('nodes')")
}
missing = REQUIRED_NODE_COLUMNS - columns
if missing:
raise ExportError(
"SQLite nodes 表缺少字段:" + ", ".join(sorted(missing))
)
root_count = connection.execute(
"SELECT COUNT(*) FROM nodes WHERE parent_id IS NULL"
).fetchone()[0]
if root_count != 1:
raise ExportError(
f"SQLite 必须且只能包含一个根节点,当前为 {root_count}"
)
def _query_overview(
connection: sqlite3.Connection,
limit: int,
) -> OverviewData:
_validate_schema(connection)
root = connection.execute(
"""
SELECT id, name, path, size, child_count
FROM nodes
WHERE parent_id IS NULL AND node_type = 'directory'
"""
).fetchone()
if root is None:
raise ExportError("SQLite 中没有有效的根目录节点")
counts = connection.execute(
"""
SELECT
COUNT(*) AS node_count,
SUM(CASE WHEN node_type = 'file' THEN 1 ELSE 0 END)
AS file_count,
SUM(CASE WHEN node_type = 'directory' THEN 1 ELSE 0 END)
AS directory_count
FROM nodes
"""
).fetchone()
rows = connection.execute(
"""
WITH RECURSIVE branch_nodes(
branch_id, node_id, node_type
) AS (
SELECT id, id, node_type
FROM nodes
WHERE parent_id = ? AND node_type = 'directory'
UNION ALL
SELECT branch_nodes.branch_id, child.id, child.node_type
FROM branch_nodes
JOIN nodes AS child ON child.parent_id = branch_nodes.node_id
),
branch_counts AS (
SELECT
branch_id,
SUM(
CASE WHEN node_type = 'file' THEN 1 ELSE 0 END
) AS file_count,
SUM(
CASE WHEN node_type = 'directory' THEN 1 ELSE 0 END
) - 1 AS directory_count
FROM branch_nodes
GROUP BY branch_id
)
SELECT
directory.id,
directory.name,
directory.path,
directory.size,
directory.child_count,
directory.order_index,
COALESCE(branch_counts.file_count, 0) AS file_count,
COALESCE(branch_counts.directory_count, 0)
AS directory_count
FROM nodes AS directory
LEFT JOIN branch_counts ON branch_counts.branch_id = directory.id
WHERE directory.parent_id = ?
AND directory.node_type = 'directory'
ORDER BY directory.size DESC, directory.order_index, directory.id
""",
(root["id"], root["id"]),
).fetchall()
direct_files = connection.execute(
"""
SELECT COUNT(*) AS file_count
FROM nodes
WHERE parent_id = ? AND node_type = 'file'
""",
(root["id"],),
).fetchone()
all_directories = tuple(
DirectorySummary(
id=row["id"],
name=row["name"],
path=row["path"],
size=row["size"],
file_count=row["file_count"],
directory_count=row["directory_count"],
child_count=row["child_count"],
order_index=row["order_index"],
)
for row in rows
)
node_count = int(counts["node_count"] or 0)
file_count = int(counts["file_count"] or 0)
directory_count = int(counts["directory_count"] or 0)
direct_file_count = int(direct_files["file_count"] or 0)
aggregated_file_count = (
sum(item.file_count for item in all_directories)
+ direct_file_count
)
aggregated_directory_count = (
1
+ sum(item.directory_count + 1 for item in all_directories)
)
if node_count != file_count + directory_count:
raise ExportError("SQLite 节点总数与文件、目录数量不一致")
if aggregated_file_count != file_count:
raise ExportError(
"一级目录文件聚合结果与 SQLite 文件总数不一致"
)
if aggregated_directory_count != directory_count:
raise ExportError(
"一级目录子目录聚合结果与 SQLite 目录总数不一致"
)
visible_directories = list(all_directories[:limit])
omitted = all_directories[limit:]
if omitted:
omitted_count = len(omitted)
visible_directories.append(
DirectorySummary(
id=None,
name=f"其他 {omitted_count:,} 个一级目录",
path=(
f"{root['path']}\n"
f"汇总未单独显示的 {omitted_count:,} 个一级目录"
),
size=sum(item.size for item in omitted),
file_count=sum(item.file_count for item in omitted),
directory_count=sum(
item.directory_count + 1 for item in omitted
),
child_count=sum(item.child_count for item in omitted),
order_index=min(item.order_index for item in omitted),
aggregated_directories=omitted_count,
)
)
return OverviewData(
root_id=root["id"],
root_name=root["name"],
root_path=root["path"],
total_size=root["size"],
node_count=node_count,
file_count=file_count,
directory_count=directory_count,
direct_file_count=direct_file_count,
direct_directory_count=len(all_directories),
directories=tuple(visible_directories),
omitted_directory_count=len(omitted),
)
def load_overview(
database_path: Path = DEFAULT_DATABASE_PATH,
limit: int = DEFAULT_OVERVIEW_LIMIT,
) -> OverviewData:
"""Read and aggregate an overview without modifying the SQLite file."""
if not 1 <= limit <= MAX_OVERVIEW_LIMIT:
raise ExportError(
f"一级目录显示上限必须在 1–{MAX_OVERVIEW_LIMIT} 之间"
)
with closing(_readonly_connection(database_path)) as connection:
return _query_overview(connection, limit)
def _text_units(value: str) -> int:
return sum(
2 if unicodedata.east_asian_width(character) in ("F", "W", "A")
else 1
for character in value
)
def _take_prefix(value: str, maximum_units: int) -> str:
result: list[str] = []
used_units = 0
for character in value:
character_units = _text_units(character)
if used_units + character_units > maximum_units:
break
result.append(character)
used_units += character_units
return "".join(result)
def _truncate_tail(value: str, maximum_units: int) -> str:
if _text_units(value) <= maximum_units:
return value
return _take_prefix(value, maximum_units - 1) + "…"
def _wrap_without_omitting(value: str, maximum_units: int) -> list[str]:
if not value:
return [""]
lines: list[str] = []
remaining = value
while remaining:
line = _take_prefix(remaining, maximum_units)
if not line:
line = remaining[0]
lines.append(line)
remaining = remaining[len(line) :]
return lines
def _format_bytes(size: int) -> str:
units = ("B", "KB", "MB", "GB", "TB", "PB")
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
if unit == "B":
return f"{int(value):,} {unit}"
return f"{value:.2f} {unit}"
value /= 1024
return f"{size:,} B"
def _format_ratio(size: int, total_size: int) -> str:
if total_size <= 0 or size <= 0:
return "0.0%"
percentage = size * 100 / total_size
if percentage < 0.1:
return "<0.1%"
return f"{percentage:.1f}%"
def _add_text(
parent: ET.Element,
x: float,
y: float,
value: str,
*,
size: int = 14,
color: str = "#344054",
weight: str = "400",
anchor: str | None = None,
) -> ET.Element:
attributes = {
"x": f"{x:g}",
"y": f"{y:g}",
"fill": color,
"font-family": FONT_FAMILY,
"font-size": str(size),
"font-weight": weight,
}
if anchor is not None:
attributes["text-anchor"] = anchor
element = ET.SubElement(parent, _svg_tag("text"), attributes)
element.text = value
return element
def _add_title(parent: ET.Element, name: str, path: str) -> None:
title = ET.SubElement(parent, _svg_tag("title"))
title.text = f"{name}\n{path}"
def _add_folder_icon(parent: ET.Element, x: float, y: float) -> None:
icon = ET.SubElement(
parent,
_svg_tag("g"),
{
"transform": f"translate({x:g} {y:g}) scale(1.35)",
"aria-hidden": "true",
},
)
ET.SubElement(
icon,
_svg_tag("path"),
{
"d": "M 1 4 H 8 L 10.5 7 H 21 V 19 H 1 Z",
"fill": "#5f91c9",
"stroke": "#376fae",
"stroke-width": "1.2",
"stroke-linejoin": "round",
},
)
ET.SubElement(
icon,
_svg_tag("line"),
{
"x1": "2.5",
"y1": "9",
"x2": "19.5",
"y2": "9",
"stroke": "#d8e9fb",
"stroke-width": "1",
},
)
def _add_root_card(
svg: ET.Element,
data: OverviewData,
x: float,
y: float,
height: int,
path_lines: list[str],
) -> None:
group = ET.SubElement(
svg,
_svg_tag("g"),
{"id": "root-card", "data-card-kind": "root"},
)
_add_title(group, data.root_name, data.root_path)
ET.SubElement(
group,
_svg_tag("rect"),
{
"x": f"{x:g}",
"y": f"{y:g}",
"width": str(ROOT_CARD_WIDTH),
"height": str(height),
"rx": "16",
"fill": "#e7f1ff",
"stroke": "#84aee0",
"stroke-width": "1.5",
},
)
_add_folder_icon(group, x + 24, y + 22)
_add_text(
group,
x + 68,
y + 38,
data.root_name,
size=22,
color="#164a84",
weight="700",
)
_add_text(
group,
x + ROOT_CARD_WIDTH - 24,
y + 35,
"大目录概览",
size=13,
color="#5276a1",
weight="600",
anchor="end",
)
path_y = y + 70
_add_text(
group,
x + 24,
path_y,
"完整路径",
size=12,
color="#60758d",
weight="600",
)
for index, line in enumerate(path_lines):
_add_text(
group,
x + 108,
path_y + index * 19,
line,
size=13,
color="#294966",
)
stats_y = y + height - 34
statistics = (
("文件总数", f"{data.file_count:,}"),
("目录总数", f"{data.directory_count:,}"),
("总大小", _format_bytes(data.total_size)),
("一级目录", f"{data.direct_directory_count:,}"),
)
statistic_width = (ROOT_CARD_WIDTH - 48) / len(statistics)
for index, (label, value) in enumerate(statistics):
statistic_x = x + 24 + index * statistic_width
_add_text(
group,
statistic_x,
stats_y - 22,
label,
size=12,
color="#60758d",
)
_add_text(
group,
statistic_x,
stats_y,
value,
size=17,
color="#164a84",
weight="700",
)
def _add_directory_card(
parent: ET.Element,
item: DirectorySummary,
total_size: int,
x: float,
y: float,
) -> None:
is_aggregate = item.id is None
group = ET.SubElement(
parent,
_svg_tag("g"),
{
"transform": f"translate({x:g} {y:g})",
"data-card-kind": "aggregate" if is_aggregate else "directory",
},
)
_add_title(group, item.name, item.path)
ET.SubElement(
group,
_svg_tag("rect"),
{
"x": "0",
"y": "0",
"width": str(CARD_WIDTH),
"height": str(CARD_HEIGHT),
"rx": "13",
"fill": "#f8fafc" if is_aggregate else "#f3f8ff",
"stroke": "#b9c5d4" if is_aggregate else "#cbdcf3",
"stroke-width": "1.2",
},
)
_add_folder_icon(group, 18, 17)
_add_text(
group,
60,
35,
_truncate_tail(item.name, CARD_NAME_MAX_UNITS),
size=16,
color="#344054" if is_aggregate else "#164a84",
weight="700",
)
_add_text(group, 20, 74, "文件", size=12, color="#667085")
_add_text(
group,
67,
74,
f"{item.file_count:,}",
size=14,
color="#344054",
weight="600",
)
_add_text(group, 164, 74, "子目录", size=12, color="#667085")
_add_text(
group,
224,
74,
f"{item.directory_count:,}",
size=14,
color="#344054",
weight="600",
)
_add_text(group, 20, 105, "累计大小", size=12, color="#667085")
_add_text(
group,
92,
105,
_format_bytes(item.size),
size=14,
color="#344054",
weight="600",
)
ratio_text = _format_ratio(item.size, total_size)
_add_text(
group,
CARD_WIDTH - 20,
105,
ratio_text,
size=14,
color="#477bb5",
weight="700",
anchor="end",
)
bar_x = 20
bar_y = 128
bar_width = CARD_WIDTH - 40
ET.SubElement(
group,
_svg_tag("rect"),
{
"x": str(bar_x),
"y": str(bar_y),
"width": str(bar_width),
"height": "9",
"rx": "4.5",
"fill": "#e4eaf1",
},
)
ratio = item.size / total_size if total_size > 0 else 0
fill_width = min(bar_width, max(0.0, bar_width * ratio))
if fill_width > 0:
ET.SubElement(
group,
_svg_tag("rect"),
{
"x": str(bar_x),
"y": str(bar_y),
"width": f"{max(2.0, fill_width):g}",
"height": "9",
"rx": "4.5",
"fill": "#76a8de" if not is_aggregate else "#9aa8b8",
},
)
footer = (
f"汇总 {item.aggregated_directories:,} 个一级目录"
if is_aggregate
else f"直接子节点 {item.child_count:,}"
)
_add_text(group, 20, 158, footer, size=11, color="#7a8797")
def build_svg(data: OverviewData) -> tuple[ET.ElementTree, int, int]:
"""Build a static, script-free SVG directory overview."""
path_lines = _wrap_without_omitting(
data.root_path, ROOT_PATH_MAX_UNITS
)
root_height = max(
ROOT_CARD_MIN_HEIGHT,
157 + max(0, len(path_lines) - 1) * 19,
)
card_count = len(data.directories)
card_rows = max(1, math.ceil(card_count / CARD_COLUMNS))
cards_start_y = CANVAS_PADDING + root_height + SECTION_GAP
canvas_height = (
cards_start_y
+ 42
+ card_rows * CARD_HEIGHT
+ max(0, card_rows - 1) * CARD_GAP_Y
+ 72
)
svg = ET.Element(
_svg_tag("svg"),
{
"version": "1.1",
"viewBox": f"0 0 {CANVAS_WIDTH} {canvas_height}",
"width": str(CANVAS_WIDTH),
"height": str(canvas_height),
"role": "img",
"aria-label": (
f"{data.root_name} 大目录概览,"
f"{data.directory_count} 个目录,{data.file_count} 个文件"
),
},
)
document_title = ET.SubElement(svg, _svg_tag("title"))
document_title.text = f"FolderVisualizer:{data.root_name} 大目录概览"
ET.SubElement(
svg,
_svg_tag("rect"),
{
"x": "0",
"y": "0",
"width": str(CANVAS_WIDTH),
"height": str(canvas_height),
"fill": "#ffffff",
},
)
root_y = CANVAS_PADDING
_add_root_card(
svg,
data,
CANVAS_PADDING,
root_y,
root_height,
path_lines,
)
center_x = CANVAS_WIDTH / 2
line_start_y = root_y + root_height
line_end_y = cards_start_y - 18
connector = ET.SubElement(
svg,
_svg_tag("g"),
{"id": "overview-connector", "aria-hidden": "true"},
)
ET.SubElement(
connector,
_svg_tag("line"),
{
"x1": f"{center_x:g}",
"y1": f"{line_start_y:g}",
"x2": f"{center_x:g}",
"y2": f"{line_end_y:g}",
"stroke": "#b9c6d5",
"stroke-width": "1.5",
},
)
ET.SubElement(
connector,
_svg_tag("path"),
{
"d": (
f"M {center_x - 5:g} {line_end_y - 7:g} "
f"L {center_x:g} {line_end_y:g} "
f"L {center_x + 5:g} {line_end_y - 7:g}"
),
"fill": "none",
"stroke": "#b9c6d5",
"stroke-width": "1.5",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
)
_add_text(
svg,
CANVAS_PADDING,
cards_start_y + 18,
"一级目录概览 · 按累计大小降序",
size=17,
color="#344054",
weight="700",
)
_add_text(
svg,
CANVAS_WIDTH - CANVAS_PADDING,
cards_start_y + 18,
(
f"显示 {len(data.directories) - 1:,} / "
f"{data.direct_directory_count:,} 个一级目录"
if data.omitted_directory_count
else f"共 {data.direct_directory_count:,} 个一级目录"
),
size=12,
color="#7a8797",
anchor="end",
)
cards_group = ET.SubElement(svg, _svg_tag("g"), {"id": "directory-cards"})
grid_y = cards_start_y + 42
for index, item in enumerate(data.directories):
row = index // CARD_COLUMNS
column = index % CARD_COLUMNS
card_x = CANVAS_PADDING + column * (CARD_WIDTH + CARD_GAP_X)
card_y = grid_y + row * (CARD_HEIGHT + CARD_GAP_Y)
_add_directory_card(
cards_group,
item,
data.total_size,
card_x,
card_y,
)
footer_y = canvas_height - 28
footer = (
"本图仅展示一级目录汇总,不展开文件和深层节点。"
f"根目录直属文件 {data.direct_file_count:,} 个已计入根目录总数。"
)
if data.omitted_directory_count:
footer += (
f"另有 {data.omitted_directory_count:,} 个一级目录已合并到“其他”卡片。"
)
_add_text(
svg,
CANVAS_PADDING,
footer_y,
footer,
size=12,
color="#7a8797",
)
return ET.ElementTree(svg), CANVAS_WIDTH, canvas_height
def default_output_path(
data: OverviewData,
output_dir: Path = DEFAULT_OUTPUT_DIR,
) -> Path:
return (
output_dir.resolve()
/ f"{_safe_filename(data.root_name)}-overview.svg"
)
def export_large_overview(
database_path: Path = DEFAULT_DATABASE_PATH,
output_path: Path | None = None,
output_dir: Path = DEFAULT_OUTPUT_DIR,
limit: int = DEFAULT_OVERVIEW_LIMIT,
) -> ExportResult:
"""Query the index and atomically publish a compact overview SVG."""
started_at = time.perf_counter()
query_started_at = time.perf_counter()
data = load_overview(database_path, limit)
query_seconds = time.perf_counter() - query_started_at
final_output_path = (
output_path.resolve()
if output_path is not None
else default_output_path(data, output_dir)
)
final_output_path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = final_output_path.with_name(
f"{final_output_path.name}.tmp"
)
temporary_path.unlink(missing_ok=True)
try:
tree, width, height = build_svg(data)
svg_element_count = sum(1 for _ in tree.getroot().iter())
ET.indent(tree, space=" ")
tree.write(
temporary_path,
encoding="utf-8",
xml_declaration=True,
short_empty_elements=True,
)
os.replace(temporary_path, final_output_path)
svg_size = final_output_path.stat().st_size
except (OSError, TypeError, ValueError) as error:
temporary_path.unlink(missing_ok=True)
raise ExportError(f"无法生成 SVG:{error}") from error
return ExportResult(
output_path=final_output_path,
elapsed_seconds=time.perf_counter() - started_at,
query_seconds=query_seconds,
svg_size=svg_size,
width=width,
height=height,
database_node_count=data.node_count,
file_count=data.file_count,
directory_count=data.directory_count,
direct_directory_count=data.direct_directory_count,
rendered_directory_cards=len(data.directories),
omitted_directory_count=data.omitted_directory_count,
svg_element_count=svg_element_count,
)
def _overview_limit(value: str) -> int:
try:
limit = int(value)
except ValueError as error:
raise argparse.ArgumentTypeError("显示上限必须是整数") from error
if not 1 <= limit <= MAX_OVERVIEW_LIMIT:
raise argparse.ArgumentTypeError(
f"显示上限必须在 1–{MAX_OVERVIEW_LIMIT} 之间"
)
return limit
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="根据大目录 SQLite 索引生成一级目录概览 SVG"
)
parser.add_argument(
"--database",
type=Path,
default=DEFAULT_DATABASE_PATH,
help=f"SQLite 索引路径(默认:{DEFAULT_DATABASE_PATH})",
)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--output",
type=Path,
help="指定完整 SVG 输出路径",
)
output_group.add_argument(
"--output-dir",
type=Path,
default=DEFAULT_OUTPUT_DIR,
help=f"SVG 输出目录(默认:{DEFAULT_OUTPUT_DIR})",
)
parser.add_argument(
"--limit",
type=_overview_limit,
default=DEFAULT_OVERVIEW_LIMIT,
help=(
"单独显示的一级目录数量,默认 60,最大 100;"
"超出部分合并为“其他”"
),
)
return parser.parse_args()
def main() -> int:
args = _parse_args()
try:
result = export_large_overview(
database_path=args.database,
output_path=args.output,
output_dir=args.output_dir,
limit=args.limit,
)
except KeyboardInterrupt:
print("\n大目录概览 SVG 导出已取消。")
return 130
except (ExportError, OSError, sqlite3.Error) as error:
print(f"错误:{error}")
return 1
print("大目录概览 SVG 导出完成")
print(f"输出:{result.output_path}")
print(f"数据库节点:{result.database_node_count:,}")
print(f"文件数量:{result.file_count:,}")
print(f"目录数量:{result.directory_count:,}")
print(f"一级目录:{result.direct_directory_count:,}")
print(f"SVG 目录卡片:{result.rendered_directory_cards:,}")
print(f"省略并汇总:{result.omitted_directory_count:,}")
print(f"SVG 元素:{result.svg_element_count:,}")
print(f"画布:{result.width:,} × {result.height:,}")
print(f"SQLite 聚合耗时:{result.query_seconds:.3f} 秒")
print(f"总耗时:{result.elapsed_seconds:.3f} 秒")
print(f"SVG 大小:{result.svg_size:,} 字节")
return 0
if __name__ == "__main__":
raise SystemExit(main())