-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathmain.go
More file actions
870 lines (783 loc) · 25.3 KB
/
main.go
File metadata and controls
870 lines (783 loc) · 25.3 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
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/limits"
codemapmcp "codemap/mcp"
"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() {
// 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()
if len(os.Args) >= 4 {
root = os.Args[3]
}
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 global 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 global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "setup" {
root, _ := os.Getwd()
cmd.RunSetup(os.Args[2:], root)
return
}
// Handle "mcp" subcommand before global flag parsing
if len(os.Args) >= 2 && os.Args[1] == "mcp" {
if err := codemapmcp.Run(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "MCP server error: %v\n", err)
os.Exit(1)
}
return
}
// Handle "skill" subcommand before global 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 global 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")
// 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(" --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()
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 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 the Codemap plugin into your home plugin marketplace")
fmt.Println()
fmt.Println("MCP server:")
fmt.Println(" codemap mcp # Run Codemap MCP server on stdio")
fmt.Println()
fmt.Println("Recommended onboarding:")
fmt.Println(" codemap setup # Configure project config + Claude 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)
}
// 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
}
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 {
runWatchMode(absRoot, *debugMode)
return
}
// Importers mode - check file impact
if *importersMode != "" {
runImportersMode(absRoot, *importersMode, *jsonMode)
return
}
// Get changed files if --diff is specified
var diffInfo *scanner.DiffInfo
if *diffMode {
var err error
diffInfo, err = scanner.GitDiffInfo(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)
return
}
mode := "tree"
if *skylineMode {
mode = "skyline"
}
// Scan files
files, err := scanner.ScanFiles(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 = scanner.AnalyzeImpact(absRoot, files)
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)
}
}
// 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"`
}
func runDepsMode(absRoot, root string, jsonMode bool, diffRef string, changedFiles map[string]bool, stdinMode bool) {
var analyses []FileAnalysis
var externalDeps map[string][]string
var err error
if stdinMode {
analyses, externalDeps, err = runDepsFromStdin()
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading stdin manifest: %v\n", err)
os.Exit(1)
}
// Use the manifest root as absRoot if provided
if externalDeps == nil {
externalDeps = make(map[string][]string)
}
} else {
analyses, err = scanForDepsWithHint(root)
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 = scanner.ReadExternalDeps(absRoot)
}
// Filter to changed files if --diff specified
if changedFiles != nil {
analyses = scanner.FilterAnalysisToChanged(analyses, changedFiles)
}
depsProject := scanner.DepsProject{
Root: absRoot,
Mode: "deps",
Files: analyses,
ExternalDeps: externalDeps,
DiffRef: diffRef,
}
// Render or output JSON
if jsonMode {
json.NewEncoder(os.Stdout).Encode(depsProject)
} else {
render.Depgraph(os.Stdout, depsProject)
}
}
// scanForDepsWithHint wraps scanner.ScanForDeps (extracted for testability).
func scanForDepsWithHint(root string) ([]FileAnalysis, error) {
return scanner.ScanForDeps(root)
}
// 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() ([]FileAnalysis, map[string][]string, error) {
var manifest stdinManifest
if err := json.NewDecoder(os.Stdin).Decode(&manifest); err != nil {
return nil, nil, fmt.Errorf("invalid JSON: %w", err)
}
if len(manifest.Files) == 0 {
return nil, nil, nil
}
// Create temp directory and write manifest files
tempDir, err := os.MkdirTemp("", "codemap-stdin-*")
if err != nil {
return nil, nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer os.RemoveAll(tempDir)
for _, f := range manifest.Files {
dest := filepath.Join(tempDir, f.Path)
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return nil, nil, fmt.Errorf("mkdir %s: %w", filepath.Dir(dest), err)
}
if err := os.WriteFile(dest, []byte(f.Content), 0644); err != nil {
return nil, nil, fmt.Errorf("write %s: %w", f.Path, err)
}
}
// Run ast-grep on temp directory
analyses, err := scanner.ScanForDeps(tempDir)
if err != nil {
return nil, nil, err
}
// Read external deps from temp directory (manifest may include go.mod etc.)
externalDeps := scanner.ReadExternalDeps(tempDir)
return analyses, externalDeps, 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) (scanner.ImportersReport, error) {
fg, err := scanner.BuildFileGraph(root)
if err != nil {
return scanner.ImportersReport{}, err
}
return buildImportersReportFromGraph(root, file, fg), nil
}
func runImportersMode(root, file string, jsonMode bool) {
report, err := buildImportersReport(root, file)
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
}
renderImportersReport(os.Stdout, report)
}
func runWatchSubcommand(subCmd, root string) {
absRoot, err := filepath.Abs(root)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
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)
}
cmd := execCommand(exe, "watch", "daemon", absRoot)
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 {
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)
}
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:
anim.Render(progress)
if progress < 95 {
progress++
}
time.Sleep(50 * time.Millisecond)
}
}
}()
}
// Shallow clone (quiet)
cmd := execCommand("git", "clone", "--depth", "1", "--single-branch", "-q", url, tempDir)
cloneErr := cmd.Run()
if isTTY {
done <- true
time.Sleep(50 * time.Millisecond) // Let animation finish
}
if cloneErr != nil {
os.RemoveAll(tempDir)
return "", fmt.Errorf("git clone failed: %w", cloneErr)
}
return tempDir, nil
}
// isTerminal checks if a file is a terminal
func isTerminal(f *os.File) bool {
stat, err := f.Stat()
if err != nil {
return false
}
return (stat.Mode() & os.ModeCharDevice) != 0
}
// extractRepoName extracts "owner/repo" from a GitHub URL
func extractRepoName(url string) string {
// Remove protocol
url = strings.TrimPrefix(url, "https://")
url = strings.TrimPrefix(url, "http://")
// Remove host
url = strings.TrimPrefix(url, "github.com/")
url = strings.TrimPrefix(url, "gitlab.com/")
// Remove trailing .git
url = strings.TrimSuffix(url, ".git")
// Remove trailing slashes
url = strings.TrimSuffix(url, "/")
return url
}