-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1265 lines (1118 loc) · 38.9 KB
/
cli.py
File metadata and controls
1265 lines (1118 loc) · 38.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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Den Rozhnovskiy
from __future__ import annotations
import os
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Literal, Protocol, cast
from . import __version__
from . import ui_messages as ui
from ._cli_args import build_parser
from ._cli_baselines import (
CloneBaselineState as _CloneBaselineStateImpl,
)
from ._cli_baselines import (
MetricsBaselineSectionProbe as _MetricsBaselineSectionProbeImpl,
)
from ._cli_baselines import (
MetricsBaselineState as _MetricsBaselineStateImpl,
)
from ._cli_baselines import (
probe_metrics_baseline_section as _probe_metrics_baseline_section_impl,
)
from ._cli_baselines import (
resolve_clone_baseline_state as _resolve_clone_baseline_state_impl,
)
from ._cli_baselines import (
resolve_metrics_baseline_state as _resolve_metrics_baseline_state_impl,
)
from ._cli_config import (
ConfigValidationError,
apply_pyproject_config_overrides,
collect_explicit_cli_dests,
load_pyproject_config,
)
from ._cli_gating import (
parse_metric_reason_entry as _parse_metric_reason_entry_impl,
)
from ._cli_gating import (
print_gating_failure_block as _print_gating_failure_block_impl,
)
from ._cli_paths import _validate_output_path
from ._cli_reports import (
write_report_outputs as _write_report_outputs_impl,
)
from ._cli_rich import (
PlainConsole as _PlainConsole,
)
from ._cli_rich import (
make_console as _make_rich_console,
)
from ._cli_rich import (
make_plain_console as _make_plain_console_impl,
)
from ._cli_rich import (
print_banner as _print_banner_impl,
)
from ._cli_rich import (
rich_progress_symbols as _rich_progress_symbols_impl,
)
from ._cli_runtime import (
configure_metrics_mode as _configure_metrics_mode_impl,
)
from ._cli_runtime import (
metrics_computed as _metrics_computed_impl,
)
from ._cli_runtime import (
print_failed_files as _print_failed_files_impl,
)
from ._cli_runtime import (
resolve_cache_path as _resolve_cache_path_impl,
)
from ._cli_runtime import (
resolve_cache_status as _resolve_cache_status_impl,
)
from ._cli_runtime import (
validate_numeric_args as _validate_numeric_args_impl,
)
from ._cli_summary import MetricsSnapshot, _print_metrics, _print_summary
from .baseline import Baseline
from .cache import Cache, CacheStatus, build_segment_report_projection
from .contracts import ISSUES_URL, ExitCode
from .errors import CacheError
if TYPE_CHECKING:
from argparse import Namespace
from collections.abc import Callable, Mapping, Sequence
from types import ModuleType
from rich.console import Console as RichConsole
from rich.progress import BarColumn as RichBarColumn
from rich.progress import Progress as RichProgress
from rich.progress import SpinnerColumn as RichSpinnerColumn
from rich.progress import TextColumn as RichTextColumn
from rich.progress import TimeElapsedColumn as RichTimeElapsedColumn
from ._cli_baselines import _BaselineArgs as _BaselineArgsLike
from ._cli_gating import _GatingArgs as _GatingArgsLike
from ._cli_reports import _QuietArgs as _QuietArgsLike
from ._cli_runtime import _RuntimeArgs as _RuntimeArgsLike
from .models import MetricsDiff
from .normalize import NormalizationConfig
from .pipeline import (
AnalysisResult,
BootstrapResult,
DiscoveryResult,
GatingResult,
ReportArtifacts,
)
from .pipeline import (
OutputPaths as PipelineOutputPaths,
)
from .pipeline import (
ProcessingResult as PipelineProcessingResult,
)
MAX_FILE_SIZE = 10 * 1024 * 1024
__all__ = [
"MAX_FILE_SIZE",
"ProcessingResult",
"analyze",
"bootstrap",
"discover",
"gate",
"main",
"process",
"process_file",
"report",
]
_PIPELINE_MODULE: ModuleType | None = None
def _pipeline_module() -> ModuleType:
global _PIPELINE_MODULE
if _PIPELINE_MODULE is None:
from . import pipeline as _pipeline
_PIPELINE_MODULE = _pipeline
return _PIPELINE_MODULE
@dataclass(frozen=True, slots=True)
class OutputPaths:
html: Path | None = None
json: Path | None = None
text: Path | None = None
md: Path | None = None
sarif: Path | None = None
@dataclass(frozen=True, slots=True)
class ProcessingResult:
filepath: str
success: bool
error: str | None = None
units: list[object] | None = None
blocks: list[object] | None = None
segments: list[object] | None = None
lines: int = 0
functions: int = 0
methods: int = 0
classes: int = 0
stat: Mapping[str, int] | None = None
error_kind: str | None = None
file_metrics: object | None = None
structural_findings: list[object] | None = None
def process_file(
filepath: str,
root: str,
cfg: NormalizationConfig,
min_loc: int,
min_stmt: int,
collect_structural_findings: bool = True,
) -> ProcessingResult:
pipeline_mod = _pipeline_module()
result = pipeline_mod.process_file(
filepath,
root,
cfg,
min_loc,
min_stmt,
collect_structural_findings,
)
return cast("ProcessingResult", result)
def bootstrap(
*,
args: Namespace,
root: Path,
output_paths: PipelineOutputPaths | OutputPaths,
cache_path: Path,
) -> BootstrapResult:
return cast(
"BootstrapResult",
_pipeline_module().bootstrap(
args=args,
root=root,
output_paths=output_paths,
cache_path=cache_path,
),
)
def discover(*, boot: BootstrapResult, cache: Cache) -> DiscoveryResult:
return cast("DiscoveryResult", _pipeline_module().discover(boot=boot, cache=cache))
def process(
*,
boot: BootstrapResult,
discovery: DiscoveryResult,
cache: Cache,
on_advance: Callable[[], None] | None = None,
on_worker_error: Callable[[str], None] | None = None,
on_parallel_fallback: Callable[[Exception], None] | None = None,
) -> PipelineProcessingResult:
return cast(
"PipelineProcessingResult",
_pipeline_module().process(
boot=boot,
discovery=discovery,
cache=cache,
on_advance=on_advance,
on_worker_error=on_worker_error,
on_parallel_fallback=on_parallel_fallback,
),
)
def analyze(
*,
boot: BootstrapResult,
discovery: DiscoveryResult,
processing: PipelineProcessingResult,
) -> AnalysisResult:
return cast(
"AnalysisResult",
_pipeline_module().analyze(
boot=boot,
discovery=discovery,
processing=processing,
),
)
def report(
*,
boot: BootstrapResult,
discovery: DiscoveryResult,
processing: PipelineProcessingResult,
analysis: AnalysisResult,
report_meta: Mapping[str, object],
new_func: set[str],
new_block: set[str],
html_builder: Callable[..., str] | None = None,
metrics_diff: MetricsDiff | None = None,
) -> ReportArtifacts:
return cast(
"ReportArtifacts",
_pipeline_module().report(
boot=boot,
discovery=discovery,
processing=processing,
analysis=analysis,
report_meta=report_meta,
new_func=new_func,
new_block=new_block,
html_builder=html_builder,
metrics_diff=metrics_diff,
),
)
def gate(
*,
boot: BootstrapResult,
analysis: AnalysisResult,
new_func: set[str],
new_block: set[str],
metrics_diff: MetricsDiff | None,
) -> GatingResult:
return cast(
"GatingResult",
_pipeline_module().gate(
boot=boot,
analysis=analysis,
new_func=new_func,
new_block=new_block,
metrics_diff=metrics_diff,
),
)
class _PrinterLike(Protocol):
def print(self, *objects: object, **kwargs: object) -> None: ...
LEGACY_CACHE_PATH = Path("~/.cache/codeclone/cache.json").expanduser()
ReportPathOrigin = Literal["default", "explicit"]
def _rich_progress_symbols() -> tuple[
type[RichProgress],
type[RichSpinnerColumn],
type[RichTextColumn],
type[RichBarColumn],
type[RichTimeElapsedColumn],
]:
return _rich_progress_symbols_impl()
def _make_console(*, no_color: bool) -> RichConsole:
return _make_rich_console(
no_color=no_color,
width=ui.CLI_LAYOUT_MAX_WIDTH,
)
def _print_verbose_clone_hashes(
console: _PrinterLike,
*,
label: str,
clone_hashes: set[str],
) -> None:
if not clone_hashes:
return
console.print(f"\n {label}:")
for clone_hash in sorted(clone_hashes):
console.print(f" - {clone_hash}")
def _make_plain_console() -> _PlainConsole:
return _make_plain_console_impl()
console: RichConsole | _PlainConsole = _make_plain_console()
def _parse_metric_reason_entry(reason: str) -> tuple[str, str]:
return _parse_metric_reason_entry_impl(reason)
def _print_gating_failure_block(
*,
code: str,
entries: Sequence[tuple[str, object]],
args: Namespace,
) -> None:
_print_gating_failure_block_impl(
console=cast("_PrinterLike", console),
code=code,
entries=list(entries),
args=cast("_GatingArgsLike", cast(object, args)),
)
def build_html_report(*args: object, **kwargs: object) -> str:
# Lazy import avoids pulling HTML renderer in non-HTML CLI runs.
from .html_report import build_html_report as _build_html_report
html_builder: Callable[..., str] = _build_html_report
return html_builder(*args, **kwargs)
_CloneBaselineState = _CloneBaselineStateImpl
_MetricsBaselineState = _MetricsBaselineStateImpl
_MetricsBaselineSectionProbe = _MetricsBaselineSectionProbeImpl
def print_banner(*, root: Path | None = None) -> None:
_print_banner_impl(
console=cast("_PrinterLike", console),
banner_title=ui.banner_title(__version__),
project_name=(root.name if root is not None else None),
root_display=(str(root) if root is not None else None),
)
def _is_debug_enabled(
*,
argv: Sequence[str] | None = None,
environ: Mapping[str, str] | None = None,
) -> bool:
args = list(sys.argv[1:] if argv is None else argv)
debug_from_flag = any(arg == "--debug" for arg in args)
env = os.environ if environ is None else environ
debug_from_env = env.get("CODECLONE_DEBUG") == "1"
return debug_from_flag or debug_from_env
def _report_path_origins(argv: Sequence[str]) -> dict[str, ReportPathOrigin | None]:
origins: dict[str, ReportPathOrigin | None] = {
"html": None,
"json": None,
"md": None,
"sarif": None,
"text": None,
}
flag_to_field = {
"--html": "html",
"--json": "json",
"--md": "md",
"--sarif": "sarif",
"--text": "text",
}
index = 0
while index < len(argv):
token = argv[index]
if token == "--":
break
if "=" in token:
flag, _value = token.split("=", maxsplit=1)
field_name = flag_to_field.get(flag)
if field_name is not None:
origins[field_name] = "explicit"
index += 1
continue
field_name = flag_to_field.get(token)
if field_name is None:
index += 1
continue
next_token = argv[index + 1] if index + 1 < len(argv) else None
if next_token is None or next_token.startswith("-"):
origins[field_name] = "default"
index += 1
continue
origins[field_name] = "explicit"
index += 2
return origins
def _report_path_timestamp_slug(report_generated_at_utc: str) -> str:
return report_generated_at_utc.replace("-", "").replace(":", "")
def _timestamped_report_path(path: Path, *, report_generated_at_utc: str) -> Path:
suffix = path.suffix
stem = path.name[: -len(suffix)] if suffix else path.name
return path.with_name(
f"{stem}-{_report_path_timestamp_slug(report_generated_at_utc)}{suffix}"
)
def _resolve_output_paths(
args: Namespace,
*,
report_path_origins: Mapping[str, ReportPathOrigin | None],
report_generated_at_utc: str,
) -> OutputPaths:
printer = cast("_PrinterLike", console)
resolved: dict[str, Path | None] = {
"html": None,
"json": None,
"md": None,
"sarif": None,
"text": None,
}
output_specs = (
("html", "html_out", ".html", "HTML"),
("json", "json_out", ".json", "JSON"),
("md", "md_out", ".md", "Markdown"),
("sarif", "sarif_out", ".sarif", "SARIF"),
("text", "text_out", ".txt", "text"),
)
for field_name, arg_name, expected_suffix, label in output_specs:
raw_value = getattr(args, arg_name, None)
if not raw_value:
continue
path = _validate_output_path(
raw_value,
expected_suffix=expected_suffix,
label=label,
console=printer,
invalid_message=ui.fmt_invalid_output_extension,
invalid_path_message=ui.fmt_invalid_output_path,
)
if (
args.timestamped_report_paths
and report_path_origins.get(field_name) == "default"
):
path = _timestamped_report_path(
path,
report_generated_at_utc=report_generated_at_utc,
)
resolved[field_name] = path
return OutputPaths(
html=resolved["html"],
json=resolved["json"],
text=resolved["text"],
md=resolved["md"],
sarif=resolved["sarif"],
)
def _validate_report_ui_flags(*, args: Namespace, output_paths: OutputPaths) -> None:
if args.open_html_report and output_paths.html is None:
console.print(ui.fmt_contract_error(ui.ERR_OPEN_HTML_REPORT_REQUIRES_HTML))
sys.exit(ExitCode.CONTRACT_ERROR)
if args.timestamped_report_paths and not any(
(
output_paths.html,
output_paths.json,
output_paths.md,
output_paths.sarif,
output_paths.text,
)
):
console.print(
ui.fmt_contract_error(ui.ERR_TIMESTAMPED_REPORT_PATHS_REQUIRES_REPORT)
)
sys.exit(ExitCode.CONTRACT_ERROR)
def _resolve_cache_path(*, root_path: Path, args: Namespace, from_args: bool) -> Path:
return _resolve_cache_path_impl(
root_path=root_path,
args=cast("_RuntimeArgsLike", cast(object, args)),
from_args=from_args,
legacy_cache_path=LEGACY_CACHE_PATH,
console=cast("_PrinterLike", console),
)
def _validate_numeric_args(args: Namespace) -> bool:
return _validate_numeric_args_impl(cast("_RuntimeArgsLike", cast(object, args)))
def _configure_metrics_mode(*, args: Namespace, metrics_baseline_exists: bool) -> None:
_configure_metrics_mode_impl(
args=cast("_RuntimeArgsLike", cast(object, args)),
metrics_baseline_exists=metrics_baseline_exists,
console=cast("_PrinterLike", console),
)
def _print_failed_files(failed_files: Sequence[str]) -> None:
_print_failed_files_impl(
failed_files=tuple(failed_files),
console=cast("_PrinterLike", console),
)
def _metrics_computed(args: Namespace) -> tuple[str, ...]:
return _metrics_computed_impl(cast("_RuntimeArgsLike", cast(object, args)))
def _probe_metrics_baseline_section(path: Path) -> _MetricsBaselineSectionProbe:
return _probe_metrics_baseline_section_impl(path)
def _resolve_clone_baseline_state(
*,
args: Namespace,
baseline_path: Path,
baseline_exists: bool,
analysis: AnalysisResult,
shared_baseline_payload: dict[str, object] | None = None,
) -> _CloneBaselineState:
return _resolve_clone_baseline_state_impl(
args=cast("_BaselineArgsLike", cast(object, args)),
baseline_path=baseline_path,
baseline_exists=baseline_exists,
func_groups=analysis.func_groups,
block_groups=analysis.block_groups,
codeclone_version=__version__,
console=cast("_PrinterLike", console),
shared_baseline_payload=shared_baseline_payload,
)
def _resolve_metrics_baseline_state(
*,
args: Namespace,
metrics_baseline_path: Path,
metrics_baseline_exists: bool,
baseline_updated_path: Path | None,
analysis: AnalysisResult,
shared_baseline_payload: dict[str, object] | None = None,
) -> _MetricsBaselineState:
return _resolve_metrics_baseline_state_impl(
args=cast("_BaselineArgsLike", cast(object, args)),
metrics_baseline_path=metrics_baseline_path,
metrics_baseline_exists=metrics_baseline_exists,
baseline_updated_path=baseline_updated_path,
project_metrics=analysis.project_metrics,
console=cast("_PrinterLike", console),
shared_baseline_payload=shared_baseline_payload,
)
def _resolve_cache_status(cache: Cache) -> tuple[CacheStatus, str | None]:
return _resolve_cache_status_impl(cache)
def _cache_update_segment_projection(cache: Cache, analysis: AnalysisResult) -> None:
if not hasattr(cache, "segment_report_projection"):
return
new_projection = build_segment_report_projection(
digest=analysis.segment_groups_raw_digest,
suppressed=analysis.suppressed_segment_groups,
groups=analysis.segment_groups,
)
if new_projection != cache.segment_report_projection:
cache.segment_report_projection = new_projection
cache._dirty = True
def _run_analysis_stages(
*,
args: Namespace,
boot: BootstrapResult,
cache: Cache,
) -> tuple[DiscoveryResult, PipelineProcessingResult, AnalysisResult]:
def _require_rich_console(
value: RichConsole | _PlainConsole,
) -> RichConsole:
if isinstance(value, _PlainConsole):
raise RuntimeError("Rich console is required when progress UI is enabled.")
return value
use_status = not args.quiet and not args.no_progress
try:
if use_status:
with console.status(ui.STATUS_DISCOVERING, spinner="dots"):
discovery_result = discover(boot=boot, cache=cache)
else:
discovery_result = discover(boot=boot, cache=cache)
except OSError as exc:
console.print(ui.fmt_contract_error(ui.ERR_SCAN_FAILED.format(error=exc)))
sys.exit(ExitCode.CONTRACT_ERROR)
for warning in discovery_result.skipped_warnings:
console.print(f"[warning]{warning}[/warning]")
total_files = len(discovery_result.files_to_process)
if total_files > 0 and not args.quiet and args.no_progress:
console.print(ui.fmt_processing_changed(total_files))
if total_files > 0 and not args.no_progress:
(
progress_cls,
spinner_column_cls,
text_column_cls,
bar_column_cls,
time_elapsed_column_cls,
) = _rich_progress_symbols()
with progress_cls(
spinner_column_cls(),
text_column_cls("[progress.description]{task.description}"),
bar_column_cls(),
text_column_cls("[progress.percentage]{task.percentage:>3.0f}%"),
time_elapsed_column_cls(),
console=_require_rich_console(console),
) as progress_ui:
task_id = progress_ui.add_task(
f"Analyzing {total_files} files...",
total=total_files,
)
processing_result = process(
boot=boot,
discovery=discovery_result,
cache=cache,
on_advance=lambda: progress_ui.advance(task_id),
on_worker_error=lambda reason: console.print(
ui.fmt_worker_failed(reason)
),
on_parallel_fallback=lambda exc: console.print(
ui.fmt_parallel_fallback(exc)
),
)
else:
processing_result = process(
boot=boot,
discovery=discovery_result,
cache=cache,
on_worker_error=(
(lambda reason: console.print(ui.fmt_batch_item_failed(reason)))
if args.no_progress
else (lambda reason: console.print(ui.fmt_worker_failed(reason)))
),
on_parallel_fallback=lambda exc: console.print(
ui.fmt_parallel_fallback(exc)
),
)
_print_failed_files(processing_result.failed_files)
# Keep unreadable-source diagnostics visible in normal mode even if
# failed_files was filtered/empty due upstream transport differences.
if not processing_result.failed_files and processing_result.source_read_failures:
_print_failed_files(processing_result.source_read_failures)
if use_status:
with console.status(ui.STATUS_GROUPING, spinner="dots"):
analysis_result = analyze(
boot=boot,
discovery=discovery_result,
processing=processing_result,
)
_cache_update_segment_projection(cache, analysis_result)
try:
cache.save()
except CacheError as exc:
console.print(ui.fmt_cache_save_failed(exc))
else:
analysis_result = analyze(
boot=boot,
discovery=discovery_result,
processing=processing_result,
)
_cache_update_segment_projection(cache, analysis_result)
try:
cache.save()
except CacheError as exc:
console.print(ui.fmt_cache_save_failed(exc))
return discovery_result, processing_result, analysis_result
def _write_report_outputs(
*,
args: Namespace,
output_paths: OutputPaths,
report_artifacts: ReportArtifacts,
open_html_report: bool = False,
) -> str | None:
return _write_report_outputs_impl(
args=cast("_QuietArgsLike", cast(object, args)),
output_paths=output_paths,
report_artifacts=report_artifacts,
console=cast("_PrinterLike", console),
open_html_report=open_html_report,
)
def _enforce_gating(
*,
args: Namespace,
boot: BootstrapResult,
analysis: AnalysisResult,
processing: PipelineProcessingResult,
source_read_contract_failure: bool,
baseline_failure_code: ExitCode | None,
metrics_baseline_failure_code: ExitCode | None,
new_func: set[str],
new_block: set[str],
metrics_diff: MetricsDiff | None,
html_report_path: str | None,
) -> None:
if source_read_contract_failure:
console.print(
ui.fmt_contract_error(
ui.fmt_unreadable_source_in_gating(
count=len(processing.source_read_failures)
)
)
)
for failure in processing.source_read_failures[:10]:
console.print(f" • {failure}")
if len(processing.source_read_failures) > 10:
console.print(f" ... and {len(processing.source_read_failures) - 10} more")
sys.exit(ExitCode.CONTRACT_ERROR)
if baseline_failure_code is not None:
console.print(ui.fmt_contract_error(ui.ERR_BASELINE_GATING_REQUIRES_TRUSTED))
sys.exit(baseline_failure_code)
if metrics_baseline_failure_code is not None:
console.print(
ui.fmt_contract_error(
"Metrics baseline is untrusted or missing for requested metrics gating."
)
)
sys.exit(metrics_baseline_failure_code)
gate_result = gate(
boot=boot,
analysis=analysis,
new_func=new_func,
new_block=new_block,
metrics_diff=metrics_diff,
)
metric_reasons = [
reason[len("metric:") :]
for reason in gate_result.reasons
if reason.startswith("metric:")
]
if metric_reasons:
_print_gating_failure_block(
code="metrics",
entries=[_parse_metric_reason_entry(reason) for reason in metric_reasons],
args=args,
)
sys.exit(ExitCode.GATING_FAILURE)
if "clone:new" in gate_result.reasons:
default_report = Path(".cache/codeclone/report.html")
resolved_html_report_path = html_report_path
if resolved_html_report_path is None and default_report.exists():
resolved_html_report_path = str(default_report)
clone_entries: list[tuple[str, object]] = [
("new_function_clone_groups", len(new_func)),
("new_block_clone_groups", len(new_block)),
]
if resolved_html_report_path:
clone_entries.append(("report", resolved_html_report_path))
clone_entries.append(("accept", "codeclone . --update-baseline"))
_print_gating_failure_block(
code="new-clones",
entries=clone_entries,
args=args,
)
if args.verbose:
_print_verbose_clone_hashes(
cast("_PrinterLike", console),
label="Function clone hashes",
clone_hashes=new_func,
)
_print_verbose_clone_hashes(
cast("_PrinterLike", console),
label="Block clone hashes",
clone_hashes=new_block,
)
sys.exit(ExitCode.GATING_FAILURE)
threshold_reason = next(
(
reason
for reason in gate_result.reasons
if reason.startswith("clone:threshold:")
),
None,
)
if threshold_reason is not None:
_, _, total_raw, threshold_raw = threshold_reason.split(":", maxsplit=3)
total = int(total_raw)
threshold = int(threshold_raw)
_print_gating_failure_block(
code="threshold",
entries=(
("clone_groups_total", total),
("clone_groups_limit", threshold),
),
args=args,
)
sys.exit(ExitCode.GATING_FAILURE)
def _main_impl() -> None:
global console
run_started_at = time.monotonic()
from ._cli_meta import _build_report_meta, _current_report_timestamp_utc
ap = build_parser(__version__)
def _prepare_run_inputs() -> tuple[
Namespace,
Path,
Path,
bool,
Path,
bool,
OutputPaths,
Path,
dict[str, object] | None,
str,
]:
global console
raw_argv = tuple(sys.argv[1:])
explicit_cli_dests = collect_explicit_cli_dests(ap, argv=raw_argv)
report_path_origins = _report_path_origins(raw_argv)
report_generated_at_utc = _current_report_timestamp_utc()
cache_path_from_args = any(
arg in {"--cache-dir", "--cache-path"}
or arg.startswith(("--cache-dir=", "--cache-path="))
for arg in sys.argv
)
metrics_path_from_args = any(
arg == "--metrics-baseline" or arg.startswith("--metrics-baseline=")
for arg in sys.argv
)
args = ap.parse_args()
try:
root_path = Path(args.root).resolve()
if not root_path.exists():
console.print(
ui.fmt_contract_error(ui.ERR_ROOT_NOT_FOUND.format(path=root_path))
)
sys.exit(ExitCode.CONTRACT_ERROR)
except OSError as exc:
console.print(
ui.fmt_contract_error(ui.ERR_INVALID_ROOT_PATH.format(error=exc))
)
sys.exit(ExitCode.CONTRACT_ERROR)
try:
pyproject_config = load_pyproject_config(root_path)
except ConfigValidationError as exc:
console.print(ui.fmt_contract_error(str(exc)))
sys.exit(ExitCode.CONTRACT_ERROR)
apply_pyproject_config_overrides(
args=args,
config_values=pyproject_config,
explicit_cli_dests=explicit_cli_dests,
)
if args.debug:
os.environ["CODECLONE_DEBUG"] = "1"
if args.ci:
args.fail_on_new = True
args.no_color = True
args.quiet = True
console = (
_make_plain_console()
if args.quiet
else _make_console(no_color=args.no_color)
)
if not _validate_numeric_args(args):
console.print(
ui.fmt_contract_error(
"Size limits must be non-negative integers (MB), "
"threshold flags must be >= 0 or -1."
)
)
sys.exit(ExitCode.CONTRACT_ERROR)
baseline_arg_path = Path(args.baseline).expanduser()
try:
baseline_path = baseline_arg_path.resolve()
baseline_exists = baseline_path.exists()
except OSError as exc:
console.print(
ui.fmt_contract_error(
ui.fmt_invalid_baseline_path(path=baseline_arg_path, error=exc)
)
)
sys.exit(ExitCode.CONTRACT_ERROR)
shared_baseline_payload: dict[str, object] | None = None
default_metrics_baseline = ap.get_default("metrics_baseline")
metrics_path_overridden = metrics_path_from_args or (
args.metrics_baseline != default_metrics_baseline
)
metrics_baseline_arg_path = Path(
args.metrics_baseline if metrics_path_overridden else args.baseline
).expanduser()
try:
metrics_baseline_path = metrics_baseline_arg_path.resolve()
if metrics_baseline_path == baseline_path:
probe = _probe_metrics_baseline_section(metrics_baseline_path)
metrics_baseline_exists = probe.has_metrics_section
shared_baseline_payload = probe.payload
else:
metrics_baseline_exists = metrics_baseline_path.exists()
except OSError as exc:
console.print(
ui.fmt_contract_error(
ui.fmt_invalid_baseline_path(
path=metrics_baseline_arg_path,
error=exc,
)
)
)
sys.exit(ExitCode.CONTRACT_ERROR)
if (
args.update_baseline
and not args.skip_metrics
and not args.update_metrics_baseline
):
args.update_metrics_baseline = True
_configure_metrics_mode(
args=args,
metrics_baseline_exists=metrics_baseline_exists,
)
if (
args.update_metrics_baseline
and metrics_baseline_path == baseline_path
and not baseline_exists
and not args.update_baseline
):