-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathmain.go
More file actions
1050 lines (955 loc) · 32.8 KB
/
Copy pathmain.go
File metadata and controls
1050 lines (955 loc) · 32.8 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"codemap/cmd"
"codemap/config"
"codemap/handoff"
"codemap/internal/buildinfo"
"codemap/internal/projectpath"
"codemap/limits"
"codemap/render"
"codemap/scanner"
"codemap/watch"
)
type watchProcess interface {
Start() error
Stop()
FileCount() int
GetEvents(limit int) []watch.Event
}
var (
newWatchProcess = func(root string, verbose bool) (watchProcess, error) {
return watch.NewDaemon(root, verbose)
}
watchIsRunning = watch.IsRunning
stopWatchDaemon = watch.Stop
writeWatchPID = watch.WritePID
removeWatchPID = watch.RemovePID
executablePath = os.Executable
execCommand = exec.Command
notifySignals = signal.Notify
terminalChecker = isTerminal
)
func main() {
args, err := applyGlobalRootOptions(os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(2)
}
os.Args = append([]string{os.Args[0]}, args...)
if len(os.Args) >= 2 && (os.Args[1] == "version" || os.Args[1] == "--version" || os.Args[1] == "-version") {
fmt.Printf("codemap %s\n", buildinfo.Current())
return
}
// Handle "watch" subcommand before flag parsing
if len(os.Args) >= 2 && os.Args[1] == "watch" {
subCmd := "status"
if len(os.Args) >= 3 {
subCmd = os.Args[2]
}
root, _ := os.Getwd()
if len(os.Args) >= 4 {
root = os.Args[3]
}
runWatchSubcommand(subCmd, root)
return
}
// Handle "hook" subcommand before flag parsing
if len(os.Args) >= 2 && os.Args[1] == "hook" {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "Usage: codemap hook <hookname>")
fmt.Fprintln(os.Stderr, "Available hooks: session-start, pre-edit, post-edit, prompt-submit, pre-compact, session-stop")
os.Exit(1)
}
hookName := os.Args[2]
root, _ := os.Getwd()
hookAgent := "claude"
hookIntegration := ""
for _, arg := range os.Args[3:] {
switch {
case arg == "--agent=codex":
hookAgent = "codex"
_ = os.Setenv("CODEX", "1")
case strings.HasPrefix(arg, "--agent="):
fmt.Fprintf(os.Stderr, "Unsupported hook agent: %s\n", strings.TrimPrefix(arg, "--agent="))
os.Exit(2)
case strings.HasPrefix(arg, "--integration="):
hookIntegration = strings.TrimPrefix(arg, "--integration=")
default:
root = arg
}
}
if hookIntegration != "" {
valid := (hookIntegration == "claude-setup" && hookAgent == "claude") ||
(hookIntegration == "codex-setup" && hookAgent == "codex")
if !valid {
fmt.Fprintf(os.Stderr, "Unsupported hook integration: %s for agent %s\n", hookIntegration, hookAgent)
os.Exit(2)
}
}
if err := cmd.RunHookWithTimeout(hookName, root, cmd.HookTimeoutFromEnv(os.Getenv)); err != nil {
var timeoutErr *cmd.HookTimeoutError
if errors.As(err, &timeoutErr) {
fmt.Fprintf(os.Stderr, "Hook warning: %v\n", timeoutErr)
fmt.Fprintln(os.Stderr, "Continuing without hook output. Set CODEMAP_HOOK_TIMEOUT=0 to disable timeout.")
return
}
fmt.Fprintf(os.Stderr, "Hook error: %v\n", err)
os.Exit(1)
}
return
}
// Handle "config" subcommand before default analysis flag parsing.
if len(os.Args) >= 2 && os.Args[1] == "config" {
subCmd := ""
if len(os.Args) >= 3 {
subCmd = os.Args[2]
}
root, _ := os.Getwd()
if len(os.Args) >= 4 {
root = os.Args[3]
}
cmd.RunConfig(subCmd, root)
return
}
// Handle "setup" subcommand before default analysis flag parsing.
if len(os.Args) >= 2 && os.Args[1] == "setup" {
root, _ := os.Getwd()
if code := cmd.RunSetup(os.Args[2:], root); code != 0 {
os.Exit(code)
}
return
}
if len(os.Args) >= 2 && os.Args[1] == "doctor" {
root, _ := os.Getwd()
if code := cmd.RunDoctor(os.Args[2:], root); code != 0 {
os.Exit(code)
}
return
}
// Handle "mcp" subcommand before default analysis flag parsing.
if len(os.Args) >= 2 && os.Args[1] == "mcp" {
if code := cmd.RunMCP(os.Args[2:]); code != 0 {
os.Exit(code)
}
return
}
// Handle "skill" subcommand before default analysis flag parsing.
if len(os.Args) >= 2 && os.Args[1] == "skill" {
root, _ := os.Getwd()
cmd.RunSkill(os.Args[2:], root)
return
}
// Handle "plugin" subcommand before global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "plugin" {
cmd.RunPlugin(os.Args[2:])
return
}
// Handle "context" subcommand before default analysis flag parsing.
if len(os.Args) >= 2 && os.Args[1] == "context" {
root, _ := os.Getwd()
cmd.RunContext(os.Args[2:], root)
return
}
// Handle "serve" subcommand before global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "serve" {
root, _ := os.Getwd()
cmd.RunServe(os.Args[2:], root)
return
}
// Handle "handoff" subcommand before global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "handoff" {
runHandoffSubcommand(os.Args[2:])
return
}
// Handle "blast-radius" subcommand before global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "blast-radius" {
runBlastRadiusSubcommand(os.Args[2:])
return
}
skylineMode := flag.Bool("skyline", false, "Enable skyline visualization mode")
animateMode := flag.Bool("animate", false, "Enable animation (use with --skyline)")
depsMode := flag.Bool("deps", false, "Enable dependency graph mode (function/import analysis)")
diffMode := flag.Bool("diff", false, "Only show files changed vs main (or use --ref to specify branch)")
diffRef := flag.String("ref", "main", "Branch/ref to compare against (use with --diff)")
depthLimit := flag.Int("depth", 0, "Limit tree depth (0 = unlimited)")
onlyExts := flag.String("only", "", "Only show files with these extensions (comma-separated, e.g., 'swift,go')")
excludePatterns := flag.String("exclude", "", "Exclude files matching patterns (comma-separated, e.g., '.xcassets,Fonts')")
jsonMode := flag.Bool("json", false, "Output JSON (for Python renderer compatibility)")
debugMode := flag.Bool("debug", false, "Show debug info (gitignore loading, paths, etc.)")
watchMode := flag.Bool("watch", false, "Live file watcher daemon (experimental)")
stdinMode := flag.Bool("stdin", false, "Read file manifest from stdin (use with --deps)")
importersMode := flag.String("importers", "", "Check file impact: who imports it, is it a hub?")
helpMode := flag.Bool("help", false, "Show help")
flag.BoolVar(helpMode, "h", false, "Show help (shorthand)")
// Short flag aliases
flag.IntVar(depthLimit, "d", 0, "Limit tree depth (shorthand)")
flag.Parse()
if *helpMode {
fmt.Println("codemap - Generate a brain map of your codebase for LLM context")
fmt.Println()
fmt.Println("Usage: codemap [options] [path]")
fmt.Println()
fmt.Println("Options:")
fmt.Println(" --help Show this help message")
fmt.Println(" --version Show build version")
fmt.Println(" -C, --project-root <repo> Operate on code in <repo>.")
fmt.Println(" --setup-root <repo> Reuse state from <repo>/.codemap.")
fmt.Println(" --skyline City skyline visualization")
fmt.Println(" --animate Animated skyline (use with --skyline)")
fmt.Println(" --deps Dependency flow map (functions & imports)")
fmt.Println(" --diff Only show files changed vs main")
fmt.Println(" --ref <branch> Branch to compare against (default: main)")
fmt.Println(" --depth, -d <n> Limit tree depth (0 = unlimited)")
fmt.Println(" --only <exts> Only show files with these extensions (e.g., 'swift,go')")
fmt.Println(" --exclude <patterns> Exclude paths matching patterns (e.g., '.xcassets,Fonts')")
fmt.Println(" --stdin Read JSON file manifest from stdin (use with --deps)")
fmt.Println(" --importers <file> Check file impact (who imports it, hub status)")
fmt.Println(" --json Output machine-readable JSON")
fmt.Println(" --debug Show scanner and path diagnostics")
fmt.Println(" --watch Run the live file watcher daemon")
fmt.Println()
fmt.Println("Examples:")
fmt.Println(" codemap . # Basic tree view")
fmt.Println(" codemap --skyline . # Skyline visualization")
fmt.Println(" codemap --skyline --animate # Animated skyline")
fmt.Println(" codemap --deps /path/to/proj # Dependency flow map")
fmt.Println(" codemap --diff # Files changed vs main")
fmt.Println(" codemap --diff --ref develop # Files changed vs develop")
fmt.Println(" codemap --depth 3 . # Show only 3 levels deep")
fmt.Println(" codemap --only swift . # Just Swift files")
fmt.Println(" codemap --exclude .xcassets,Fonts,.png # Hide assets")
fmt.Println(" codemap --importers scanner/types.go # Check file impact")
fmt.Println(" echo '{...}' | codemap --deps --stdin # Deps from file manifest")
fmt.Println()
fmt.Println("Remote repos (clones temporarily):")
fmt.Println(" codemap github.com/user/repo # GitHub repo")
fmt.Println(" codemap https://github.com/user/repo")
fmt.Println(" codemap gitlab.com/user/repo # GitLab repo")
fmt.Println()
fmt.Println("Note: Flags must come before the path/URL.")
fmt.Println()
fmt.Println("Hooks (for Claude Code and Codex integration):")
fmt.Println(" codemap hook session-start # Show project context")
fmt.Println(" codemap hook pre-edit # Check before editing (stdin)")
fmt.Println(" codemap hook post-edit # Check after editing (stdin)")
fmt.Println(" codemap hook prompt-submit # Parse user prompt (stdin)")
fmt.Println(" codemap hook pre-compact # Save state before compact")
fmt.Println(" codemap hook session-stop # Session summary")
fmt.Println(" codemap handoff [path] # Build handoff artifact for agent switching")
fmt.Println(" codemap blast-radius [path] # Compact bounded blast-radius bundle")
fmt.Println()
fmt.Println("Project config:")
fmt.Println(" codemap config init # Create .codemap/config.json (auto-detects extensions)")
fmt.Println(" codemap config show # Show current project config")
fmt.Println()
fmt.Println("Plugin management:")
fmt.Println(" codemap plugin install # Install/update and activate the Codemap plugin")
fmt.Println(" codemap doctor # Check Codex or Claude integration prerequisites")
fmt.Println()
fmt.Println("MCP server:")
fmt.Println(" codemap mcp # Run Codemap MCP server on stdio")
fmt.Println()
fmt.Println("More subcommands:")
fmt.Println(" codemap watch status|start|stop # Manage the background watch daemon")
fmt.Println(" codemap skill list|show <name> # List or show bundled agent skills")
fmt.Println(" codemap context # Print machine-readable project context JSON")
fmt.Println(" codemap serve # Serve project intelligence over HTTP")
fmt.Println(" codemap version # Show build version")
fmt.Println()
fmt.Println("Recommended onboarding:")
fmt.Println(" codemap setup # Configure project and agent hooks")
fmt.Println(" codemap setup --global # Write hooks to ~/.claude/settings.json")
os.Exit(0)
}
root := flag.Arg(0)
if root == "" {
root = "."
}
// Handle GitHub URLs - clone to temp dir (but prefer local paths if they exist)
var tempDir string
var remoteURL, repoName string
_, localPathErr := os.Stat(root)
if isGitHubURL(root) && localPathErr != nil {
// Only clone if it looks like a URL AND doesn't exist locally
// This preserves ~/go/src/github.com/user/repo style paths
remoteURL = root
repoName = extractRepoName(root)
var err error
tempDir, err = cloneRepo(root, repoName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error cloning repo: %v\n", err)
os.Exit(1)
}
defer os.RemoveAll(tempDir)
root = tempDir
}
absRoot, err := filepath.Abs(root)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting absolute path: %v\n", err)
os.Exit(1)
}
// A bare word that isn't a directory is almost always a typo'd subcommand
// ("codemap drift"), so fail with directions instead of a path-resolution error.
if _, statErr := os.Stat(root); os.IsNotExist(statErr) {
fmt.Fprintf(os.Stderr, "Error: path %q does not exist.\n", root)
fmt.Fprintln(os.Stderr, "If you meant a subcommand, run 'codemap --help' for the full list.")
os.Exit(1)
}
if _, err := cmd.ValidateProjectPath(absRoot); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Initialize gitignore cache (supports nested .gitignore files)
gitCache := scanner.NewGitIgnoreCache(root)
// Parse --only and --exclude flags
var only, exclude []string
if *onlyExts != "" {
for _, ext := range strings.Split(*onlyExts, ",") {
if trimmed := strings.TrimSpace(ext); trimmed != "" {
only = append(only, trimmed)
}
}
}
if *excludePatterns != "" {
for _, pattern := range strings.Split(*excludePatterns, ",") {
if trimmed := strings.TrimSpace(pattern); trimmed != "" {
exclude = append(exclude, trimmed)
}
}
}
// Load project config (CLI flags take precedence)
projCfg := config.Load(absRoot)
if len(only) == 0 && len(projCfg.Only) > 0 {
only = projCfg.Only
}
if len(exclude) == 0 && len(projCfg.Exclude) > 0 {
exclude = projCfg.Exclude
}
if *depthLimit == 0 && projCfg.Depth > 0 {
*depthLimit = projCfg.Depth
}
filters := scanner.Filters{Only: only, Exclude: exclude}
if *debugMode {
fmt.Fprintf(os.Stderr, "[debug] Root path: %s\n", root)
fmt.Fprintf(os.Stderr, "[debug] Absolute path: %s\n", absRoot)
fmt.Fprintf(os.Stderr, "[debug] GitIgnore cache initialized (supports nested .gitignore files)\n")
}
// Watch mode - start daemon
if *watchMode {
resolvedRoot, _, err := cmd.ResolveNearestGitRoot(absRoot)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting watch root: %v\n", err)
os.Exit(1)
}
runWatchMode(resolvedRoot, *debugMode)
return
}
// Importers mode - check file impact
if *importersMode != "" {
runImportersMode(absRoot, *importersMode, *jsonMode, filters)
return
}
// Get changed files if --diff is specified
var diffInfo *scanner.DiffInfo
if *diffMode {
var err error
diffInfo, err = scanner.GitDiffInfo(context.Background(), absRoot, *diffRef)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting git diff: %v\n", err)
fmt.Fprintf(os.Stderr, "Make sure '%s' is a valid branch/ref\n", *diffRef)
os.Exit(1)
}
if len(diffInfo.Changed) == 0 {
fmt.Printf("No files changed vs %s\n", *diffRef)
os.Exit(0)
}
}
// Handle --deps mode separately
if *depsMode {
var changedFiles map[string]bool
if diffInfo != nil {
changedFiles = diffInfo.Changed
}
runDepsMode(absRoot, root, *jsonMode, *diffRef, changedFiles, *stdinMode, filters)
return
}
mode := "tree"
if *skylineMode {
mode = "skyline"
}
// Scan files
files, err := scanner.ScanFiles(context.Background(), root, gitCache, only, exclude)
if err != nil {
fmt.Fprintf(os.Stderr, "Error walking tree: %v\n", err)
os.Exit(1)
}
// Filter to changed files if --diff specified (with diff info annotations)
var impact []scanner.ImpactInfo
var activeDiffRef string
if diffInfo != nil {
files = scanner.FilterToChangedWithInfo(files, diffInfo)
impact, err = scanner.AnalyzeImpact(context.Background(), absRoot, files)
if err != nil {
fmt.Fprintf(os.Stderr, "Error analyzing impact: %v\n", err)
os.Exit(1)
}
activeDiffRef = *diffRef
}
project := scanner.Project{
Root: absRoot,
Name: repoName,
RemoteURL: remoteURL,
Mode: mode,
Animate: *animateMode,
Files: files,
DiffRef: activeDiffRef,
Impact: impact,
Depth: *depthLimit,
Only: only,
Exclude: exclude,
}
// Render or output JSON
if *jsonMode {
json.NewEncoder(os.Stdout).Encode(project)
} else if *skylineMode {
render.Skyline(os.Stdout, project, *animateMode)
} else {
render.Tree(os.Stdout, project)
}
}
func applyGlobalRootOptions(args []string) ([]string, error) {
opts, remaining, err := cmd.ParseGlobalRootOptions(args)
if err != nil {
return nil, err
}
if !opts.Active() {
launchDir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("get working directory: %w", err)
}
if _, err := projectpath.Select(launchDir); err != nil {
return nil, err
}
return remaining, nil
}
launchDir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("get working directory: %w", err)
}
roots, err := cmd.ResolveGlobalRoots(opts, launchDir)
if err != nil {
return nil, err
}
// Canonicalize the stored setup root so projectpath and daemon args agree
// with the resolved project root (e.g. macOS /var -> /private/var).
if canonical, err := filepath.EvalSymlinks(roots.Setup); err == nil {
roots.Setup = canonical
}
if err := os.Chdir(roots.Project); err != nil {
return nil, fmt.Errorf("change to project root %q: %w", roots.Project, err)
}
if opts.SetupRoot != "" {
projectpath.SetSetupRoot(roots.Setup)
} else {
projectpath.ResetSetupRoot()
}
return remaining, nil
}
// stdinManifest is the JSON format accepted by --stdin.
type stdinManifest struct {
Root string `json:"root"`
Files []struct {
Path string `json:"path"`
Content string `json:"content"`
} `json:"files"`
}
// safeStdinManifestPath validates a --stdin manifest file path and returns a
// cleaned, slash-normalized path that stays inside the manifest root. Absolute
// paths and any ".." traversal are rejected so a hostile manifest cannot write
// outside the private temp directory.
func safeStdinManifestPath(rel string) (string, bool) {
if rel == "" || filepath.IsAbs(rel) {
return "", false
}
cleaned := filepath.Clean(filepath.FromSlash(rel))
if cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(filepath.Separator)) || filepath.IsAbs(cleaned) {
return "", false
}
return cleaned, true
}
func runDepsMode(absRoot, root string, jsonMode bool, diffRef string, changedFiles map[string]bool, stdinMode bool, filters scanner.Filters) {
var outcome scanner.ScanOutcome
var externalDeps map[string][]string
var graph *scanner.FileGraph
var err error
if stdinMode {
outcome, externalDeps, graph, err = runDepsFromStdin(filters)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading stdin manifest: %v\n", err)
os.Exit(1)
}
if externalDeps == nil {
externalDeps = make(map[string][]string)
}
} else {
outcome, err = scanForDepsOutcomeWithHint(root, filters)
if err != nil {
if errors.Is(err, scanner.ErrAstGrepNotFound) {
printAstGrepInstallHint(os.Stderr, err)
} else {
fmt.Fprintf(os.Stderr, "Error scanning dependencies: %v\n", err)
}
os.Exit(1)
}
externalDeps, err = scanner.ReadExternalDeps(context.Background(), absRoot, 0)
if err != nil {
externalDeps = make(map[string][]string)
}
// Build the graph from the scan outcome. The graph is best-effort: a
// fail-closed scan or a non-fatal graph build problem must not turn
// --deps into a hard error. Coverage falls back to the scan outcome's
// own sources when no graph is available.
if built, graphErr := scanner.BuildFileGraphFromOutcome(context.Background(), absRoot, outcome, filters); graphErr == nil {
graph = built
}
}
// Filter to changed files if --diff specified
if changedFiles != nil {
outcome.Analyses = scanner.FilterAnalysisToChanged(outcome.Analyses, changedFiles)
}
// Derive coverage from the graph's provenance when one was built; otherwise
// fall back to the scan outcome's sources (nil graph = empty stdin manifest
// or best-effort graph failure).
coverageSources := outcome.Sources
if graph != nil {
coverageSources = graph.Coverage.Sources
}
depsProject := scanner.NewDepsProjectWithCoverage(absRoot, outcome.Analyses, externalDeps, diffRef, scanner.CoverageFromSources(coverageSources))
// Render or output JSON
if jsonMode {
json.NewEncoder(os.Stdout).Encode(depsProject)
} else {
render.Depgraph(context.Background(), os.Stdout, depsProject)
}
}
// scanForDepsOutcomeWithHint wraps scanner.ScanForDeps (extracted for testability).
func scanForDepsOutcomeWithHint(root string, filters scanner.Filters) (scanner.ScanOutcome, error) {
return scanner.ScanForDeps(context.Background(), root, filters)
}
// runDepsFromStdin reads a JSON manifest from stdin, writes files to a temp
// directory, runs ast-grep on it, and returns the results with paths matching
// the original manifest.
func runDepsFromStdin(filters scanner.Filters) (scanner.ScanOutcome, map[string][]string, *scanner.FileGraph, error) {
var manifest stdinManifest
if err := json.NewDecoder(os.Stdin).Decode(&manifest); err != nil {
return scanner.ScanOutcome{}, nil, nil, fmt.Errorf("invalid JSON: %w", err)
}
if len(manifest.Files) == 0 {
// Return a valid empty graph/outcome so callers never dereference a nil
// graph when deriving coverage; an empty manifest is an empty answer.
return scanner.ScanOutcome{}, nil, &scanner.FileGraph{}, nil
}
// Create temp directory and write manifest files
tempDir, err := os.MkdirTemp("", "codemap-stdin-*")
if err != nil {
return scanner.ScanOutcome{}, nil, nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer os.RemoveAll(tempDir)
for _, f := range manifest.Files {
rel, ok := safeStdinManifestPath(f.Path)
if !ok {
return scanner.ScanOutcome{}, nil, nil, fmt.Errorf("invalid manifest path %q: must be a relative path inside the manifest root", f.Path)
}
dest := filepath.Join(tempDir, rel)
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return scanner.ScanOutcome{}, nil, nil, fmt.Errorf("mkdir %s: %w", filepath.Dir(dest), err)
}
if err := os.WriteFile(dest, []byte(f.Content), 0644); err != nil {
return scanner.ScanOutcome{}, nil, nil, fmt.Errorf("write %s: %w", f.Path, err)
}
}
// Run ast-grep on temp directory
outcome, err := scanner.ScanForDeps(context.Background(), tempDir, filters)
if err != nil {
return scanner.ScanOutcome{}, nil, nil, err
}
// Read external deps from temp directory (manifest may include go.mod etc.)
externalDeps, err := scanner.ReadExternalDeps(context.Background(), tempDir, 0)
if err != nil {
return scanner.ScanOutcome{}, nil, nil, err
}
// Build the graph in the temp directory so coverage provenance is honest.
graph, err := scanner.BuildFileGraphFromOutcome(context.Background(), tempDir, outcome, filters)
if err != nil {
return scanner.ScanOutcome{}, nil, nil, err
}
return outcome, externalDeps, graph, nil
}
// FileAnalysis is a type alias for use in main package.
type FileAnalysis = scanner.FileAnalysis
func runWatchMode(root string, verbose bool) {
fmt.Println("codemap watch - Live code graph daemon")
fmt.Println()
daemon, err := newWatchProcess(root, verbose)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := daemon.Start(); err != nil {
fmt.Fprintf(os.Stderr, "Error starting watch: %v\n", err)
os.Exit(1)
}
fmt.Printf("Watching: %s\n", root)
fmt.Printf("Files tracked: %d\n", daemon.FileCount())
fmt.Println("Event log: .codemap/events.log")
fmt.Println()
fmt.Println("Press Ctrl+C to stop")
fmt.Println()
// Wait for interrupt
sigChan := make(chan os.Signal, 1)
notifySignals(sigChan, os.Interrupt, syscall.SIGTERM)
<-sigChan
fmt.Println()
fmt.Println("Shutting down...")
daemon.Stop()
// Print session summary
events := daemon.GetEvents(0)
fmt.Println()
fmt.Println("Session summary:")
fmt.Printf(" Files tracked: %d\n", daemon.FileCount())
fmt.Printf(" Events logged: %d\n", len(events))
}
func buildImportersReport(root, file string, filters scanner.Filters) (scanner.ImportersReport, error) {
fg, err := scanner.BuildFileGraph(context.Background(), root, filters)
if err != nil {
return scanner.ImportersReport{}, err
}
return buildImportersReportFromGraph(root, file, fg), nil
}
func runImportersMode(root, file string, jsonMode bool, filters scanner.Filters) {
report, err := buildImportersReport(root, file, filters)
if err != nil {
fmt.Fprintf(os.Stderr, "Error building file graph: %v\n", err)
os.Exit(1)
}
if jsonMode {
_ = json.NewEncoder(os.Stdout).Encode(report)
return
}
renderImportersReportCLI(os.Stdout, report)
}
func runWatchSubcommand(subCmd, root string) {
absRoot, _, err := cmd.ResolveNearestGitRoot(root)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
absRoot, err = cmd.ValidateProjectPath(absRoot)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Canonicalize so the daemon identity and path comparisons agree (e.g.
// macOS /var -> /private/var).
if canonical, err := filepath.EvalSymlinks(absRoot); err == nil {
absRoot = canonical
}
switch subCmd {
case "start":
if watchIsRunning(absRoot) {
fmt.Println("Watch daemon already running")
return
}
// Fork a background daemon
exe, err := executablePath()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
args := projectpath.PrependSetupRootArgs("watch", "daemon", absRoot)
cmd := execCommand(exe, args...)
cmd.Stdout = nil
cmd.Stderr = nil
cmd.Stdin = nil
// Detach from parent process group (Unix only)
setSysProcAttr(cmd)
if err := cmd.Start(); err != nil {
fmt.Fprintf(os.Stderr, "Error starting daemon: %v\n", err)
os.Exit(1)
}
fmt.Printf("Watch daemon started (pid %d)\n", cmd.Process.Pid)
case "daemon":
// Internal: run as the actual daemon process
runDaemon(absRoot)
case "stop":
if !watchIsRunning(absRoot) {
fmt.Println("Watch daemon not running")
return
}
if err := stopWatchDaemon(absRoot); err != nil {
if errors.Is(err, watch.ErrForeignDaemonPID) {
fmt.Println("Watch daemon not running (cleared stale PID file)")
return
}
fmt.Fprintf(os.Stderr, "Error stopping daemon: %v\n", err)
os.Exit(1)
}
fmt.Println("Watch daemon stopped")
case "status":
if watchIsRunning(absRoot) {
state := watch.ReadState(absRoot)
if state != nil {
fmt.Printf("Watch daemon running\n")
fmt.Printf(" Files: %d\n", state.FileCount)
fmt.Printf(" Hubs: %d\n", len(state.Hubs))
fmt.Printf(" Updated: %s\n", state.UpdatedAt.Format("15:04:05"))
} else {
fmt.Println("Watch daemon running (no state)")
}
} else {
fmt.Println("Watch daemon not running")
}
default:
fmt.Fprintf(os.Stderr, "Unknown watch command: %s\n", subCmd)
fmt.Fprintln(os.Stderr, "Usage: codemap watch [start|stop|status]")
os.Exit(1)
}
}
func runHandoffSubcommand(args []string) {
fs := flag.NewFlagSet("handoff", flag.ExitOnError)
since := fs.String("since", "6h", "Look back window for recent events (Go duration, e.g. 2h, 30m)")
baseRef := fs.String("ref", handoff.DefaultBaseRef, "Git base ref for diff (default: main)")
jsonMode := fs.Bool("json", false, "Output raw handoff JSON")
latest := fs.Bool("latest", false, "Read the latest saved handoff instead of generating a new one")
prefixOnly := fs.Bool("prefix", false, "Render only the stable prefix layer")
deltaOnly := fs.Bool("delta", false, "Render only the recent delta layer")
detailPath := fs.String("detail", "", "Load full detail for a changed file path from handoff delta")
noSave := fs.Bool("no-save", false, "Do not persist generated handoff artifact")
if err := fs.Parse(args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if *prefixOnly && *deltaOnly {
fmt.Fprintln(os.Stderr, "Error: --prefix and --delta are mutually exclusive")
os.Exit(1)
}
root := "."
if fs.NArg() > 0 {
root = fs.Arg(0)
}
absRoot, err := filepath.Abs(root)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if _, err := cmd.ValidateProjectPath(absRoot); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
var artifact *handoff.Artifact
if *latest {
artifact, err = handoff.ReadLatest(absRoot)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading handoff: %v\n", err)
os.Exit(1)
}
if artifact == nil {
fmt.Printf("No handoff artifact found at %s\n", handoff.LatestPath(absRoot))
return
}
} else {
sinceDuration, err := time.ParseDuration(*since)
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid --since duration: %v\n", err)
os.Exit(1)
}
if sinceDuration <= 0 {
fmt.Fprintf(os.Stderr, "Invalid --since duration: must be > 0\n")
os.Exit(1)
}
artifact, err = handoff.Build(absRoot, handoff.BuildOptions{
BaseRef: *baseRef,
Since: sinceDuration,
})
if err != nil {
fmt.Fprintf(os.Stderr, "Error building handoff: %v\n", err)
os.Exit(1)
}
if !*noSave {
if err := handoff.WriteLatest(absRoot, artifact); err != nil {
fmt.Fprintf(os.Stderr, "Error saving handoff: %v\n", err)
os.Exit(1)
}
}
}
if *detailPath != "" {
detail, err := handoff.BuildFileDetail(absRoot, artifact, *detailPath, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading handoff detail: %v\n", err)
os.Exit(1)
}
if *jsonMode {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(detail); err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}
return
}
out := handoff.RenderFileDetailMarkdown(detail)
out = limits.TruncateAtLineBoundary(out, limits.MaxHandoffDetailBytes, "\n\n... (handoff detail truncated)\n")
fmt.Print(out)
return
}
if *jsonMode {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
switch {
case *prefixOnly:
if err := enc.Encode(artifact.Prefix); err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}
case *deltaOnly:
if err := enc.Encode(artifact.Delta); err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}
default:
if err := enc.Encode(artifact); err != nil {
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err)
os.Exit(1)
}
}
return
}
var out string
switch {
case *prefixOnly:
out = handoff.RenderPrefixMarkdown(artifact.Prefix)
case *deltaOnly:
out = handoff.RenderDeltaMarkdown(artifact.Delta)
default:
out = handoff.RenderMarkdown(artifact)
}
out = limits.TruncateAtLineBoundary(out, limits.MaxHandoffMarkdownBytes, "\n\n... (handoff output truncated)\n")
fmt.Print(out)
if !*latest && !*noSave {
fmt.Println()
fmt.Printf("Saved: %s\n", handoff.LatestPath(absRoot))
fmt.Printf("Prefix: %s\n", handoff.PrefixPath(absRoot))
fmt.Printf("Delta: %s\n", handoff.DeltaPath(absRoot))
fmt.Printf("Metrics: %s\n", handoff.MetricsPath(absRoot))
}
}
func runDaemon(root string) {
daemon, err := newWatchProcess(root, false)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := daemon.Start(); err != nil {
fmt.Fprintf(os.Stderr, "Error starting watch: %v\n", err)
os.Exit(1)
}
// Write PID file
writeWatchPID(root)
// Wait for stop signal (SIGTERM or state file removal)
sigChan := make(chan os.Signal, 1)
notifySignals(sigChan, syscall.SIGTERM, syscall.SIGINT)
<-sigChan
daemon.Stop()
removeWatchPID(root)
}
// isGitHubURL checks if the input looks like a GitHub repo URL
func isGitHubURL(s string) bool {
s = strings.ToLower(s)
return strings.HasPrefix(s, "github.com/") ||
strings.HasPrefix(s, "https://github.com/") ||
strings.HasPrefix(s, "http://github.com/") ||
strings.HasPrefix(s, "gitlab.com/") ||
strings.HasPrefix(s, "https://gitlab.com/")
}
// cloneRepo clones a git repo to a temp directory (shallow clone)
func cloneRepo(url string, repoName string) (string, error) {
// Normalize URL
if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
url = "https://" + url
}
// Create temp dir
tempDir, err := os.MkdirTemp("", "codemap-")
if err != nil {
return "", fmt.Errorf("failed to create temp dir: %w", err)
}
// Only animate if stderr is a real terminal
isTTY := terminalChecker(os.Stderr)
var done chan bool
if isTTY {
anim := render.NewCloneAnimation(os.Stderr, repoName)
done = make(chan bool)
go func() {
progress := 0
for {
select {
case <-done:
// Clear the line completely when done
fmt.Fprint(os.Stderr, "\r\033[K")
return
default: