-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
2201 lines (1946 loc) · 66.6 KB
/
cache.py
File metadata and controls
2201 lines (1946 loc) · 66.6 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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Den Rozhnovskiy
from __future__ import annotations
import os
from collections.abc import Collection
from enum import Enum
from json import JSONDecodeError
from pathlib import Path
from typing import TYPE_CHECKING, Literal, TypedDict, TypeGuard, TypeVar, cast
from .baseline import current_python_tag
from .cache_io import (
as_int_or_none as _cache_as_int,
)
from .cache_io import (
as_object_list as _cache_as_list,
)
from .cache_io import (
as_str_dict as _cache_as_str_dict,
)
from .cache_io import (
as_str_or_none as _cache_as_str,
)
from .cache_io import (
read_json_document,
sign_cache_payload,
verify_cache_payload_signature,
write_json_document_atomically,
)
from .cache_paths import runtime_filepath_from_wire, wire_filepath_from_runtime
from .cache_segments import (
SegmentReportProjection as _SegmentReportProjection,
)
from .cache_segments import (
build_segment_report_projection as _build_segment_report_projection,
)
from .cache_segments import (
decode_segment_report_projection,
encode_segment_report_projection,
)
from .contracts import BASELINE_FINGERPRINT_VERSION, CACHE_VERSION
from .errors import CacheError
from .models import (
BlockGroupItem,
BlockUnit,
ClassMetrics,
DeadCandidate,
FileMetrics,
FunctionGroupItem,
ModuleDep,
SegmentGroupItem,
SegmentUnit,
StructuralFindingGroup,
StructuralFindingOccurrence,
Unit,
)
from .structural_findings import normalize_structural_finding_group
if TYPE_CHECKING:
from collections.abc import Callable, Mapping, Sequence
SegmentReportProjection = _SegmentReportProjection
build_segment_report_projection = _build_segment_report_projection
_as_str = _cache_as_str
_as_int = _cache_as_int
_as_list = _cache_as_list
_as_str_dict = _cache_as_str_dict
MAX_CACHE_SIZE_BYTES = 50 * 1024 * 1024
LEGACY_CACHE_SECRET_FILENAME = ".cache_secret"
_DEFAULT_WIRE_UNIT_FLOW_PROFILES = (
0,
"none",
False,
"fallthrough",
"none",
"none",
)
class CacheStatus(str, Enum):
OK = "ok"
MISSING = "missing"
TOO_LARGE = "too_large"
UNREADABLE = "unreadable"
INVALID_JSON = "invalid_json"
INVALID_TYPE = "invalid_type"
VERSION_MISMATCH = "version_mismatch"
PYTHON_TAG_MISMATCH = "python_tag_mismatch"
FINGERPRINT_MISMATCH = "mismatch_fingerprint_version"
ANALYSIS_PROFILE_MISMATCH = "analysis_profile_mismatch"
INTEGRITY_FAILED = "integrity_failed"
class FileStat(TypedDict):
mtime_ns: int
size: int
class SourceStatsDict(TypedDict):
lines: int
functions: int
methods: int
classes: int
UnitDict = FunctionGroupItem
BlockDict = BlockGroupItem
SegmentDict = SegmentGroupItem
class ClassMetricsDictBase(TypedDict):
qualname: str
filepath: str
start_line: int
end_line: int
cbo: int
lcom4: int
method_count: int
instance_var_count: int
risk_coupling: str
risk_cohesion: str
class ClassMetricsDict(ClassMetricsDictBase, total=False):
coupled_classes: list[str]
class ModuleDepDict(TypedDict):
source: str
target: str
import_type: str
line: int
class DeadCandidateDictBase(TypedDict):
qualname: str
local_name: str
filepath: str
start_line: int
end_line: int
kind: str
class DeadCandidateDict(DeadCandidateDictBase, total=False):
suppressed_rules: list[str]
class StructuralFindingOccurrenceDict(TypedDict):
qualname: str
start: int
end: int
class StructuralFindingGroupDict(TypedDict):
finding_kind: str
finding_key: str
signature: dict[str, str]
items: list[StructuralFindingOccurrenceDict]
class CacheEntryBase(TypedDict):
stat: FileStat
units: list[UnitDict]
blocks: list[BlockDict]
segments: list[SegmentDict]
class CacheEntry(CacheEntryBase, total=False):
source_stats: SourceStatsDict
class_metrics: list[ClassMetricsDict]
module_deps: list[ModuleDepDict]
dead_candidates: list[DeadCandidateDict]
referenced_names: list[str]
referenced_qualnames: list[str]
import_names: list[str]
class_names: list[str]
structural_findings: list[StructuralFindingGroupDict]
class AnalysisProfile(TypedDict):
min_loc: int
min_stmt: int
block_min_loc: int
block_min_stmt: int
segment_min_loc: int
segment_min_stmt: int
class CacheData(TypedDict):
version: str
python_tag: str
fingerprint_version: str
analysis_profile: AnalysisProfile
files: dict[str, CacheEntry]
def _normalize_cached_structural_group(
group: StructuralFindingGroupDict,
*,
filepath: str,
) -> StructuralFindingGroupDict | None:
signature = dict(group["signature"])
finding_kind = group["finding_kind"]
finding_key = group["finding_key"]
normalized = normalize_structural_finding_group(
StructuralFindingGroup(
finding_kind=finding_kind,
finding_key=finding_key,
signature=signature,
items=tuple(
StructuralFindingOccurrence(
finding_kind=finding_kind,
finding_key=finding_key,
file_path=filepath,
qualname=item["qualname"],
start=item["start"],
end=item["end"],
signature=signature,
)
for item in group["items"]
),
)
)
if normalized is None:
return None
return StructuralFindingGroupDict(
finding_kind=normalized.finding_kind,
finding_key=normalized.finding_key,
signature=dict(normalized.signature),
items=[
StructuralFindingOccurrenceDict(
qualname=item.qualname,
start=item.start,
end=item.end,
)
for item in normalized.items
],
)
def _normalize_cached_structural_groups(
groups: Sequence[StructuralFindingGroupDict],
*,
filepath: str,
) -> list[StructuralFindingGroupDict]:
normalized = [
candidate
for candidate in (
_normalize_cached_structural_group(group, filepath=filepath)
for group in groups
)
if candidate is not None
]
normalized.sort(key=lambda group: (-len(group["items"]), group["finding_key"]))
return normalized
_DecodedItemT = TypeVar("_DecodedItemT")
_ValidatedItemT = TypeVar("_ValidatedItemT")
class Cache:
__slots__ = (
"_canonical_runtime_paths",
"_dirty",
"analysis_profile",
"cache_schema_version",
"data",
"fingerprint_version",
"legacy_secret_warning",
"load_status",
"load_warning",
"max_size_bytes",
"path",
"root",
"segment_report_projection",
)
_CACHE_VERSION = CACHE_VERSION
def __init__(
self,
path: str | Path,
*,
root: str | Path | None = None,
max_size_bytes: int | None = None,
min_loc: int = 10,
min_stmt: int = 6,
block_min_loc: int = 20,
block_min_stmt: int = 8,
segment_min_loc: int = 20,
segment_min_stmt: int = 10,
):
self.path = Path(path)
self.root = _resolve_root(root)
self.fingerprint_version = BASELINE_FINGERPRINT_VERSION
self.analysis_profile: AnalysisProfile = {
"min_loc": min_loc,
"min_stmt": min_stmt,
"block_min_loc": block_min_loc,
"block_min_stmt": block_min_stmt,
"segment_min_loc": segment_min_loc,
"segment_min_stmt": segment_min_stmt,
}
self.data: CacheData = _empty_cache_data(
version=self._CACHE_VERSION,
python_tag=current_python_tag(),
fingerprint_version=self.fingerprint_version,
analysis_profile=self.analysis_profile,
)
self._canonical_runtime_paths: set[str] = set()
self.legacy_secret_warning = self._detect_legacy_secret_warning()
self.cache_schema_version: str | None = None
self.load_status = CacheStatus.MISSING
self.load_warning: str | None = self.legacy_secret_warning
self.max_size_bytes = (
MAX_CACHE_SIZE_BYTES if max_size_bytes is None else max_size_bytes
)
self.segment_report_projection: SegmentReportProjection | None = None
self._dirty: bool = True # new cache is dirty until loaded from disk
def _detect_legacy_secret_warning(self) -> str | None:
secret_path = self.path.parent / LEGACY_CACHE_SECRET_FILENAME
try:
if secret_path.exists():
return (
f"Legacy cache secret file detected at {secret_path}; "
"delete this obsolete file."
)
except OSError as e:
return f"Legacy cache secret check failed: {e}"
return None
def _set_load_warning(self, message: str | None) -> None:
warning = message
if warning is None:
warning = self.legacy_secret_warning
elif self.legacy_secret_warning:
warning = f"{warning}\n{self.legacy_secret_warning}"
self.load_warning = warning
def _ignore_cache(
self,
message: str,
*,
status: CacheStatus,
schema_version: str | None = None,
) -> None:
self._set_load_warning(message)
self.load_status = status
self.cache_schema_version = schema_version
self.data = _empty_cache_data(
version=self._CACHE_VERSION,
python_tag=current_python_tag(),
fingerprint_version=self.fingerprint_version,
analysis_profile=self.analysis_profile,
)
self._canonical_runtime_paths = set()
self.segment_report_projection = None
def _reject_cache_load(
self,
message: str,
*,
status: CacheStatus,
schema_version: str | None = None,
) -> CacheData | None:
self._ignore_cache(
message,
status=status,
schema_version=schema_version,
)
return None
def _reject_invalid_cache_format(
self,
*,
schema_version: str | None = None,
) -> CacheData | None:
return self._reject_cache_load(
"Cache format invalid; ignoring cache.",
status=CacheStatus.INVALID_TYPE,
schema_version=schema_version,
)
def _reject_version_mismatch(self, version: str) -> CacheData | None:
return self._reject_cache_load(
f"Cache version mismatch (found {version}); ignoring cache.",
status=CacheStatus.VERSION_MISMATCH,
schema_version=version,
)
def load(self) -> None:
try:
exists = self.path.exists()
except OSError as e:
self._ignore_cache(
f"Cache unreadable; ignoring cache: {e}",
status=CacheStatus.UNREADABLE,
)
return
if not exists:
self._set_load_warning(None)
self.load_status = CacheStatus.MISSING
self.cache_schema_version = None
self._canonical_runtime_paths = set()
self.segment_report_projection = None
return
try:
size = self.path.stat().st_size
if size > self.max_size_bytes:
self._ignore_cache(
"Cache file too large "
f"({size} bytes, max {self.max_size_bytes}); ignoring cache.",
status=CacheStatus.TOO_LARGE,
)
return
raw_obj = read_json_document(self.path)
parsed = self._load_and_validate(raw_obj)
if parsed is None:
return
self.data = parsed
self._canonical_runtime_paths = set(parsed["files"].keys())
self.load_status = CacheStatus.OK
self._set_load_warning(None)
self._dirty = False # freshly loaded — nothing to persist
except OSError as e:
self._ignore_cache(
f"Cache unreadable; ignoring cache: {e}",
status=CacheStatus.UNREADABLE,
)
except JSONDecodeError:
self._ignore_cache(
"Cache corrupted; ignoring cache.",
status=CacheStatus.INVALID_JSON,
)
def _load_and_validate(self, raw_obj: object) -> CacheData | None:
raw = _as_str_dict(raw_obj)
if raw is None:
return self._reject_invalid_cache_format()
# Legacy cache format: top-level {version, files, _signature}.
legacy_version = _as_str(raw.get("version"))
if legacy_version is not None:
return self._reject_version_mismatch(legacy_version)
version = _as_str(raw.get("v"))
if version is None:
return self._reject_invalid_cache_format()
if version != self._CACHE_VERSION:
return self._reject_version_mismatch(version)
sig = _as_str(raw.get("sig"))
payload_obj = raw.get("payload")
payload = _as_str_dict(payload_obj)
if sig is None or payload is None:
return self._reject_invalid_cache_format(schema_version=version)
if not verify_cache_payload_signature(payload, sig):
return self._reject_cache_load(
"Cache signature mismatch; ignoring cache.",
status=CacheStatus.INTEGRITY_FAILED,
schema_version=version,
)
runtime_tag = current_python_tag()
py_tag = _as_str(payload.get("py"))
if py_tag is None:
return self._reject_invalid_cache_format(schema_version=version)
if py_tag != runtime_tag:
return self._reject_cache_load(
"Cache python tag mismatch "
f"(found {py_tag}, expected {runtime_tag}); ignoring cache.",
status=CacheStatus.PYTHON_TAG_MISMATCH,
schema_version=version,
)
fp_version = _as_str(payload.get("fp"))
if fp_version is None:
return self._reject_invalid_cache_format(schema_version=version)
if fp_version != self.fingerprint_version:
return self._reject_cache_load(
"Cache fingerprint version mismatch "
f"(found {fp_version}, expected {self.fingerprint_version}); "
"ignoring cache.",
status=CacheStatus.FINGERPRINT_MISMATCH,
schema_version=version,
)
analysis_profile = _as_analysis_profile(payload.get("ap"))
if analysis_profile is None:
return self._reject_invalid_cache_format(schema_version=version)
if analysis_profile != self.analysis_profile:
return self._reject_cache_load(
"Cache analysis profile mismatch "
f"(found min_loc={analysis_profile['min_loc']}, "
f"min_stmt={analysis_profile['min_stmt']}; "
f"expected min_loc={self.analysis_profile['min_loc']}, "
f"min_stmt={self.analysis_profile['min_stmt']}); "
"ignoring cache.",
status=CacheStatus.ANALYSIS_PROFILE_MISMATCH,
schema_version=version,
)
files_obj = payload.get("files")
files_dict = _as_str_dict(files_obj)
if files_dict is None:
return self._reject_invalid_cache_format(schema_version=version)
parsed_files: dict[str, CacheEntry] = {}
for wire_path, file_entry_obj in files_dict.items():
runtime_path = runtime_filepath_from_wire(wire_path, root=self.root)
parsed_entry = self._decode_entry(file_entry_obj, runtime_path)
if parsed_entry is None:
return self._reject_invalid_cache_format(schema_version=version)
parsed_files[runtime_path] = _canonicalize_cache_entry(parsed_entry)
self.segment_report_projection = decode_segment_report_projection(
payload.get("sr"),
root=self.root,
)
self.cache_schema_version = version
return CacheData(
version=self._CACHE_VERSION,
python_tag=runtime_tag,
fingerprint_version=self.fingerprint_version,
analysis_profile=self.analysis_profile,
files=parsed_files,
)
def save(self) -> None:
if not self._dirty:
return
try:
wire_files: dict[str, object] = {}
wire_map = {
rp: wire_filepath_from_runtime(rp, root=self.root)
for rp in self.data["files"]
}
for runtime_path in sorted(self.data["files"], key=wire_map.__getitem__):
entry = self.get_file_entry(runtime_path)
if entry is None:
continue
wire_files[wire_map[runtime_path]] = self._encode_entry(entry)
payload: dict[str, object] = {
"py": current_python_tag(),
"fp": self.fingerprint_version,
"ap": self.analysis_profile,
"files": wire_files,
}
segment_projection = encode_segment_report_projection(
self.segment_report_projection,
root=self.root,
)
if segment_projection is not None:
payload["sr"] = segment_projection
signed_doc = {
"v": self._CACHE_VERSION,
"payload": payload,
"sig": sign_cache_payload(payload),
}
write_json_document_atomically(self.path, signed_doc)
self._dirty = False
self.data["version"] = self._CACHE_VERSION
self.data["python_tag"] = current_python_tag()
self.data["fingerprint_version"] = self.fingerprint_version
self.data["analysis_profile"] = self.analysis_profile
except OSError as e:
raise CacheError(f"Failed to save cache: {e}") from e
@staticmethod
def _decode_entry(value: object, filepath: str) -> CacheEntry | None:
return _decode_wire_file_entry(value, filepath)
@staticmethod
def _encode_entry(entry: CacheEntry) -> dict[str, object]:
return _encode_wire_file_entry(entry)
def _store_canonical_file_entry(
self,
*,
runtime_path: str,
canonical_entry: CacheEntry,
) -> CacheEntry:
previous_entry = self.data["files"].get(runtime_path)
was_canonical = runtime_path in self._canonical_runtime_paths
self.data["files"][runtime_path] = canonical_entry
self._canonical_runtime_paths.add(runtime_path)
if not was_canonical or previous_entry != canonical_entry:
self._dirty = True
return canonical_entry
def get_file_entry(self, filepath: str) -> CacheEntry | None:
runtime_lookup_key = filepath
entry_obj = self.data["files"].get(runtime_lookup_key)
if entry_obj is None:
wire_key = wire_filepath_from_runtime(filepath, root=self.root)
runtime_lookup_key = runtime_filepath_from_wire(wire_key, root=self.root)
entry_obj = self.data["files"].get(runtime_lookup_key)
if entry_obj is None:
return None
if runtime_lookup_key in self._canonical_runtime_paths:
if _is_canonical_cache_entry(entry_obj):
return entry_obj
self._canonical_runtime_paths.discard(runtime_lookup_key)
if not isinstance(entry_obj, dict):
return None
entry = entry_obj
required = {"stat", "units", "blocks", "segments"}
if not required.issubset(entry.keys()):
return None
stat = _as_file_stat_dict(entry.get("stat"))
units = _as_typed_unit_list(entry.get("units"))
blocks = _as_typed_block_list(entry.get("blocks"))
segments = _as_typed_segment_list(entry.get("segments"))
if stat is None or units is None or blocks is None or segments is None:
return None
class_metrics_raw = _as_typed_class_metrics_list(entry.get("class_metrics", []))
module_deps_raw = _as_typed_module_deps_list(entry.get("module_deps", []))
dead_candidates_raw = _as_typed_dead_candidates_list(
entry.get("dead_candidates", [])
)
referenced_names_raw = _as_typed_string_list(entry.get("referenced_names", []))
referenced_qualnames_raw = _as_typed_string_list(
entry.get("referenced_qualnames", [])
)
import_names_raw = _as_typed_string_list(entry.get("import_names", []))
class_names_raw = _as_typed_string_list(entry.get("class_names", []))
if (
class_metrics_raw is None
or module_deps_raw is None
or dead_candidates_raw is None
or referenced_names_raw is None
or referenced_qualnames_raw is None
or import_names_raw is None
or class_names_raw is None
):
return None
entry_to_canonicalize: CacheEntry = CacheEntry(
stat=stat,
units=units,
blocks=blocks,
segments=segments,
class_metrics=class_metrics_raw,
module_deps=module_deps_raw,
dead_candidates=dead_candidates_raw,
referenced_names=referenced_names_raw,
referenced_qualnames=referenced_qualnames_raw,
import_names=import_names_raw,
class_names=class_names_raw,
)
source_stats = _as_source_stats_dict(entry.get("source_stats"))
if source_stats is not None:
entry_to_canonicalize["source_stats"] = source_stats
sf_raw = entry.get("structural_findings")
if isinstance(sf_raw, list):
entry_to_canonicalize["structural_findings"] = sf_raw
canonical_entry = _canonicalize_cache_entry(entry_to_canonicalize)
return self._store_canonical_file_entry(
runtime_path=runtime_lookup_key,
canonical_entry=canonical_entry,
)
def put_file_entry(
self,
filepath: str,
stat_sig: FileStat,
units: list[Unit],
blocks: list[BlockUnit],
segments: list[SegmentUnit],
*,
source_stats: SourceStatsDict | None = None,
file_metrics: FileMetrics | None = None,
structural_findings: list[StructuralFindingGroup] | None = None,
) -> None:
runtime_path = runtime_filepath_from_wire(
wire_filepath_from_runtime(filepath, root=self.root),
root=self.root,
)
unit_rows = [_unit_dict_from_model(unit, runtime_path) for unit in units]
block_rows = [_block_dict_from_model(block, runtime_path) for block in blocks]
segment_rows = [
_segment_dict_from_model(segment, runtime_path) for segment in segments
]
(
class_metrics_rows,
module_dep_rows,
dead_candidate_rows,
referenced_names,
referenced_qualnames,
import_names,
class_names,
) = _new_optional_metrics_payload()
if file_metrics is not None:
class_metrics_rows = [
_class_metrics_dict_from_model(metric, runtime_path)
for metric in file_metrics.class_metrics
]
module_dep_rows = [
_module_dep_dict_from_model(dep) for dep in file_metrics.module_deps
]
dead_candidate_rows = [
_dead_candidate_dict_from_model(candidate, runtime_path)
for candidate in file_metrics.dead_candidates
]
referenced_names = sorted(set(file_metrics.referenced_names))
referenced_qualnames = sorted(set(file_metrics.referenced_qualnames))
import_names = sorted(set(file_metrics.import_names))
class_names = sorted(set(file_metrics.class_names))
source_stats_payload = source_stats or SourceStatsDict(
lines=0,
functions=0,
methods=0,
classes=0,
)
entry_dict = CacheEntry(
stat=stat_sig,
source_stats=source_stats_payload,
units=unit_rows,
blocks=block_rows,
segments=segment_rows,
class_metrics=class_metrics_rows,
module_deps=module_dep_rows,
dead_candidates=dead_candidate_rows,
referenced_names=referenced_names,
referenced_qualnames=referenced_qualnames,
import_names=import_names,
class_names=class_names,
)
if structural_findings is not None:
entry_dict["structural_findings"] = _normalize_cached_structural_groups(
[
_structural_group_dict_from_model(group)
for group in structural_findings
],
filepath=runtime_path,
)
canonical_entry = _canonicalize_cache_entry(entry_dict)
self._store_canonical_file_entry(
runtime_path=runtime_path,
canonical_entry=canonical_entry,
)
def file_stat_signature(path: str) -> FileStat:
st = os.stat(path)
return FileStat(
mtime_ns=st.st_mtime_ns,
size=st.st_size,
)
def _empty_cache_data(
*,
version: str,
python_tag: str,
fingerprint_version: str,
analysis_profile: AnalysisProfile,
) -> CacheData:
return CacheData(
version=version,
python_tag=python_tag,
fingerprint_version=fingerprint_version,
analysis_profile=analysis_profile,
files={},
)
def _as_risk_literal(value: object) -> Literal["low", "medium", "high"] | None:
match value:
case "low":
return "low"
case "medium":
return "medium"
case "high":
return "high"
case _:
return None
def _new_optional_metrics_payload() -> tuple[
list[ClassMetricsDict],
list[ModuleDepDict],
list[DeadCandidateDict],
list[str],
list[str],
list[str],
list[str],
]:
return [], [], [], [], [], [], []
def _unit_dict_from_model(unit: Unit, filepath: str) -> UnitDict:
return FunctionGroupItem(
qualname=unit.qualname,
filepath=filepath,
start_line=unit.start_line,
end_line=unit.end_line,
loc=unit.loc,
stmt_count=unit.stmt_count,
fingerprint=unit.fingerprint,
loc_bucket=unit.loc_bucket,
cyclomatic_complexity=unit.cyclomatic_complexity,
nesting_depth=unit.nesting_depth,
risk=unit.risk,
raw_hash=unit.raw_hash,
entry_guard_count=unit.entry_guard_count,
entry_guard_terminal_profile=unit.entry_guard_terminal_profile,
entry_guard_has_side_effect_before=unit.entry_guard_has_side_effect_before,
terminal_kind=unit.terminal_kind,
try_finally_profile=unit.try_finally_profile,
side_effect_order_profile=unit.side_effect_order_profile,
)
def _block_dict_from_model(block: BlockUnit, filepath: str) -> BlockDict:
return BlockGroupItem(
block_hash=block.block_hash,
filepath=filepath,
qualname=block.qualname,
start_line=block.start_line,
end_line=block.end_line,
size=block.size,
)
def _segment_dict_from_model(segment: SegmentUnit, filepath: str) -> SegmentDict:
return SegmentGroupItem(
segment_hash=segment.segment_hash,
segment_sig=segment.segment_sig,
filepath=filepath,
qualname=segment.qualname,
start_line=segment.start_line,
end_line=segment.end_line,
size=segment.size,
)
def _class_metrics_dict_from_model(
metric: ClassMetrics,
filepath: str,
) -> ClassMetricsDict:
return ClassMetricsDict(
qualname=metric.qualname,
filepath=filepath,
start_line=metric.start_line,
end_line=metric.end_line,
cbo=metric.cbo,
lcom4=metric.lcom4,
method_count=metric.method_count,
instance_var_count=metric.instance_var_count,
risk_coupling=metric.risk_coupling,
risk_cohesion=metric.risk_cohesion,
coupled_classes=sorted(set(metric.coupled_classes)),
)
def _module_dep_dict_from_model(dep: ModuleDep) -> ModuleDepDict:
return ModuleDepDict(
source=dep.source,
target=dep.target,
import_type=dep.import_type,
line=dep.line,
)
def _dead_candidate_dict_from_model(
candidate: DeadCandidate,
filepath: str,
) -> DeadCandidateDict:
result = DeadCandidateDict(
qualname=candidate.qualname,
local_name=candidate.local_name,
filepath=filepath,
start_line=candidate.start_line,
end_line=candidate.end_line,
kind=candidate.kind,
)
if candidate.suppressed_rules:
result["suppressed_rules"] = sorted(set(candidate.suppressed_rules))
return result
def _structural_occurrence_dict_from_model(
occurrence: StructuralFindingOccurrence,
) -> StructuralFindingOccurrenceDict:
return StructuralFindingOccurrenceDict(
qualname=occurrence.qualname,
start=occurrence.start,
end=occurrence.end,
)
def _structural_group_dict_from_model(
group: StructuralFindingGroup,
) -> StructuralFindingGroupDict:
return StructuralFindingGroupDict(
finding_kind=group.finding_kind,
finding_key=group.finding_key,
signature=dict(group.signature),
items=[
_structural_occurrence_dict_from_model(occurrence)
for occurrence in group.items
],
)
def _as_file_stat_dict(value: object) -> FileStat | None:
if not _is_file_stat_dict(value):
return None
obj = cast("Mapping[str, object]", value)
mtime_ns = obj.get("mtime_ns")
size = obj.get("size")
if not isinstance(mtime_ns, int) or not isinstance(size, int):
return None
return FileStat(mtime_ns=mtime_ns, size=size)
def _as_source_stats_dict(value: object) -> SourceStatsDict | None:
if not _is_source_stats_dict(value):
return None
obj = cast("Mapping[str, object]", value)
lines = obj.get("lines")
functions = obj.get("functions")
methods = obj.get("methods")
classes = obj.get("classes")
assert isinstance(lines, int)
assert isinstance(functions, int)
assert isinstance(methods, int)
assert isinstance(classes, int)
return SourceStatsDict(
lines=lines,
functions=functions,
methods=methods,
classes=classes,
)
def _as_typed_list(
value: object,
*,
predicate: Callable[[object], bool],
) -> list[_ValidatedItemT] | None:
if not isinstance(value, list):
return None
if not all(predicate(item) for item in value):
return None
return cast("list[_ValidatedItemT]", value)
def _as_typed_unit_list(value: object) -> list[UnitDict] | None:
return _as_typed_list(value, predicate=_is_unit_dict)
def _as_typed_block_list(value: object) -> list[BlockDict] | None:
return _as_typed_list(value, predicate=_is_block_dict)
def _as_typed_segment_list(value: object) -> list[SegmentDict] | None:
return _as_typed_list(value, predicate=_is_segment_dict)
def _as_typed_class_metrics_list(value: object) -> list[ClassMetricsDict] | None:
return _as_typed_list(value, predicate=_is_class_metrics_dict)
def _as_typed_dead_candidates_list(
value: object,
) -> list[DeadCandidateDict] | None:
return _as_typed_list(value, predicate=_is_dead_candidate_dict)