This repository was archived by the owner on Sep 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
404 lines (360 loc) · 12.7 KB
/
Copy pathmain.go
File metadata and controls
404 lines (360 loc) · 12.7 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/fs"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
// Definition represents a declared function, method, or constructor.
type Definition struct {
ID string `json:"id"`
Name string `json:"name"`
Package string `json:"package"`
FilePath string `json:"filePath"`
Line int `json:"line"`
}
// CallSite represents where a Definition is called/used.
type CallSite struct {
FilePath string `json:"filePath"`
Line int `json:"line"`
CallerID string `json:"callerId"`
}
// Mapping links a single Definition to all the places it's called.
type Mapping struct {
Definition Definition `json:"definition"`
CallSites []CallSite `json:"callSites"`
}
// AnalysisTarget holds the filesystem path and module path for a codebase to be analyzed.
type AnalysisTarget struct {
FSRoot string // The absolute path on the filesystem
ModulePath string // The Go module path (e.g., "github.com/my/project")
}
var (
definitions = make(map[string]Definition)
mappings = make(map[string]*Mapping)
fileSet = token.NewFileSet()
)
func main() {
// --- 1. Flags and Configuration ---
targetPath := flag.String("path", ".", "Path to the Go application to analyze")
outputFile := flag.String("out", "codemap.json", "Output JSON file name")
serveAddr := flag.String("serve", "", "If set, serves visualization on this address (e.g., ':8080')")
visualizerDir := flag.String("viz-dir", "./visualizer", "Path to the visualizer's static files (html, css, js)")
goModCache := flag.String("gopath", "", "Path to Go's module cache (GOMODCACHE). If empty, will try to auto-detect.")
analyzeDeps := flag.String("analyze-deps", "", "Comma-separated list of external dependency prefixes to analyze (e.g., 'bitbucket/ggwp,github.com/gin-gonic/gin')")
skipPatternsRaw := flag.String("skip", "", "Comma-separated list of path substrings to skip (e.g., 'ent,models,generated')") // <<< CHANGED
flag.Parse()
// <<< CHANGED: Process the skip patterns into a slice for easy use
var skipPatterns []string
if *skipPatternsRaw != "" {
skipPatterns = strings.Split(*skipPatternsRaw, ",")
}
if *goModCache == "" {
cmd := exec.Command("go", "env", "GOMODCACHE")
out, err := cmd.Output()
if err != nil {
log.Fatalf("Could not auto-detect GOMODCACHE. Please specify it with the -gopath flag. Error: %v", err)
}
*goModCache = strings.TrimSpace(string(out))
log.Printf("Auto-detected GOMODCACHE: %s", *goModCache)
}
mainModulePath, err := getModulePath(*targetPath)
if err != nil {
log.Fatalf("Error finding module path in %s: %v", *targetPath, err)
}
log.Printf("Analyzing main module: %s\n", mainModulePath)
// --- 2. Identify all codebases to analyze (local project + dependencies) ---
analysisTargets := []AnalysisTarget{{FSRoot: *targetPath, ModulePath: mainModulePath}}
if *analyzeDeps != "" {
depPrefixes := strings.Split(*analyzeDeps, ",")
log.Printf("Finding specified dependencies to analyze: %v", depPrefixes)
dependencyTargets, err := findDependencyPaths(*targetPath, *goModCache, depPrefixes)
if err != nil {
log.Fatalf("Could not resolve dependency paths: %v", err)
}
analysisTargets = append(analysisTargets, dependencyTargets...)
}
// --- 3. Run Analysis Passes ---
log.Println("Pass 1: Finding all function definitions...")
for _, target := range analysisTargets {
log.Printf("Scanning definitions in %s (%s)", target.ModulePath, target.FSRoot)
err := walkAndProcess(target, skipPatterns, findDefinitions) // <<< CHANGED
if err != nil {
log.Fatalf("Error during definition scan in %s: %v", target.FSRoot, err)
}
}
log.Println("Pass 2: Finding all call sites...")
for _, target := range analysisTargets {
log.Printf("Scanning call sites in %s (%s)", target.ModulePath, target.FSRoot)
err := walkAndProcess(target, skipPatterns, findCallSites) // <<< CHANGED
if err != nil {
log.Fatalf("Error during call site scan in %s: %v", target.FSRoot, err)
}
}
// --- 4. Serialize and Output Results ---
var finalMappings []Mapping
// <<< CHANGED: Filter out mappings that have no call sites.
for _, m := range mappings {
if len(m.CallSites) > 0 {
finalMappings = append(finalMappings, *m)
}
}
jsonData, err := json.MarshalIndent(finalMappings, "", " ")
if err != nil {
log.Fatalf("Error marshalling JSON: %v", err)
}
err = os.WriteFile(*outputFile, jsonData, 0644)
if err != nil {
log.Fatalf("Error writing to %s: %v", err)
}
log.Printf("Successfully created mapping file: %s", *outputFile)
if *serveAddr != "" {
serveVisualization(*serveAddr, *outputFile, *visualizerDir)
}
}
// <<< CHANGED: Function signature updated to accept skipPatterns
// walkAndProcess abstracts the file walking logic for a given analysis target.
func walkAndProcess(target AnalysisTarget, skipPatterns []string, processor func(filePath string, target AnalysisTarget)) error {
return filepath.WalkDir(target.FSRoot, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// <<< CHANGED: Check if the path should be skipped based on user-provided patterns.
for _, pattern := range skipPatterns {
// Ensure we don't match on empty strings from the split
if pattern != "" && strings.Contains(path, pattern) {
log.Printf("Skipping path due to skip pattern '%s': %s", pattern, path)
// If it's a directory, skip the whole directory.
if d.IsDir() {
return filepath.SkipDir
}
// If it's a file, just skip this file.
return nil
}
}
if !d.IsDir() && strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") {
processor(path, target)
}
return nil
})
}
// getModulePath reads the module path from a go.mod file.
func getModulePath(targetDir string) (string, error) {
goModPath := filepath.Join(targetDir, "go.mod")
content, err := os.ReadFile(goModPath)
if err != nil {
return "", fmt.Errorf("could not read go.mod in '%s': %w", targetDir, err)
}
return modfile.ModulePath(content), nil
}
// findDependencyPaths parses the go.mod file to find the filesystem paths of specified dependencies.
func findDependencyPaths(projectRoot, goModCache string, depPrefixes []string) ([]AnalysisTarget, error) {
var targets []AnalysisTarget
goModPath := filepath.Join(projectRoot, "go.mod")
content, err := os.ReadFile(goModPath)
if err != nil {
return nil, fmt.Errorf("could not read go.mod in '%s': %w", projectRoot, err)
}
modFile, err := modfile.Parse(goModPath, content, nil)
if err != nil {
return nil, fmt.Errorf("could not parse go.mod: %w", err)
}
for _, req := range modFile.Require {
for _, prefix := range depPrefixes {
trimmedPrefix := strings.TrimSpace(prefix)
if strings.HasPrefix(req.Mod.Path, trimmedPrefix) {
escapedPath, err := module.EscapePath(req.Mod.Path)
if err != nil {
log.Printf("Warning: could not escape module path %s: %v", req.Mod.Path, err)
continue
}
depPath := filepath.Join(goModCache, escapedPath+"@"+req.Mod.Version)
if _, err := os.Stat(depPath); os.IsNotExist(err) {
log.Printf("Warning: dependency path not found, skipping: %s", depPath)
continue
}
log.Printf("Found matching dependency: %s version %s at %s", req.Mod.Path, req.Mod.Version, depPath)
targets = append(targets, AnalysisTarget{
FSRoot: depPath,
ModulePath: req.Mod.Path,
})
break
}
}
}
return targets, nil
}
// findDefinitions scans a single file for function and method definitions.
func findDefinitions(filePath string, target AnalysisTarget) {
node, err := parser.ParseFile(fileSet, filePath, nil, 0)
if err != nil {
log.Printf("Warning: Could not parse %s: %v\n", filePath, err)
return
}
relPath, _ := filepath.Rel(target.FSRoot, filePath)
pkgDir := filepath.Dir(relPath)
if pkgDir == "." {
pkgDir = ""
}
fullPkgPath := filepath.ToSlash(filepath.Join(target.ModulePath, pkgDir))
ast.Inspect(node, func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
funcName := fn.Name.Name
def := Definition{
Name: funcName,
FilePath: filepath.ToSlash(relPath),
Line: fileSet.Position(fn.Pos()).Line,
Package: fullPkgPath,
}
if fn.Recv != nil && len(fn.Recv.List) > 0 {
typeExpr := fn.Recv.List[0].Type
buf := new(bytes.Buffer)
if err := printer.Fprint(buf, fileSet, typeExpr); err != nil {
log.Printf("Warning: could not print receiver type for %s in %s: %v", funcName, filePath, err)
return true
}
receiverType := buf.String()
def.ID = fmt.Sprintf("%s.%s.%s", fullPkgPath, receiverType, funcName)
} else {
def.ID = fmt.Sprintf("%s.%s", fullPkgPath, funcName)
}
definitions[def.ID] = def
mappings[def.ID] = &Mapping{Definition: def, CallSites: []CallSite{}}
return true
})
}
// callSiteVisitor implements ast.Visitor to find function calls with accurate caller context.
type callSiteVisitor struct {
fileSet *token.FileSet
target AnalysisTarget
importMap map[string]string
currentPkg string
callerIDStack []string
}
// Visit traverses the AST. It's the core of the improved call site analysis.
func (v *callSiteVisitor) Visit(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
if fn, ok := n.(*ast.FuncDecl); ok {
var callerID string
if fn.Recv != nil && len(fn.Recv.List) > 0 {
typeExpr := fn.Recv.List[0].Type
buf := new(bytes.Buffer)
if err := printer.Fprint(buf, v.fileSet, typeExpr); err != nil {
log.Printf("Warning: could not print receiver type for %s in %s: %v", fn.Name.Name, v.target.FSRoot, err)
callerID = fmt.Sprintf("%s.<?>%s", v.currentPkg, fn.Name.Name)
} else {
callerID = fmt.Sprintf("%s.%s.%s", v.currentPkg, buf.String(), fn.Name.Name)
}
} else {
callerID = fmt.Sprintf("%s.%s", v.currentPkg, fn.Name.Name)
}
v.callerIDStack = append(v.callerIDStack, callerID)
if fn.Body != nil {
ast.Walk(v, fn.Body)
}
v.callerIDStack = v.callerIDStack[:len(v.callerIDStack)-1]
return nil
}
if call, ok := n.(*ast.CallExpr); ok {
if len(v.callerIDStack) > 0 {
calleeID := v.resolveCalleeID(call.Fun)
if m, found := mappings[calleeID]; found {
relPath, _ := filepath.Rel(v.target.FSRoot, v.fileSet.Position(call.Pos()).Filename)
m.CallSites = append(m.CallSites, CallSite{
FilePath: filepath.ToSlash(relPath),
Line: v.fileSet.Position(call.Pos()).Line,
CallerID: v.callerIDStack[len(v.callerIDStack)-1],
})
}
}
}
return v
}
// resolveCalleeID determines the unique ID of the function being called.
func (v *callSiteVisitor) resolveCalleeID(fun ast.Expr) string {
switch f := fun.(type) {
case *ast.SelectorExpr:
if pkgIdent, ok := f.X.(*ast.Ident); ok {
if fullPkgPath, found := v.importMap[pkgIdent.Name]; found {
return fmt.Sprintf("%s.%s", fullPkgPath, f.Sel.Name)
}
}
case *ast.Ident:
return fmt.Sprintf("%s.%s", v.currentPkg, f.Name)
}
return ""
}
// findCallSites prepares and runs the callSiteVisitor on a file.
func findCallSites(filePath string, target AnalysisTarget) {
node, err := parser.ParseFile(fileSet, filePath, nil, 0)
if err != nil {
log.Printf("Warning: Could not parse %s: %v\n", filePath, err)
return
}
relPath, _ := filepath.Rel(target.FSRoot, filePath)
pkgDir := filepath.Dir(relPath)
if pkgDir == "." {
pkgDir = ""
}
currentFullPkgPath := filepath.ToSlash(filepath.Join(target.ModulePath, pkgDir))
importMap := make(map[string]string)
for _, imp := range node.Imports {
path := strings.Trim(imp.Path.Value, `"`)
if imp.Name != nil {
if imp.Name.Name == "_" {
continue
}
importMap[imp.Name.Name] = path
} else {
parts := strings.Split(path, "/")
importMap[parts[len(parts)-1]] = path
}
}
visitor := &callSiteVisitor{
fileSet: fileSet,
target: target,
importMap: importMap,
currentPkg: currentFullPkgPath,
callerIDStack: []string{},
}
ast.Walk(visitor, node)
}
// serveVisualization starts a web server to display the results.
func serveVisualization(addr, jsonFile, vizDir string) {
log.Printf("Starting visualization server at http://localhost%s", addr)
mux := http.NewServeMux()
mux.HandleFunc("/api/codemap", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
http.ServeFile(w, r, jsonFile)
})
fs := http.FileServer(http.Dir(vizDir))
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".css") {
w.Header().Set("Content-Type", "text/css")
} else if strings.HasSuffix(r.URL.Path, ".js") || strings.HasSuffix(r.URL.Path, ".mjs") {
w.Header().Set("Content-Type", "application/javascript")
}
fs.ServeHTTP(w, r)
}))
if err := http.ListenAndServe(addr, mux); err != nil {
log.Fatalf("Server failed: %v", err)
}
}