-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcli.py
1232 lines (1113 loc) Β· 37.9 KB
/
cli.py
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
from __future__ import annotations
import argparse
import json
import sys
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any
from tach import __version__, cache, extension, icons
from tach import filesystem as fs
from tach.check_external import check_external
from tach.console import console_err
from tach.constants import CONFIG_FILE_NAME, TOOL_NAME
from tach.errors import (
TachCircularDependencyError,
TachClosedBetaError,
TachConfigError,
TachError,
TachSetupError,
TachVisibilityError,
)
from tach.extension import ProjectConfig
from tach.filesystem import install_pre_commit
from tach.init import init_project
from tach.logging import CallInfo, init_logging, logger
from tach.modularity import export_report, upload_report_to_gauge
from tach.parsing import extend_and_validate, parse_project_config
from tach.report import external_dependency_report, report
from tach.show import (
generate_module_graph_dot_file,
generate_module_graph_mermaid,
upload_show_report,
)
from tach.test import run_affected_tests
if TYPE_CHECKING:
from tach.extension import UnusedDependencies
import signal
def handle_sigint(_signum: int, _frame: Any) -> None:
print("Exiting...")
sys.exit(1)
signal.signal(signal.SIGINT, handle_sigint)
def print_unused_dependencies(
all_unused_dependencies: list[UnusedDependencies],
) -> None:
constraint_messages = "\n".join(
f"{icons.FAIL} [bold]'{unused_dependencies.path}'[/] does not depend on: [bold]{[dependency.path for dependency in unused_dependencies.dependencies]}[/]"
for unused_dependencies in all_unused_dependencies
)
console_err.print(
"[red bold]Unused Dependencies[/]\n" + f"[yellow]{constraint_messages}[/]"
)
console_err.print(
f"\nRemove the unused dependencies from {CONFIG_FILE_NAME}.toml, "
f"or consider running '{TOOL_NAME} sync' to update module configuration and "
f"remove all unused dependencies.\n",
style="yellow",
)
def print_no_config_found(
output_format: str = "text", *, config_file_name: str = CONFIG_FILE_NAME
) -> None:
if output_format == "json":
json.dump({"error": "No config file found"}, sys.stdout)
else:
console_err.print(
f"{config_file_name}.toml not found. Do you need to run [cyan]'{TOOL_NAME} init'[/]?",
style="red",
)
def print_no_modules_found() -> None:
console_err.print(
f"No modules defined in {CONFIG_FILE_NAME}.toml. Do you need to run [cyan]'tach mod'[/]?",
style="red",
)
def print_no_dependencies_found() -> None:
console_err.print(
f"No dependencies defined in {CONFIG_FILE_NAME}.toml. You may need to run [cyan]'tach sync'[/] or check your python source root.",
style="red",
)
def print_show_web_suggestion(is_mermaid: bool = False) -> None:
if is_mermaid:
console_err.print(
"NOTE: You are generating a Mermaid graph locally representing your module graph. For a remotely hosted visualization, use the '--web' argument.\nTo visualize your graph, you will need to use Mermaid.js: https://mermaid.js.org/config/usage.html\n",
style="cyan",
)
else:
console_err.print(
"NOTE: You are generating a DOT file locally representing your module graph. For a remotely hosted visualization, use the '--web' argument.\nTo visualize your graph, you will need a program like GraphViz: https://www.graphviz.org/download/\n",
style="cyan",
)
def print_generated_module_graph_file(
output_filepath: Path, is_mermaid: bool = False
) -> None:
if is_mermaid:
console_err.print(
f"Generated a Mermaid file containing your module graph at '{output_filepath}'",
style="green",
)
else:
console_err.print(
f"Generated a DOT file containing your module graph at '{output_filepath}'",
style="green",
)
def print_circular_dependency_error(
module_paths: list[str], output_format: str = "text"
) -> None:
if output_format == "json":
json.dump(
{"error": "Circular dependency", "dependencies": module_paths}, sys.stdout
)
else:
console_err.print(
"\n".join(
[
f"{icons.FAIL} [red]Circular dependency detected for module [/]'{module_path}'"
for module_path in module_paths
]
)
+ f"\n\n[yellow]Resolve circular dependencies.\n"
f"Remove or unset 'forbid_circular_dependencies' from "
f"'{CONFIG_FILE_NAME}.toml' to allow circular dependencies.[/]",
)
def print_visibility_errors(
visibility_errors: list[tuple[str, str, list[str]]], output_format: str = "text"
) -> None:
if output_format == "json":
json.dump(
{"error": "Visibility error", "visibility_errors": visibility_errors},
sys.stdout,
)
else:
for dependent_module, dependency_module, visibility in visibility_errors:
console_err.print(
f"{icons.FAIL} [red]Module configuration error:[/] [yellow]'{dependent_module}' cannot depend on '{dependency_module}' because '{dependent_module}' does not match its visibility: {visibility}.[/]"
"\n"
f"[yellow]Adjust 'visibility' for '{dependency_module}' to include '{dependent_module}', or remove the dependency.[/]"
"\n",
)
def add_base_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-e",
"--exclude",
required=False,
type=str,
metavar="file_or_path,...",
help="Comma separated path list to exclude. tests/, ci/, etc.",
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=TOOL_NAME,
add_help=True,
)
parser.add_argument(
"--version", action="version", version=f"{TOOL_NAME} {__version__}"
)
subparsers = parser.add_subparsers(title="commands", dest="command")
## tach mod
mod_parser = subparsers.add_parser(
"mod",
prog=f"{TOOL_NAME} mod",
help="Configure module boundaries interactively",
description="Configure module boundaries interactively",
)
mod_parser.add_argument(
"-d",
"--depth",
type=int,
nargs="?",
default=None,
help="The number of child directories to expand from the root",
)
add_base_arguments(mod_parser)
## tach check
check_parser = subparsers.add_parser(
"check",
prog=f"{TOOL_NAME} check",
help="Check existing boundaries against your dependencies and module interfaces",
description="Check existing boundaries against your dependencies and module interfaces",
)
check_parser.add_argument(
"--exact",
action="store_true",
help="When checking dependencies, raise errors if any dependencies are unused.",
)
check_parser.add_argument(
"--dependencies",
action="store_true",
help="Check dependency constraints between modules. When present, all checks must be explicitly enabled.",
)
check_parser.add_argument(
"--interfaces",
action="store_true",
help="Check interface implementations. When present, all checks must be explicitly enabled.",
)
check_parser.add_argument(
"--output",
choices=["text", "json"],
default="text",
help="Output format (default: text)",
)
add_base_arguments(check_parser)
## tach check-external
check_parser_external = subparsers.add_parser(
"check-external",
prog=f"{TOOL_NAME} check-external",
help="Perform checks related to third-party dependencies",
description="Perform checks related to third-party dependencies",
)
add_base_arguments(check_parser_external)
## tach sync
sync_parser = subparsers.add_parser(
"sync",
prog=f"{TOOL_NAME} sync",
help="Sync constraints with actual dependencies in your project.",
description="Sync constraints with actual dependencies in your project.",
)
sync_parser.add_argument(
"--add",
action="store_true",
help="Add any missing dependencies, but do not remove unused dependencies.",
)
add_base_arguments(sync_parser)
## tach report
report_parser = subparsers.add_parser(
"report",
prog=f"{TOOL_NAME} report",
help="Create a report of dependencies and usages.",
description="Create a report of dependencies and usages.",
)
report_parser.add_argument(
"path", help="The path or directory path used to generate the report."
)
# Report type flags
report_parser.add_argument(
"--dependencies",
action="store_true",
help="Generate dependency report. When present, all reports must be explicitly enabled.",
)
report_parser.add_argument(
"--usages",
action="store_true",
help="Generate usage report. When present, all reports must be explicitly enabled.",
)
report_parser.add_argument(
"--external",
action="store_true",
help="Generate external dependency report. When present, all reports must be explicitly enabled.",
)
# Report options
report_parser.add_argument(
"-d",
"--dependency-modules",
required=False,
type=str,
metavar="module_path,...",
help="Comma separated module list of dependencies to include [includes everything by default]",
)
report_parser.add_argument(
"-u",
"--usage-modules",
required=False,
type=str,
metavar="module_path,...",
help="Comma separated module list of usages to include [includes everything by default]",
)
report_parser.add_argument(
"--raw",
action="store_true",
help="Group lines by module and print each without any formatting.",
)
add_base_arguments(report_parser)
## tach show
show_parser = subparsers.add_parser(
"show",
prog=f"{TOOL_NAME} show",
help="Visualize the dependency graph of your project.",
description="Visualize the dependency graph of your project.",
)
show_parser.add_argument(
"included_paths",
type=Path,
nargs="*",
help="Paths to include in the module graph. If not provided, the entire project is included.",
)
show_parser.add_argument(
"--web",
action="store_true",
help="Open your dependency graph in a remote web viewer.",
)
show_parser.add_argument(
"--mermaid",
action="store_true",
help="Generate a mermaid.js graph instead of a DOT file.",
)
show_parser.add_argument(
"-o",
"--out",
type=Path,
nargs="?",
default=None,
help="Specify an output path for a locally generated module graph file.",
)
## tach install
install_parser = subparsers.add_parser(
"install",
prog=f"{TOOL_NAME} install",
help=f"Install {TOOL_NAME} into your workflow (e.g. as a pre-commit hook)",
description=f"Install {TOOL_NAME} into your workflow (e.g. as a pre-commit hook)",
)
install_parser.add_argument(
"target",
choices=InstallTarget.choices(),
help="What kind of installation to perform (e.g. pre-commit)",
)
## tach test
test_parser = subparsers.add_parser(
"test",
prog=f"{TOOL_NAME} test",
help="Run tests on modules impacted by the current changes.",
description="Run tests on modules impacted by the current changes.",
)
test_parser.add_argument(
"--base",
type=str,
nargs="?",
default="main",
help="The base commit to use when determining which modules are impacted by changes. [default: 'main']",
)
test_parser.add_argument(
"--head",
type=str,
nargs="?",
default="",
help="The head commit to use when determining which modules are impacted by changes. [default: current filesystem]",
)
test_parser.add_argument(
"--disable-cache",
action="store_true",
help="Do not check cache for results, and do not push results to cache.",
)
test_parser.add_argument(
"pytest_args",
nargs=argparse.REMAINDER,
help=f"Arguments forwarded to pytest. Use '--' to separate these arguments. Ex: '{TOOL_NAME} test -- -v'",
)
## tach upload
upload_parser = subparsers.add_parser(
"upload",
prog=f"{TOOL_NAME} upload",
help="[CLOSED BETA] Upload a modularity report to Gauge",
description="[CLOSED BETA] Upload a modularity report to Gauge",
)
upload_parser.add_argument(
"-f",
"--force",
action="store_true",
help="Ignore warnings and force the report to be generated.",
)
## tach export
export_parser = subparsers.add_parser(
"export",
prog=f"{TOOL_NAME} export",
help="Export a modularity report to a local file",
description="Export a modularity report to a local file",
)
export_parser.add_argument(
"-o",
"--output",
type=Path,
nargs="?",
default=None,
help="Specify an output path for the modularity report [DEFAULT: 'modularity_report.json']",
)
export_parser.add_argument(
"-f",
"--force",
action="store_true",
help="Ignore warnings and force the report to be generated.",
)
## tach server
server_parser = subparsers.add_parser(
"server",
prog=f"{TOOL_NAME} server",
help="Start the Language Server Protocol (LSP) server",
description="Start the Language Server Protocol (LSP) server",
)
server_parser.add_argument(
"-c",
"--config",
type=Path,
nargs="?",
default=None,
help="Path to the config file",
)
## tach init
init_parser = subparsers.add_parser(
"init",
prog=f"{TOOL_NAME} init",
help="Initialize a new project",
description="Initialize a new project",
)
init_parser.add_argument(
"--force",
action="store_true",
help="Force re-initialization if project is already configured.",
)
return parser
def parse_arguments(
args: list[str],
) -> tuple[argparse.Namespace, argparse.ArgumentParser]:
parser = build_parser()
parsed_args = parser.parse_args(args)
return parsed_args, parser
@dataclass
class CachedOutput:
key: str
output: list[tuple[int, str]] = field(default_factory=list)
exit_code: int | None = None
@property
def exists(self) -> bool:
return self.exit_code is not None
def replay(self):
for fd, output in self.output:
if fd == 1:
print(output, file=sys.stdout)
elif fd == 2:
print(output, file=sys.stderr)
def check_cache_for_action(
project_root: Path, project_config: ProjectConfig, action: str
) -> CachedOutput:
cache_key = extension.create_computation_cache_key(
project_root=project_root,
source_roots=[
project_root / source_root for source_root in project_config.source_roots
],
action=action,
py_interpreter_version=f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
file_dependencies=project_config.cache.file_dependencies,
env_dependencies=project_config.cache.env_dependencies,
backend=project_config.cache.backend,
)
cache_result = extension.check_computation_cache(
project_root=project_root, cache_key=cache_key
)
if cache_result:
return CachedOutput(
key=cache_key,
output=cache_result[0],
exit_code=cache_result[1],
)
return CachedOutput(key=cache_key)
def tach_check(
project_config: ProjectConfig,
project_root: Path,
exact: bool = False,
dependencies: bool = True,
interfaces: bool = True,
output_format: str = "text",
):
logger.info(
"tach check called",
extra={
"data": CallInfo(
function="tach_check",
parameters={"exact": exact, "output_format": output_format},
),
},
)
try:
exact |= project_config.exact
diagnostics = extension.check(
project_root=project_root,
project_config=project_config,
dependencies=dependencies,
interfaces=interfaces,
)
has_errors = any(diagnostic.is_error() for diagnostic in diagnostics)
if output_format == "json":
try:
print(
extension.serialize_diagnostics_json(diagnostics, pretty_print=True)
)
except ValueError as e:
json.dump({"error": str(e)}, sys.stdout)
sys.exit(1 if has_errors else 0)
if diagnostics:
print(
extension.format_diagnostics(
project_root=project_root, diagnostics=diagnostics
),
file=sys.stderr,
)
exit_code = 1 if has_errors else 0
# If we're checking in exact mode, we want to verify that there are no unused dependencies
if dependencies and exact:
unused_dependencies = extension.detect_unused_dependencies(
project_root=project_root,
project_config=project_config,
)
if unused_dependencies:
print_unused_dependencies(unused_dependencies)
exit_code = 1
except TachCircularDependencyError as e:
print_circular_dependency_error(e.dependencies, output_format)
sys.exit(1)
except TachVisibilityError as e:
print_visibility_errors(e.visibility_errors, output_format)
sys.exit(1)
except Exception as e:
if output_format == "json":
json.dump({"error": str(e)}, sys.stdout)
else:
print(str(e))
sys.exit(1)
if exit_code == 0 and output_format == "text":
console_err.print(f"{icons.SUCCESS} All modules validated!", style="green")
sys.exit(exit_code)
def tach_check_external(
project_config: ProjectConfig,
project_root: Path,
):
logger.info(
"tach check-external called",
extra={
"data": CallInfo(
function="tach_check_external",
),
},
)
try:
diagnostics = check_external(
project_root=project_root,
project_config=project_config,
)
if diagnostics:
print(
extension.format_diagnostics(
project_root=project_root, diagnostics=diagnostics
),
file=sys.stderr,
)
has_errors = any(diagnostic.is_error() for diagnostic in diagnostics)
if has_errors:
sys.exit(1)
else:
console_err.print(
f"{icons.SUCCESS} All external dependencies validated!", style="green"
)
sys.exit(0)
except Exception as e:
print(str(e))
sys.exit(1)
def tach_mod(
project_root: Path,
depth: int | None = 1,
exclude_paths: list[str] | None = None,
):
logger.info(
"tach mod called",
extra={
"data": CallInfo(
function="tach_mod",
parameters={"depth": depth},
),
},
)
# Local import because prompt_toolkit takes about ~80ms to load
from tach.mod import mod_edit_interactive
try:
project_config = parse_project_config(root=project_root) or ProjectConfig()
exclude_paths = extend_and_validate(
exclude_paths, project_config.exclude, project_config.use_regex_matching
)
saved_changes, warnings = mod_edit_interactive(
project_root=project_root,
project_config=project_config,
exclude_paths=exclude_paths,
depth=depth,
)
except Exception as e:
console_err.print(str(e))
sys.exit(1)
if warnings:
console_err.print("\n".join(warnings))
if saved_changes:
console_err.print(
f"{icons.SUCCESS} Set modules! You may want to run '{TOOL_NAME} sync' "
f"to automatically set boundaries.",
style="green",
)
sys.exit(0)
def tach_sync(
project_config: ProjectConfig,
project_root: Path,
add: bool = False,
):
logger.info(
"tach sync called",
extra={
"data": CallInfo(
function="tach_sync",
parameters={"add": add},
),
},
)
try:
extension.sync_project(
project_root=project_root,
project_config=project_config,
add=add,
)
except Exception as e:
print(str(e))
sys.exit(1)
console_err.print(f"{icons.SUCCESS} Synced dependencies.", style="green")
sys.exit(0)
class InstallTarget(Enum):
PRE_COMMIT = "pre-commit"
@classmethod
def choices(cls) -> list[str]:
return [item.value for item in cls]
def tach_install(project_root: Path, target: InstallTarget) -> None:
logger.info(
"tach install called",
extra={
"data": CallInfo(
function="tach_install",
),
},
)
try:
if target == InstallTarget.PRE_COMMIT:
installed, warning = install_pre_commit(project_root=project_root)
else:
raise NotImplementedError(f"Target {target} is not supported by 'install'.")
except Exception as e:
print(str(e))
sys.exit(1)
if installed:
console_err.print(
f"{icons.SUCCESS} Pre-commit hook installed to '.git/hooks/pre-commit'.",
style="green",
)
sys.exit(0)
else:
console_err.print(
f"Pre-commit hook could not be installed: {warning}",
style="yellow",
)
sys.exit(1)
def tach_report(
project_config: ProjectConfig,
project_root: Path,
path: str,
include_dependency_modules: list[str] | None = None,
include_usage_modules: list[str] | None = None,
dependencies: bool = False,
usages: bool = False,
external: bool = False,
raw: bool = False,
):
logger.info(
"tach report called",
extra={
"data": CallInfo(
function="tach_report",
parameters={
"dependencies": dependencies,
"usages": usages,
"external": external,
},
),
},
)
try:
# Generate reports based on flags
generate_all = not (dependencies or usages or external)
generate_dependencies = generate_all or dependencies
generate_usages = generate_all or usages
generate_external = generate_all or external
reports: list[str] = []
if generate_dependencies or generate_usages:
reports.append(
report(
project_root,
Path(path),
project_config=project_config,
include_dependency_modules=include_dependency_modules,
include_usage_modules=include_usage_modules,
skip_dependencies=not generate_dependencies,
skip_usages=not generate_usages,
raw=raw,
)
)
if generate_external:
reports.append(
external_dependency_report(
project_root,
Path(path),
raw=raw,
project_config=project_config,
)
)
print("\n".join(reports))
sys.exit(0)
except TachError as e:
print(f"Report failed: {e}", file=sys.stderr)
sys.exit(1)
def tach_show(
project_config: ProjectConfig,
project_root: Path,
included_paths: list[Path] | None = None,
is_web: bool = False,
is_mermaid: bool = False,
output_filepath: Path | None = None,
):
logger.info(
"tach show called",
extra={
"data": CallInfo(
function="tach_show",
parameters={"is_web": is_web, "is_mermaid": is_mermaid},
),
},
)
if is_web and is_mermaid:
console_err.print(
"Passing --web generates a remote graph; ignoring '--mermaid' flag.",
style="yellow",
)
if project_config.has_no_modules():
print_no_modules_found()
sys.exit(1)
if project_config.has_no_dependencies():
print_no_dependencies_found()
sys.exit(1)
try:
included_paths = list(
map(lambda path: project_root / path, included_paths or [])
)
if is_web:
result = upload_show_report(
project_root=project_root,
project_config=project_config,
included_paths=included_paths,
)
if result:
console_err.print("View your dependency graph here:")
console_err.print(result)
sys.exit(0)
else:
sys.exit(1)
else:
print_show_web_suggestion(is_mermaid=is_mermaid)
if is_mermaid:
output_filepath = output_filepath or Path(
f"{TOOL_NAME}_module_graph.mmd"
)
generate_module_graph_mermaid(
project_config,
included_paths=included_paths,
output_filepath=output_filepath,
)
print_generated_module_graph_file(output_filepath, is_mermaid=True)
sys.exit(0)
else:
output_filepath = output_filepath or Path(
f"{TOOL_NAME}_module_graph.dot"
)
generate_module_graph_dot_file(
project_config,
included_paths=included_paths,
output_filepath=output_filepath,
)
print_generated_module_graph_file(output_filepath)
sys.exit(0)
except TachError as e:
print(f"Failed to show module graph: {e}")
sys.exit(1)
def tach_test(
project_config: ProjectConfig,
project_root: Path,
head: str,
base: str,
disable_cache: bool,
pytest_args: list[Any],
):
logger.info(
"tach test called",
extra={
"data": CallInfo(
function="tach_test",
parameters={
"disable_cache": disable_cache,
"pytest_args": pytest_args,
},
),
},
)
if pytest_args and pytest_args[0] != "--":
console_err.print(
f"[red]Unknown arguments received. Use '--' to separate arguments for pytest. Ex: '{TOOL_NAME} test -- -v'[/]"
)
sys.exit(1)
try:
if disable_cache:
# If cache disabled, just run affected tests and exit
results = run_affected_tests(
project_root=project_root,
project_config=project_config,
head=head,
base=base,
pytest_args=pytest_args[1:], # Remove '--' pseudo-argument
)
sys.exit(results.exit_code)
# Below this line caching is enabled
cached_output = check_cache_for_action(
project_root, project_config, f"tach-test,{head},{base},{pytest_args}"
)
if cached_output.exists:
# Early exit, cached terminal output was found
console_err.print(
"============ Cached results found! ============",
style="green",
)
cached_output.replay()
console_err.print(
"============ END Cached results ============",
style="green",
)
sys.exit(cached_output.exit_code)
# Cache missed, capture terminal output while tests run so we can update the cache
results = run_affected_tests(
project_root=project_root,
project_config=project_config,
head=head,
base=base,
pytest_args=pytest_args[1:], # Remove '--' pseudo-argument
)
if results.tests_ran_to_completion:
extension.update_computation_cache(
project_root,
cache_key=cached_output.key,
value=(
[
*(
(1, stdout_line)
for stdout_line in results.stdout.split("\n")
),
*(
(2, stderr_line)
for stderr_line in results.stderr.split("\n")
),
],
results.exit_code,
),
)
sys.exit(results.exit_code)
except TachError as e:
console_err.print(f"[red]Report failed: {e}[/]")
sys.exit(1)
def tach_export(
project_config: ProjectConfig,
project_root: Path,
output_path: Path | None = None,
force: bool = False,
):
logger.info(
"tach export called",
extra={
"data": CallInfo(
function="tach_export",
parameters={"force": force},
),
},
)
try:
export_report(
project_root=project_root,
project_config=project_config,
output_path=output_path,
force=force,
)
except TachError as e:
print(f"Failed to export modularity report: {e}")
sys.exit(1)
def tach_upload(
project_config: ProjectConfig,
project_root: Path,
force: bool = False,
):
logger.info(
"tach upload called",
extra={
"data": CallInfo(
function="tach_upload",
parameters={"force": force},
),
},
)
try:
upload_report_to_gauge(
project_root=project_root,