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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use colored::Colorize;
use tracing::Level;
use tracing_subscriber::FmtSubscriber;
mod commands;
mod config;
mod data_dir;
mod embed;
mod engine;
mod error;
mod formatters;
mod git;
mod hook;
mod index;
mod mcp;
mod progress;
use index::schema;
use commands::{
auth, commit_cmd, completion, config_cmd, debt, hook_cmd, init, profile, providers, review,
scan, upload,
};
use config::loader;
use engine::memory;
use formatters::OutputFormat;
/// Cora — AI Code Review CLI with BYOK (Bring Your Own Key)
///
/// Review diffs and scan projects using any OpenAI-compatible LLM.
/// Configure via .cora.yaml, CLI flags, or environment variables.
#[derive(Parser, Debug)]
#[clap(
name = "cora",
version,
about = "CLI-first AI code review — BYOK, diff/scan/branch, pre-commit hooks",
long_version = concat!(env!("CARGO_PKG_VERSION"), "\n", env!("CARGO_PKG_REPOSITORY"))
)]
struct Cli {
/// Global options
#[command(flatten)]
global: GlobalOptions,
/// Subcommand
#[command(subcommand)]
command: Command,
}
#[derive(clap::Args, Debug, Clone)]
struct GlobalOptions {
/// Path to config file (default: auto-discover .cora.yaml)
#[clap(long, global = true, env = "CORA_CONFIG")]
pub config: Option<String>,
/// Output format: pretty, json, compact, sarif
#[clap(long, global = true, value_parser = ["pretty", "json", "compact", "sarif"], env = "CORA_FORMAT")]
pub format: Option<String>,
/// Disable colored output
#[clap(long, global = true, env = "CORA_NO_COLOR")]
pub no_color: bool,
/// LLM provider name (e.g. openai, anthropic, ollama)
#[clap(long, global = true, env = "CORA_PROVIDER")]
pub provider: Option<String>,
/// LLM model name (e.g. gpt-4o-mini, claude-3-haiku)
#[clap(long, global = true, env = "CORA_MODEL")]
pub model: Option<String>,
/// API base URL
#[clap(long, global = true, env = "CORA_BASE_URL")]
pub base_url: Option<String>,
/// API key (or set `CORA_API_KEY` env var for CI, or use `cora auth login`)
#[clap(long, global = true, env = "CORA_API_KEY")]
pub api_key: Option<String>,
/// Enable verbose logging
#[clap(long, global = true)]
pub verbose: bool,
}
#[derive(Subcommand, Debug)]
enum Command {
/// Build or update the symbol index for code intelligence
Index {
/// Show index statistics instead of building
#[clap(long)]
stats: bool,
/// Prune deleted files from index
#[clap(long)]
prune: bool,
/// Rebuild index from scratch (drop existing)
#[clap(long)]
rebuild: bool,
/// Watch for file changes and auto-update index
#[clap(long)]
watch: bool,
/// Verbose output
#[clap(long, short)]
verbose: bool,
},
/// Search the symbol index for code intelligence
Explore {
/// Search query (symbol name or keyword)
query: Option<String>,
/// Filter by symbol kind (function, struct, enum, trait, etc.)
#[clap(long)]
kind: Option<String>,
/// Filter by file path prefix
#[clap(long)]
file: Option<String>,
/// Filter by language
#[clap(long)]
language: Option<String>,
/// Maximum results
#[clap(long, default_value = "50")]
limit: usize,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Find all callers of a symbol (who calls this?)
Callers {
/// Symbol name to search for
symbol: String,
/// Maximum results
#[clap(long, default_value = "50")]
limit: usize,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Analyze the impact of changing a symbol (what breaks?)
Impact {
/// Symbol name to analyze
symbol: String,
/// Traversal depth (how many levels up the call graph)
#[clap(long, default_value = "3")]
depth: u32,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Trace execution paths through the codebase
Trace {
/// Symbol name to start tracing from
symbol: String,
/// Trace direction: outgoing (callees) or incoming (callers)
#[clap(long, value_parser = ["outgoing", "incoming"], default_value = "outgoing")]
direction: String,
/// Traversal depth (max hops)
#[clap(long, default_value = "3")]
depth: u32,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Show architecture overview (modules, edge types, structure)
Arch {
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Hybrid search: FTS5 + vector + graph → RRF fusion
Brain {
/// Search query
query: Vec<String>,
/// Maximum results (default: 20)
#[clap(long, default_value = "20")]
limit: usize,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Find tests affected by changed files
Affected {
/// Changed files (space-separated). If empty, reads from git diff.
files: Vec<String>,
/// Read changed files from stdin (pipe from git diff --name-only)
#[clap(long)]
stdin: bool,
/// Test file glob pattern (default: *test*, *spec*)
#[clap(long)]
filter: Option<String>,
/// Output as JSON
#[clap(long)]
json: bool,
},
/// Review staged changes, generate commit message, and commit
Commit {
/// YOLO mode — auto-commit without prompts
#[clap(long)]
yolo: bool,
/// Force commit even if quality gate fails
#[clap(long)]
force: bool,
/// Skip review, only generate commit message
#[clap(long)]
no_review: bool,
/// Always open editor to edit message
#[clap(long)]
edit: bool,
/// Stream LLM response in real-time
#[clap(long)]
stream: bool,
/// Suppress all output except the result
#[clap(long, short)]
quiet: bool,
},
/// Review a git diff (staged, unpushed, or branch)
Review {
/// Review staged changes (git diff --cached)
#[clap(long)]
staged: bool,
/// Review unpushed changes (HEAD vs @{u})
#[clap(long)]
unpushed: bool,
/// Review changes vs a base branch
#[clap(long)]
base: Option<String>,
/// Review changes from a git commit ref (e.g. HEAD, HEAD~3..HEAD, abc123)
#[clap(long)]
commit: Option<String>,
/// Read diff from a file instead of git
#[clap(long)]
diff_file: Option<String>,
/// Review unstaged changes (working tree)
#[clap(long)]
unstaged: bool,
/// Override max diff size in chars (default: 50000 from config)
#[clap(long, name = "CHARS")]
max_diff_size: Option<usize>,
/// Stream LLM response tokens in real-time
#[clap(long)]
stream: bool,
/// Disable auto-chunking for large diffs (auto-chunk is enabled by default)
#[clap(long)]
no_auto_chunk: bool,
/// Output structured NDJSON progress events to stderr
#[clap(long)]
progress: bool,
/// Suppress all output except the formatted review result
#[clap(long, short)]
quiet: bool,
/// Write formatted output to a file instead of stdout
#[clap(long, value_name = "PATH")]
output_file: Option<String>,
/// Filter results by minimum severity (info, minor, major, critical)
#[clap(long, value_parser = ["info", "minor", "major", "critical"])]
severity: Option<String>,
/// Disable review caching
#[clap(long)]
no_cache: bool,
/// CI mode: skip diff size limit, exit 2 if any findings
#[clap(long)]
ci: bool,
/// Upload SARIF output to GitHub Code Scanning after review
/// (implies --format sarif)
#[clap(long)]
upload: bool,
/// GitHub repository for upload (default: from git remote origin)
#[clap(long, env = "GITHUB_REPOSITORY")]
repo: Option<String>,
/// GitHub ref for upload (default: current branch)
#[clap(long, env = "GITHUB_REF")]
ref_name: Option<String>,
/// GitHub token for upload (default: `GITHUB_TOKEN` env var)
#[clap(long, env = "GITHUB_TOKEN")]
token: Option<String>,
/// Recall project patterns from Uteke before review (requires `uteke` CLI)
#[clap(long)]
memory: bool,
/// Save review findings to Uteke after review (implies --memory)
#[clap(long)]
learn: bool,
},
/// Scan a project directory for issues
Scan {
/// Root directory to scan (default: current directory)
#[clap(long)]
path: Option<String>,
/// Include glob patterns (e.g. "src/**/*.rs")
#[clap(long)]
include: Vec<String>,
/// Exclude glob patterns (e.g. "vendor/**")
#[clap(long)]
exclude: Vec<String>,
/// Additional file extensions to scan
#[clap(long)]
extensions: Vec<String>,
/// Only scan files changed since last scan (uses ~/.cora/scan-cache.json)
#[clap(long)]
incremental: bool,
/// Focus areas for review (overrides config)
#[clap(long)]
focus: Vec<String>,
/// Maximum files per LLM batch (default: 20). Lower this to work around
/// provider token limits or rate-limit errors on large scans.
#[clap(long, value_name = "N", default_value_t = 20)]
batch_files: usize,
/// Abort the entire scan when a batch fails to parse instead of
/// skipping it and continuing (default: skip and continue).
#[clap(long)]
no_continue_on_batch_error: bool,
},
/// Manage quality profiles (preset rule sets)
Profile {
#[command(subcommand)]
action: ProfileAction,
},
/// Upload a SARIF file to GitHub Code Scanning
UploadSarif {
/// Path to SARIF file to upload (default: reads from stdin)
file: Option<String>,
/// GitHub repository (default: from git remote origin)
#[clap(long, env = "GITHUB_REPOSITORY")]
repo: Option<String>,
/// GitHub ref (default: current branch)
#[clap(long, env = "GITHUB_REF")]
ref_name: Option<String>,
/// GitHub token (default: `GITHUB_TOKEN` env var)
#[clap(long, env = "GITHUB_TOKEN")]
token: Option<String>,
},
/// Create a .cora.yaml config file and install pre-commit hook
Init {
/// Overwrite existing config file
#[clap(long)]
force: bool,
/// Skip pre-commit hook installation
#[clap(long)]
no_hook: bool,
},
/// Manage pre-commit git hooks
Hook {
#[command(subcommand)]
action: HookAction,
},
/// Manage API key authentication
Auth {
#[command(subcommand)]
action: AuthAction,
},
/// View or set configuration
Config {
#[command(subcommand)]
action: ConfigAction,
},
/// List detected/available LLM providers
Providers,
/// Generate shell completion scripts
Completion {
/// Shell name: bash, zsh, fish, or powershell
shell: String,
},
/// Start MCP server (Model Context Protocol for AI agents)
Mcp,
/// Manage review findings (list, dismiss, reopen, stats)
Findings {
#[command(subcommand)]
action: commands::findings::FindingsAction,
},
/// Show tech debt report from review history
Debt {
/// Output as JSON
#[clap(long)]
json: bool,
/// Show quality score trend graph
#[clap(long)]
trend: bool,
/// Only show data since a date (YYYY-MM-DD) or git tag
#[clap(long)]
since: Option<String>,
/// Filter by branch name
#[clap(long)]
branch: Option<String>,
/// Output shields.io badge JSON
#[clap(long)]
badge: bool,
/// Show estimated debt fix time
#[clap(long)]
estimate: bool,
},
}
#[derive(Subcommand, Debug)]
enum HookAction {
/// Install the pre-commit hook
Install,
/// Uninstall the pre-commit hook
Uninstall,
}
#[derive(Subcommand, Debug)]
enum AuthAction {
/// Save an API key to local config
Login {
/// Provider name (e.g. openai, zai, anthropic, ollama) — skips interactive selection
#[clap(long)]
provider: Option<String>,
/// API key — skips interactive prompt
#[clap(long)]
api_key: Option<String>,
/// Model name (e.g. glm-5.1, gpt-4o-mini) — used with --provider
#[clap(long)]
model: Option<String>,
/// Base URL — used with --provider for custom endpoints
#[clap(long)]
base_url: Option<String>,
/// Skip confirmation when overwriting existing key
#[clap(long)]
force: bool,
},
/// Check if an API key is configured
Status,
/// Remove the stored API key
Remove,
}
#[derive(Subcommand, Debug)]
enum ConfigAction {
/// Show the current resolved configuration
Show {
/// Show only global config (~/.cora/config.yaml)
#[clap(long, conflicts_with = "project")]
global: bool,
/// Show only project config (.cora.yaml)
#[clap(long, conflicts_with = "global")]
project: bool,
},
/// Set a configuration value (keys: model, provider, `base_url`, format, severity)
Set {
/// Configuration key to set
key: String,
/// Value to assign
value: String,
/// Write to global config (~/.cora/config.yaml) instead of project .cora.yaml
#[clap(long)]
global: bool,
},
/// Validate the current configuration and report status
Validate,
}
#[derive(Subcommand, Debug)]
enum ProfileAction {
/// List available quality profiles
List,
/// Show details of a specific profile
Show {
/// Profile name (e.g. security-first, rust-strict)
name: String,
},
/// Validate a custom profile YAML file
Validate {
/// Path to the profile YAML file
path: String,
},
}
/// Format bytes as human-readable string.
fn format_bytes(bytes: u64) -> String {
if bytes < 1024 {
format!("{bytes} B")
} else if bytes < 1024 * 1024 {
format!("{:.1} KB", bytes as f64 / 1024.0)
} else {
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
}
}
#[allow(clippy::too_many_lines)]
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
// Set up logging based on verbosity
let log_level = if cli.global.verbose {
Level::DEBUG
} else {
Level::WARN
};
let subscriber = FmtSubscriber::builder()
.with_max_level(log_level)
.with_target(false)
.with_writer(std::io::stderr) // logs/warns must go to stderr, not stdout
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("cora=warn")),
)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
// Handle --no-color
if cli.global.no_color {
colored::control::set_override(false);
}
// Dispatch based on subcommand
let exit_code = match cli.command {
Command::Index {
stats: show_stats,
prune,
rebuild,
watch,
verbose,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
if rebuild {
// Delete all data for this project via CASCADE
schema::delete_project(&conn, project_id)?;
eprintln!("{}", "Dropped existing index for project.".dimmed());
// Re-register the project (gets a fresh project_id)
let _fresh_id =
schema::get_or_create_project(&conn, &project_root.to_string_lossy())?;
}
if show_stats {
let summary = index::index_stats(&conn, project_id)?;
println!("{}", "SYMBOL INDEX".cyan().bold());
println!("{}", "────────────────────────────".dimmed());
println!(" Total symbols: {}", summary.total_symbols);
println!(" Total files: {}", summary.total_files);
println!(" Database size: {}", format_bytes(summary.db_size_bytes));
println!();
println!(" {}", "By Kind".cyan());
for (kind, count) in &summary.symbols_by_kind {
println!(" {kind:<16} {count}");
}
println!();
println!(" {}", "By Language".cyan());
for (lang, count) in &summary.symbols_by_language {
println!(" {lang:<16} {count}");
}
} else if prune {
let deleted = index::prune_deleted(&conn, project_id, &project_root)?;
println!(
"{}",
format!("Pruned {deleted} deleted files from index.").green()
);
} else if watch {
// Initial index
eprintln!("{}", "🔍 Initial index...".cyan());
let stats =
index::index_project(&conn, &project_root, verbose || cli.global.verbose)?;
eprintln!(
"{}",
format!(
"✅ Indexed {} symbols. Watching for changes... (Ctrl+C to stop)",
stats.symbols_indexed
)
.green()
);
// Poll loop: re-index changed files every 2 seconds
loop {
std::thread::sleep(std::time::Duration::from_secs(2));
let stats = index::index_project(&conn, &project_root, false)?;
if stats.files_indexed > 0 {
eprintln!(
"{}",
format!(
"🔄 Updated {} files, {} symbols",
stats.files_indexed, stats.symbols_indexed
)
.cyan()
);
}
}
} else {
eprintln!("{}", "🔍 Indexing project...".cyan());
let stats =
index::index_project(&conn, &project_root, verbose || cli.global.verbose)?;
eprintln!(
"{}",
format!(
"✅ Indexed {} symbols from {} files ({} skipped, {} errors)",
stats.symbols_indexed,
stats.files_indexed,
stats.files_skipped,
stats.errors
)
.green()
);
eprintln!(
"{}",
format!(
" Database: {}",
crate::data_dir::graph_db_path().display()
)
.dimmed()
);
}
0
}
Command::Explore {
query,
kind,
file,
language,
limit,
json,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let sym_kind = kind.as_deref().map(index::SymbolKind::from_str);
let q = index::SymbolQuery {
text: query,
kind: sym_kind,
file_prefix: file,
language,
limit,
};
let results = index::search(&conn, project_id, &q)?;
if json {
let json_results: Vec<serde_json::Value> = results
.iter()
.map(|r| {
serde_json::json!({
"name": r.symbol.name,
"kind": r.symbol.kind.as_str(),
"file": r.symbol.file,
"line": r.symbol.line,
"signature": r.symbol.signature,
"language": r.symbol.language,
"score": r.score,
})
})
.collect();
println!("{}", serde_json::to_string_pretty(&json_results)?);
} else if results.is_empty() {
eprintln!("{}", "No symbols found.".yellow());
} else {
println!("{}", format!("Found {} symbols:", results.len()).cyan());
println!(
"{}",
"───────────────────────────────────────────────".dimmed()
);
for r in &results {
println!(
" {} {} {}:{}",
r.symbol.kind.as_str().blue(),
r.symbol.name.white().bold(),
r.symbol.file.dimmed(),
r.symbol.line
);
if !r.symbol.signature.is_empty() {
println!(
" {} {}",
"→".dimmed(),
r.symbol.signature.trim().dimmed()
);
}
}
}
0
}
Command::Callers {
symbol,
limit,
json,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let callers = index::graph::find_callers(&conn, project_id, &symbol, limit)?;
// Cross-project fallback: if no callers in current project,
// search across all indexed projects.
let cross_project_results = if callers.is_empty() {
let cp = index::graph::find_callers_cross_project(&conn, &symbol, limit)?;
if !cp.is_empty() {
if !json {
eprintln!(
"{}",
format!(
"No callers in current project. Found {} in other project(s):",
cp.len()
)
.yellow()
);
}
Some(cp)
} else {
None
}
} else {
None
};
if json {
if let Some(ref cp) = cross_project_results {
println!("{}", serde_json::to_string_pretty(cp)?);
} else {
println!("{}", serde_json::to_string_pretty(&callers)?);
}
} else if callers.is_empty() && cross_project_results.is_some() {
let cp = cross_project_results.as_ref().unwrap();
println!(
"{}",
format!("Callers of '{symbol}' ({}):", cp.len()).cyan()
);
println!("{}", "─".repeat(50).dimmed());
for c in cp {
println!(
" {} {}:{} {}",
c.caller.white().bold(),
c.file.dimmed(),
c.line,
c.project_root.dimmed().italic(),
);
}
} else if callers.is_empty() {
eprintln!("{}", format!("No callers found for '{symbol}'.").yellow());
} else {
println!(
"{}",
format!("Callers of '{symbol}' ({}):", callers.len()).cyan()
);
println!("{}", "─".repeat(50).dimmed());
for c in &callers {
println!(
" {} {}:{}",
c.caller.white().bold(),
c.file.dimmed(),
c.line
);
}
}
0
}
Command::Impact {
symbol,
depth,
json,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run 'cora index' first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let impact = index::graph::impact_analysis(&conn, project_id, &symbol, depth)?;
if json {
println!("{}", serde_json::to_string_pretty(&impact)?);
} else if impact.is_empty() {
eprintln!("{}", format!("No impact found for '{}'.", symbol).yellow());
} else {
println!(
"{}",
format!(
"Impact of changing '{}' ({} affected):",
symbol,
impact.len()
)
.cyan()
);
println!("{}", "\u{2500}".repeat(50).dimmed());
let mut prev_depth = 0;
for node in &impact {
if node.depth != prev_depth {
prev_depth = node.depth;
println!(" {}", format!("depth {}", node.depth).blue().bold());
}
println!(
" {} {}:{}",
node.symbol.white(),
node.file.dimmed(),
node.line
);
}
}
0
}
Command::Trace {
symbol,
direction,
depth,
json,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let dir = match direction.as_str() {
"incoming" => index::graph::TraceDirection::Incoming,
_ => index::graph::TraceDirection::Outgoing,
};
let nodes = index::graph::trace_path(&conn, project_id, &symbol, depth, dir)?;
if json {
println!("{}", serde_json::to_string_pretty(&nodes)?);
} else if nodes.is_empty() {
eprintln!("{}", format!("No trace results for '{symbol}'.").yellow());
} else {
let dir_label = match dir {
index::graph::TraceDirection::Outgoing => "calls",
index::graph::TraceDirection::Incoming => "called by",
};
println!(
"{}",
format!(
"Trace from '{}' ({}, {} nodes):",
symbol,
dir_label,
nodes.len()
)
.cyan()
);
println!("{}", "─".repeat(60).dimmed());
let mut prev_depth = 0u32;
for node in &nodes {
if node.depth != prev_depth {
prev_depth = node.depth;
println!(" {}", format!("depth {}", node.depth).blue().bold());
}
let indent = " ".repeat(node.depth as usize + 1);
let kind_tag = format!("[{}]", node.kind).dimmed();
println!(
" {}{} {} {}:{}",
indent,
node.symbol.white().bold(),
kind_tag,
node.file.dimmed(),
node.line
);
}
}
0
}
Command::Arch { json } => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let overview = index::graph::arch_overview(&conn, project_id)?;
if json {
println!("{}", serde_json::to_string_pretty(&overview)?);
} else {
println!("{}", "ARCHITECTURE OVERVIEW".cyan().bold());
println!("{}", "─".repeat(50).dimmed());
println!();
println!(
" {} {} {}",
"MODULE".bold(),
"SYMBOLS".bold(),
"EDGE TYPES".bold()
);
println!(" {}", "─".repeat(45).dimmed());
for m in &overview.modules {
println!(
" {:<30} {:>6} {:>10}",
m.name, m.symbol_count, m.edge_types
);
}
println!();
if !overview.edge_counts.is_empty() {
println!(" {}", "EDGE DISTRIBUTION".cyan().bold());
println!(" {}", "─".repeat(45).dimmed());
for (kind, count) in &overview.edge_counts {
println!(" {:<20} {:>6}", kind, count);
}
}
}
0
}
Command::Brain { query, limit, json } => {
let query_str = query.join(" ");
if query_str.trim().is_empty() {
eprintln!("{}", "Usage: cora brain <query>".yellow());
std::process::exit(1);
}
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
let results = index::brain::brain_search(&conn, project_id, &query_str, limit)?;
if json {
println!("{}", serde_json::to_string_pretty(&results)?);
} else {
if results.is_empty() {
println!("{}", "No results found.".dimmed());
} else {
println!(
"{} {} results for '{}'",
"🧠".magenta(),
results.len().to_string().bold(),
query_str
);
println!("{}", "─".repeat(60).dimmed());
for r in &results {
let signals = r.signals.join(",");
let score = format!("{:.4}", r.score);
println!(
" {:<40} {:<15} {} {}",
format!("{} ({})", r.name, r.file).green(),
format!("[{}]", r.kind).dimmed(),
format!("score={}", score).cyan(),
format!("signals={}", signals).dimmed(),
);
}
}
}
0
}
Command::Affected {
files,
stdin,
filter,
json,
} => {
let project_root = std::env::current_dir()?;
let project_root = index::resolve_project_root(&project_root).unwrap_or(project_root);
let db_path = crate::data_dir::graph_db_path();
if !db_path.exists() {
eprintln!("{}", "No index found. Run `cora index` first.".yellow());
std::process::exit(1);
}
let conn = index::open_global_index()?;
let project_id = index::ensure_project(&conn, &project_root)?;
// Gather changed files
let mut changed: Vec<String> = files;
if stdin {
use std::io::BufRead;
let stdin = std::io::stdin();
for line in stdin.lock().lines().map_while(Result::ok) {
let trimmed = line.trim().to_string();
if !trimmed.is_empty() {
changed.push(trimmed);
}
}
}
if changed.is_empty() {
// Fallback: get from git diff
let output = std::process::Command::new("git")
.args(["diff", "--name-only", "HEAD"])
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout);
changed = stdout
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
}
if changed.is_empty() {
eprintln!("{}", "No changed files detected.".yellow());
std::process::exit(0);
}
// Default test patterns
let patterns: Vec<String> = filter.map(|f| vec![f]).unwrap_or_else(|| {
vec![
"test".to_string(),
"spec".to_string(),
"_test".to_string(),
"_spec".to_string(),
]
});
// Find test files that import/reference changed source files
let mut affected_tests: std::collections::HashSet<String> =
std::collections::HashSet::new();
// Strategy 1: Find symbols in changed files, then find callers that are in test files
// Batch: fetch all symbols for all changed files in a single query
let all_symbols: Vec<String> = {
let placeholders: String =
changed.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let n = changed.len() + 1;
let sql = format!(
"SELECT DISTINCT name FROM symbols WHERE file IN ({placeholders}) AND project_id = ?{n}"
);
let mut stmt = conn.prepare(&sql)?;
let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = changed
.iter()
.map(|f| Box::new(f.clone()) as Box<dyn rusqlite::types::ToSql>)
.collect();
params.push(Box::new(project_id));
let param_refs: Vec<&dyn rusqlite::types::ToSql> =
params.iter().map(|p| p.as_ref()).collect();
let rows = stmt.query_map(param_refs.as_slice(), |row| row.get::<_, String>(0))?;
rows.filter_map(|r| r.ok()).collect()
};
// Deduplicate symbols and resolve callers with a single set-based query
{
let mut seen_syms: std::collections::HashSet<String> =
std::collections::HashSet::new();
for sym_name in all_symbols {
if seen_syms.insert(sym_name.clone()) {
let callers =
index::graph::find_callers(&conn, project_id, &sym_name, 100)?;
for caller in callers {
if patterns.iter().any(|p| caller.file.contains(p.as_str())) {
affected_tests.insert(caller.file.clone());
}
}
}
}
}
// Strategy 2: Direct test file name convention (mod_test.rs, foo_test.go)
// Prepare statement once before the loop
let mut stmt = conn.prepare(
"SELECT DISTINCT path FROM files WHERE path LIKE ?1 AND project_id = ?2",
)?;
for file in &changed {
// For Rust: src/foo.rs → tests/foo.rs or src/foo.rs → src/foo_test.rs
let stem = file
.rsplit('/')
.next()
.unwrap_or(file)
.rsplit('.')
.next()
.unwrap_or("");
let test_patterns = [
format!("{stem}_test.rs"),
format!("tests/{stem}.rs"),
format!("test_{stem}.rs"),
format!("{stem}_test.go"),
format!("{stem}_test.py"),
format!("test_{stem}.py"),
format!("{stem}.test.ts"),
format!("{stem}.spec.ts"),
];
for tp in &test_patterns {
let pattern = format!("%{tp}");
let rows = stmt.query_map(rusqlite::params![pattern, project_id], |row| {
row.get::<_, String>(0)
})?;
for f in rows.map_while(Result::ok) {
affected_tests.insert(f);
}
}
}
let mut sorted: Vec<String> = affected_tests.into_iter().collect();
sorted.sort();
if json {
println!("{}", serde_json::to_string_pretty(&sorted)?);
} else if sorted.is_empty() {
eprintln!("{}", "No affected test files found.".yellow());
} else {
println!(
"{}",
format!("Affected test files ({}):", sorted.len()).cyan()
);
println!("{}", "\u{2500}".repeat(50).dimmed());
for f in &sorted {
println!(" {}", f.white().bold());
}
}
0
}
Command::Commit {
yolo,
force,
no_review,
edit,
stream,
quiet,
} => {
let config = loader::load_config(
cli.global.config.as_deref(),
cli.global.provider.as_deref(),
cli.global.model.as_deref(),
cli.global.base_url.as_deref(),
cli.global.format.as_deref(),
cli.global.no_color,
)?;
let llm_config = loader::build_llm_config(&config, cli.global.api_key.as_deref())?;
let opts = commit_cmd::CommitOptions {
yolo,
force,
no_review,
edit,
stream,
quiet,
};
commit_cmd::execute_commit(&config, &llm_config, &opts).await?
}
Command::Review {
staged,
unpushed,
base,
commit,
diff_file,
unstaged,
max_diff_size,
stream,
no_auto_chunk,
progress,
quiet,
output_file,
severity,
no_cache,
ci,
upload,
repo,
ref_name,
token,
memory,
learn,
} => {
cmd_review(
&cli.global,
ReviewOpts {
staged,
unpushed,
base,
commit,
diff_file,
unstaged,
max_diff_size,
stream,
no_auto_chunk,
progress,
quiet,
output_file,
severity,
upload,
repo,
ref_name,
token,
no_cache,
ci,
memory,
learn,
},
)
.await?
}
Command::Scan {
path,
include,
exclude,
extensions,
incremental,
focus,
batch_files,
no_continue_on_batch_error,
} => {
cmd_scan(
&cli.global,
ScanOpts {
path,
include,
exclude,
extensions,
incremental,
focus,
batch_files,
continue_on_batch_error: !no_continue_on_batch_error,
},
)
.await?
}
Command::Profile { action } => {
match action {
ProfileAction::List => profile::execute_profile_list()?,
ProfileAction::Show { name } => profile::execute_profile_show(&name)?,
ProfileAction::Validate { path } => profile::execute_profile_validate(&path)?,
}
0
}
Command::UploadSarif {
file,
repo,
ref_name,
token,
} => {
let opts = upload::UploadOptions {
file,
repo,
ref_name,
token,
};
upload::execute_upload(&opts).await?
}
Command::Init { force, no_hook } => {
if force {
init::execute_init_force(no_hook)?;
} else {
init::execute_init(no_hook)?;
}
0
}
Command::Hook { action } => match action {
HookAction::Install => {
hook_cmd::execute_hook_install()?;
0
}
HookAction::Uninstall => {
hook_cmd::execute_hook_uninstall()?;
0
}
},
Command::Auth { action } => {
match action {
AuthAction::Login {
provider,
api_key,
model,
base_url,
force,
} => {
auth::execute_auth_login(
provider.as_deref(),
api_key.as_deref(),
model.as_deref(),
base_url.as_deref(),
force,
)?;
}
AuthAction::Status => auth::execute_auth_status()?,
AuthAction::Remove => auth::execute_auth_remove()?,
}
0
}
Command::Config { action } => match action {
ConfigAction::Show { global, project } => {
config_cmd::execute_config_show(global, project)?;
0
}
ConfigAction::Set { key, value, global } => {
config_cmd::execute_config_set(&key, &value, global)?;
0
}
ConfigAction::Validate => config_cmd::execute_config_validate()?,
},
Command::Providers => {
providers::execute_providers();
0
}
Command::Completion { shell } => {
completion::execute_completion(&shell)?;
0
}
Command::Mcp => {
mcp::server::run_server()?;
0
}
Command::Findings { action } => commands::findings::execute_findings(&action)?,
Command::Debt {
json,
trend,
since,
branch,
badge,
estimate,
} => {
let opts = debt::DebtOptions {
json,
trend,
since,
branch,
badge,
estimate,
};
debt::execute_debt(&opts)?
}
};
std::process::exit(exit_code);
}
/// Struct to hold review options from CLI.
#[allow(clippy::struct_excessive_bools)]
struct ReviewOpts {
staged: bool,
unpushed: bool,
base: Option<String>,
commit: Option<String>,
diff_file: Option<String>,
unstaged: bool,
max_diff_size: Option<usize>,
stream: bool,
no_auto_chunk: bool,
progress: bool,
quiet: bool,
output_file: Option<String>,
severity: Option<String>,
upload: bool,
repo: Option<String>,
ref_name: Option<String>,
token: Option<String>,
no_cache: bool,
ci: bool,
memory: bool,
learn: bool,
}
/// Struct to hold scan options from CLI.
struct ScanOpts {
path: Option<String>,
include: Vec<String>,
exclude: Vec<String>,
extensions: Vec<String>,
incremental: bool,
focus: Vec<String>,
batch_files: usize,
continue_on_batch_error: bool,
}
/// Handle the `review` subcommand.
async fn cmd_review(globals: &GlobalOptions, opts: ReviewOpts) -> Result<i32> {
let config = loader::load_config(
globals.config.as_deref(),
globals.provider.as_deref(),
globals.model.as_deref(),
globals.base_url.as_deref(),
globals.format.as_deref(),
globals.no_color,
)?;
let llm_config = loader::build_llm_config(&config, globals.api_key.as_deref())?;
// If --upload is set, force SARIF format
let effective_format = if opts.upload {
OutputFormat::Sarif
} else {
resolve_format(globals.format.as_deref(), &config)?
};
let progress_reporter = if opts.progress {
progress::ProgressReporter::new()
} else {
progress::ProgressReporter::disabled()
};
// Emit started event if progress enabled
progress_reporter.started("review", opts.base.as_deref());
let review_opts = review::ReviewOptions {
staged: opts.staged,
unpushed: opts.unpushed,
base: opts.base.clone(),
commit: opts.commit.clone(),
diff_file: opts.diff_file.clone(),
unstaged: opts.unstaged,
max_diff_size: opts.max_diff_size,
stream: opts.stream,
quiet: opts.quiet || opts.progress,
severity: opts.severity.clone(),
no_cache: opts.no_cache,
ci: opts.ci,
auto_chunk: !opts.no_auto_chunk,
};
// When streaming and not quiet/progress, show a simpler message
if opts.stream && !opts.quiet && !opts.progress {
eprintln!(
"{}",
format!(
"⏳ Streaming review from {} ({})…",
llm_config.provider, llm_config.model
)
.dimmed()
);
}
// Uteke memory integration: recall context before review
let mut memory_backend = memory::MemoryBackend::default();
let memory_level = if opts.learn {
memory::MemoryLevel::Learning
} else if opts.memory {
memory::MemoryLevel::Context
} else {
memory::MemoryLevel::None
};
let memory_context = if memory_level != memory::MemoryLevel::None {
memory_backend.detect();
if memory_backend.is_available() {
let project = repo_name_from_git().unwrap_or_else(|| "unknown".to_string());
let memories = memory_backend.recall_context(&project);
memory_backend.build_memory_context(&memories)
} else {
if !opts.quiet {
eprintln!(
"{}",
"⚠ --memory flag set but uteke not found on PATH. Continuing without memory."
.yellow()
);
}
String::new()
}
} else {
String::new()
};
// Execute the review (returns formatted output)
let result = review::execute_review(
&config,
&llm_config,
&review_opts,
effective_format,
&progress_reporter,
if !memory_context.is_empty() {
Some(memory_context.as_str())
} else {
None
},
)
.await?;
// Show memory status if context was used
if !memory_context.is_empty() && !opts.quiet {
eprintln!("{}", "ℹ Review enriched with Uteke memory context.".cyan());
}
// Print the formatted output (to file if --output-file, else stdout)
if let Some(ref path) = opts.output_file {
std::fs::write(path, &result.output)
.with_context(|| format!("failed to write output file: {path}"))?;
if !opts.quiet {
eprintln!("{}", format!("Output written to {path}").dimmed());
}
} else {
print!("{}", result.output);
}
// If --upload, send the SARIF output to GitHub Code Scanning
if opts.upload {
let sarif_content = result.output;
upload_sarif_content(&sarif_content, &opts.repo, &opts.ref_name, &opts.token).await?;
}
// Uteke memory integration: save findings after review
if memory_level == memory::MemoryLevel::Learning && memory_backend.is_available() {
let project = repo_name_from_git().unwrap_or_else(|| "unknown".to_string());
memory_backend.save_findings(
&project,
result.total_issues,
&result.severity_summary,
&result.categories,
);
if !opts.quiet {
eprintln!(
"{}",
format!("💾 Saved {} findings to Uteke memory.", result.total_issues).dimmed()
);
}
}
Ok(result.exit_code)
}
/// Extract repo name from git remote origin URL.
fn repo_name_from_git() -> Option<String> {
let output = std::process::Command::new("git")
.args(["remote", "get-url", "origin"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
// Extract owner/repo from https://github.com/owner/repo.git
let parts: Vec<&str> = url.split('/').collect();
if parts.len() >= 2 {
let repo = parts.last()?.trim_end_matches(".git").to_string();
let owner = parts.get(parts.len() - 2)?;
Some(format!("{}/{}", owner, repo))
} else {
None
}
}
/// Upload a SARIF string to GitHub Code Scanning.
#[allow(clippy::ref_option)]
async fn upload_sarif_content(
sarif_content: &str,
repo: &Option<String>,
ref_name: &Option<String>,
token: &Option<String>,
) -> Result<i32> {
use std::io::Write;
// Write SARIF to a temp file and upload it
let tmp_dir = std::env::temp_dir();
let tmp_path = tmp_dir.join(format!("cora-sarif-upload-{}.json", std::process::id()));
{
let mut file = std::fs::File::create(&tmp_path)?;
file.write_all(sarif_content.as_bytes())?;
}
println!(
"{}",
"\n→ Uploading SARIF to GitHub Code Scanning...".cyan()
);
let upload_opts = upload::UploadOptions {
file: Some(tmp_path.to_string_lossy().to_string()),
repo: repo.clone(),
ref_name: ref_name.clone(),
token: token.clone(),
};
let exit = upload::execute_upload(&upload_opts).await?;
// Clean up temp file
let _ = std::fs::remove_file(&tmp_path);
Ok(exit)
}
/// Handle the `scan` subcommand.
async fn cmd_scan(globals: &GlobalOptions, opts: ScanOpts) -> Result<i32> {
let config = loader::load_config(
globals.config.as_deref(),
globals.provider.as_deref(),
globals.model.as_deref(),
globals.base_url.as_deref(),
globals.format.as_deref(),
globals.no_color,
)?;
let llm_config = loader::build_llm_config(&config, globals.api_key.as_deref())?;
let format = resolve_format(globals.format.as_deref(), &config)?;
let scan_opts = scan::ScanOptions {
path: opts.path,
include: opts.include,
exclude: opts.exclude,
extensions: opts.extensions,
incremental: opts.incremental,
focus: opts.focus,
batch_files: opts.batch_files,
continue_on_batch_error: opts.continue_on_batch_error,
};
scan::execute_scan(&config, &llm_config, &scan_opts, format).await
}
/// Resolve the output format: CLI flag > config > default.
fn resolve_format(
cli_format: Option<&str>,
config: &crate::config::schema::Config,
) -> Result<OutputFormat> {
let fmt_str = cli_format.map_or_else(
|| config.output.format.clone(),
std::string::ToString::to_string,
);
OutputFormat::from_str_loose(&fmt_str)
}