-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathresolve.go
More file actions
420 lines (391 loc) · 13 KB
/
Copy pathresolve.go
File metadata and controls
420 lines (391 loc) · 13 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
package rubyextractor
import (
"sort"
"strings"
"github.com/enola-labs/enola/internal/facts"
)
// resolveImports derives internal module-coupling edges for Ruby and returns them
// as synthetic dependency facts. Rails autoloads constants, so internal coupling
// is expressed through constant references — class inheritance, include/extend
// mixins, ActiveRecord associations, and method calls — whose relation targets are
// Ruby constant names, not directory paths. None of those relation kinds are
// counted by the coupling consumers (graph, package metrics, explain hotspots),
// which only count dependency facts whose `imports` target matches a module Name.
//
// This pass builds a constant -> declaring-module-dir index, resolves every
// cross-module constant reference to a srcDir -> destDir edge, and emits one
// synthetic dependency fact per unique edge (with an `imports` relation to the
// destination module dir). It also resolves require_relative paths and Packwerk
// package.yml dependencies, and classifies require/require_relative facts as
// internal/stdlib/external in place. This mirrors the Python extractor's resolve
// pass; it never guesses — every edge comes from a real parsed reference.
func resolveImports(allFacts []facts.Fact, isRails bool) []facts.Fact {
ix := buildConstIndex(allFacts)
moduleNames := collectModuleNames(allFacts)
edges := map[[2]string]bool{}
add := func(src, dst string) {
if src == "" || dst == "" || src == dst {
return // skip empties and self-edges
}
edges[[2]string{src, dst}] = true
}
for i := range allFacts {
f := &allFacts[i]
switch f.Kind {
case facts.KindSymbol:
src := declaresTarget(f)
for _, rel := range f.Relations {
switch rel.Kind {
case facts.RelImplements: // inheritance
add(src, ix.resolve(rel.Target, src))
case facts.RelCalls:
if c := constFromCall(rel.Target); c != "" {
add(src, ix.resolve(c, src))
}
}
}
case facts.KindDependency:
src := fileDir(f.File)
for j := range f.Relations {
rel := &f.Relations[j]
switch rel.Kind {
case facts.RelImplements: // include/extend/prepend mixins
if dst := ix.resolve(rel.Target, src); dst != "" {
add(src, dst)
setSource(f, "internal")
} else {
setSource(f, "external")
}
case facts.RelDependsOn: // ActiveRecord associations
if dst := ix.resolve(rel.Target, src); dst != "" {
add(src, dst)
setSource(f, "internal")
} else {
setSource(f, "external")
}
case facts.RelImports: // require / require_relative
classifyRequire(f, rel, src, moduleNames, add)
}
}
case facts.KindModule:
// Packwerk package.yml dependencies: explicit module -> module edges.
for _, rel := range f.Relations {
if rel.Kind == facts.RelDependsOn {
add(packwerkDir(f.Name), packwerkDir(rel.Target))
}
}
}
}
return emitEdges(edges, isRails)
}
// constIndex resolves a Ruby constant reference to the slash dir of the module
// that declares it.
type constIndex struct {
qualified map[string]string // "Orders::Order" -> "app/models/orders"
bare map[string][]string // "Order" -> ["app/models/orders", ...] (sorted, deduped)
}
// buildConstIndex indexes every class/module/constant symbol by its qualified and
// bare names. Source dir is the declares-relation target (fallback fileDir).
func buildConstIndex(allFacts []facts.Fact) *constIndex {
ix := &constIndex{qualified: map[string]string{}, bare: map[string][]string{}}
for i := range allFacts {
f := &allFacts[i]
if f.Kind != facts.KindSymbol {
continue
}
switch sk, _ := f.Props["symbol_kind"].(string); sk {
case facts.SymbolClass, facts.SymbolInterface, facts.SymbolConstant:
default:
continue
}
dir := declaresTarget(f)
if dir == "" {
continue
}
qn := stripLeadingColons(f.Name)
if qn == "" {
continue
}
// Qualified: prefer the shortest declaring dir on collision (nearest root).
if cur, ok := ix.qualified[qn]; !ok || shorter(dir, cur) {
ix.qualified[qn] = dir
}
bare := lastSegment(qn)
ix.bare[bare] = append(ix.bare[bare], dir)
}
for k, dirs := range ix.bare {
ix.bare[k] = sortDedupDirs(dirs)
}
return ix
}
// resolve returns the declaring module dir of a constant reference, or "". src is
// the referring symbol's dir, used to disambiguate bare-name collisions: Ruby
// constant lookup is lexical, so a declarer in the referrer's own namespace wins.
func (ix *constIndex) resolve(ref, src string) string {
ref = stripLeadingColons(ref)
if ref == "" {
return ""
}
if dir, ok := ix.qualified[ref]; ok {
return dir
}
dirs := ix.bare[lastSegment(ref)]
switch len(dirs) {
case 0:
return ""
case 1:
return dirs[0]
}
// Ambiguous bare name (several declarers of the same simple name). Prefer the
// candidate sharing the longest leading path with the referrer's dir. If the
// best match is not strictly better than the runner-up, or no candidate shares
// any namespace with the referrer, the reference is genuinely ambiguous — drop
// it rather than fabricate an edge to an arbitrary (shortest-dir) declarer.
best, bestScore := "", 0
tie := false
for _, d := range dirs {
s := commonPrefixSegments(src, d)
switch {
case s > bestScore:
best, bestScore, tie = d, s, false
case s == bestScore:
tie = true
}
}
if bestScore == 0 || tie {
return ""
}
return best
}
// commonPrefixSegments counts the equal leading '/'-separated path segments of a
// and b (e.g. "app/models/x" vs "app/models/y" → 2, "app/x" vs "lib/y" → 0).
func commonPrefixSegments(a, b string) int {
as, bs := strings.Split(a, "/"), strings.Split(b, "/")
n := 0
for n < len(as) && n < len(bs) && as[n] == bs[n] {
n++
}
return n
}
// classifyRequire resolves a require/require_relative dependency fact: relative
// requires are intra-project (resolved to a module dir when possible); absolute
// requires are stdlib or external. Sets Props["source"] in place.
func classifyRequire(f *facts.Fact, rel *facts.Relation, src string, moduleNames map[string]bool, add func(s, d string)) {
raw := rel.Target
isRel, _ := f.Props["require_relative"].(bool)
switch {
case isRel || strings.HasPrefix(raw, "."):
if dst := resolveRequireRelative(raw, src, moduleNames); dst != "" {
add(src, dst)
}
setSource(f, "internal")
case rubyStdlib[raw] || rubyStdlib[firstPathSeg(raw)]:
setSource(f, "stdlib")
default:
setSource(f, "external")
}
}
// resolveRequireRelative resolves a relative require path (e.g. "../helper")
// against the importing file's dir, then walks up to the nearest known module.
// Returns "" if it cannot be placed inside the project.
func resolveRequireRelative(raw, importerDir string, moduleNames map[string]bool) string {
p := strings.TrimSuffix(raw, ".rb")
base := importerDir
if base == "" {
base = "."
}
for _, seg := range strings.Split(p, "/") {
switch seg {
case "", ".":
// stay
case "..":
base = parentDir(base)
default:
if base == "." {
base = seg
} else {
base = base + "/" + seg
}
}
}
// The resolved path points at a file; its module is the containing dir, walked
// up to the nearest known module.
return nearestModule(fileDir(base), moduleNames)
}
// nearestModule walks up dir's ancestors until it finds a known module, or "".
func nearestModule(dir string, moduleNames map[string]bool) string {
cur := dir
for cur != "" && cur != "." {
if moduleNames[cur] {
return cur
}
cur = parentDir(cur)
}
if moduleNames[cur] {
return cur
}
return ""
}
// emitEdges builds one synthetic dependency fact per unique edge. File is set to
// "<srcDir>/_coupling.rb" so that consumers deriving the source module via
// fileDir(File) recover exactly srcDir (a bare srcDir would lose its last segment).
func emitEdges(edges map[[2]string]bool, isRails bool) []facts.Fact {
out := make([]facts.Fact, 0, len(edges))
for e := range edges {
src, dst := e[0], e[1]
props := map[string]any{
"language": "ruby",
"source": "internal",
"synthetic_coupling": true,
}
if isRails {
props["framework"] = "rails"
}
out = append(out, facts.Fact{
Kind: facts.KindDependency,
Name: src + " -> " + dst,
File: src + "/_coupling.rb",
Props: props,
Relations: []facts.Relation{{Kind: facts.RelImports, Target: dst}},
})
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// --- helpers ---
// constFromCall turns a calls-target into its receiver constant, or "" when the
// receiver is not a constant. Splits on the LAST '.' so the inner '::' of a
// namespaced receiver is preserved: "Foo::Bar.method" -> "Foo::Bar",
// "Account.active" -> "Account", "var.method" -> "" (lowercase receiver).
func constFromCall(target string) string {
target = stripLeadingColons(target)
dot := strings.LastIndex(target, ".")
if dot < 0 {
return ""
}
recv := target[:dot]
if recv == "" || !startsUpper(recv) {
return ""
}
return recv
}
// declaresTarget returns a fact's declares-relation target (its module dir),
// falling back to the directory of its file.
func declaresTarget(f *facts.Fact) string {
for _, rel := range f.Relations {
if rel.Kind == facts.RelDeclares {
return rel.Target
}
}
return fileDir(f.File)
}
// collectModuleNames returns the set of module-fact Names.
func collectModuleNames(allFacts []facts.Fact) map[string]bool {
m := make(map[string]bool)
for i := range allFacts {
if allFacts[i].Kind == facts.KindModule {
m[allFacts[i].Name] = true
}
}
return m
}
// setSource sets Props["source"] if not already set.
func setSource(f *facts.Fact, source string) {
if f.Props == nil {
f.Props = map[string]any{}
}
if _, ok := f.Props["source"]; !ok {
f.Props["source"] = source
}
}
// packwerkDir normalizes a Packwerk package name/target: "root" -> ".".
func packwerkDir(name string) string {
if name == "root" {
return "."
}
return name
}
// fileDir returns the directory portion of a slash file path, or "." for a bare
// filename.
func fileDir(p string) string {
if i := strings.LastIndex(p, "/"); i >= 0 {
return p[:i]
}
return "."
}
// parentDir returns the parent of a slash dir path, clamped at ".".
func parentDir(p string) string {
if p == "" || p == "." {
return "."
}
if i := strings.LastIndex(p, "/"); i >= 0 {
return p[:i]
}
return "."
}
// stripLeadingColons removes a leading "::" from a Ruby constant reference.
func stripLeadingColons(s string) string {
return strings.TrimPrefix(s, "::")
}
// lastSegment returns the final "::"-separated segment ("Orders::Order" -> "Order").
func lastSegment(s string) string {
if i := strings.LastIndex(s, "::"); i >= 0 {
return s[i+2:]
}
return s
}
// firstPathSeg returns the segment before the first '/' ("net/http" -> "net").
func firstPathSeg(s string) string {
if i := strings.IndexByte(s, '/'); i >= 0 {
return s[:i]
}
return s
}
// startsUpper reports whether the first character is an ASCII uppercase letter
// (a Ruby constant always starts uppercase; a variable receiver does not).
func startsUpper(s string) bool {
return len(s) > 0 && s[0] >= 'A' && s[0] <= 'Z'
}
// shorter reports whether dir a is "nearer a source root" than b: fewer path
// segments, then lexicographically smaller.
func shorter(a, b string) bool {
sa, sb := strings.Count(a, "/"), strings.Count(b, "/")
if sa != sb {
return sa < sb
}
return a < b
}
// sortDedupDirs sorts dirs by the shorter() order and removes duplicates.
func sortDedupDirs(dirs []string) []string {
sort.Slice(dirs, func(i, j int) bool { return shorter(dirs[i], dirs[j]) })
out := dirs[:0:0]
var prev string
for i, d := range dirs {
if i == 0 || d != prev {
out = append(out, d)
}
prev = d
}
return out
}
// rubyStdlib is the set of Ruby standard-library require names, used to split
// non-internal requires into "stdlib" vs "external" in the dependency breakdown.
var rubyStdlib = map[string]bool{
"set": true, "json": true, "yaml": true, "psych": true, "date": true,
"time": true, "securerandom": true, "digest": true, "openssl": true,
"net/http": true, "net/https": true, "net/smtp": true, "net/imap": true,
"net/pop": true, "net/ftp": true, "net": true, "fileutils": true,
"logger": true, "forwardable": true, "singleton": true, "ostruct": true,
"pathname": true, "uri": true, "base64": true, "csv": true, "erb": true,
"tempfile": true, "stringio": true, "benchmark": true, "monitor": true,
"timeout": true, "thread": true, "fiber": true, "socket": true,
"resolv": true, "ipaddr": true, "zlib": true, "stringscanner": true,
"strscan": true, "io/console": true, "io/wait": true, "pp": true,
"pstore": true, "delegate": true, "observer": true, "comparable": true,
"enumerator": true, "rational": true, "complex": true, "bigdecimal": true,
"prime": true, "matrix": true, "abbrev": true, "shellwords": true,
"optparse": true, "getoptlong": true, "tsort": true, "weakref": true,
"objspace": true, "coverage": true, "ripper": true, "readline": true,
"etc": true, "fcntl": true, "syslog": true, "open3": true, "open-uri": true,
"tmpdir": true, "find": true, "rbconfig": true, "mkmf": true, "rubygems": true,
}