-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
547 lines (486 loc) · 16 KB
/
main.go
File metadata and controls
547 lines (486 loc) · 16 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
package main
import (
_ "embed"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"github.com/bmatcuk/doublestar/v4"
"goodchanges/internal/analyzer"
"goodchanges/internal/git"
"goodchanges/internal/lockfile"
"goodchanges/internal/rush"
)
//go:embed VERSION
var version string
var flagIncludeTypes bool
var flagIncludeCSS bool
var flagLog bool
var flagDebug bool
type TargetResult struct {
Name string `json:"name"`
Detections []string `json:"detections,omitempty"`
}
// envBool returns true if the environment variable is set to a non-empty value.
func envBool(key string) bool {
return os.Getenv(key) != ""
}
// logf prints to stdout only when LOG_LEVEL is set.
func logf(format string, args ...interface{}) {
if flagLog {
fmt.Printf(format, args...)
}
}
func main() {
for _, arg := range os.Args[1:] {
if arg == "-v" || arg == "--version" {
fmt.Print(strings.TrimSpace(version))
fmt.Println()
os.Exit(0)
}
}
flagIncludeTypes = envBool("INCLUDE_TYPES")
flagIncludeCSS = envBool("INCLUDE_CSS")
logLevel := strings.ToUpper(os.Getenv("LOG_LEVEL"))
flagLog = logLevel == "BASIC" || logLevel == "DEBUG"
flagDebug = logLevel == "DEBUG"
analyzer.Debug = flagDebug
analyzer.IncludeCSS = flagIncludeCSS
var mergeBase string
if commit := os.Getenv("COMPARE_COMMIT"); commit != "" {
mergeBase = commit
} else {
compareBranch := os.Getenv("COMPARE_BRANCH")
if compareBranch == "" {
compareBranch = "origin/master"
}
var err error
mergeBase, err = git.MergeBase(compareBranch)
if err != nil {
fmt.Fprintf(os.Stderr, "Error finding merge-base with %s: %v\n", compareBranch, err)
os.Exit(1)
}
}
changedFiles, err := git.ChangedFilesSince(mergeBase)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting changed files: %v\n", err)
os.Exit(1)
}
rushConfig, err := rush.LoadConfig(".")
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading rush config: %v\n", err)
os.Exit(1)
}
projectMap := rush.BuildProjectMap(rushConfig)
configMap := rush.LoadAllProjectConfigs(rushConfig)
// Parse TARGETS filter early to skip expensive detection for non-matching targets
var targetPatterns []string
if targetsEnv := os.Getenv("TARGETS"); targetsEnv != "" {
targetPatterns = strings.Split(targetsEnv, ",")
}
// When TARGETS is set, compute the relevant package set: active targets + their
// transitive dependencies. Only these packages need change detection and analysis.
var relevantPackages map[string]bool
if len(targetPatterns) > 0 {
var targetSeeds []string
for _, rp := range rushConfig.Projects {
cfg := configMap[rp.ProjectFolder]
if cfg == nil {
continue
}
for _, td := range cfg.Targets {
if matchesTargetFilter(td.OutputName(rp.PackageName), targetPatterns) {
targetSeeds = append(targetSeeds, rp.PackageName)
}
}
}
relevantPackages = rush.FindTransitiveDependencies(projectMap, targetSeeds)
}
changedProjects := rush.FindChangedProjects(rushConfig, projectMap, changedFiles, configMap, relevantPackages)
// Detect lockfile dep changes per subspace (folder → set of changed dep names)
depChangedDeps, versionChangedSubspaces := findLockfileAffectedProjects(rushConfig, mergeBase)
// When lockfileVersion changes in a subspace, treat all projects in that subspace
// as having all external deps changed. This feeds into the existing taint propagation:
// depChangedDeps → changedProjects → affectedSet → library analysis → target detection.
for _, rp := range rushConfig.Projects {
subspace := rp.SubspaceName
if subspace == "" {
subspace = "default"
}
if versionChangedSubspaces[subspace] {
if depChangedDeps[rp.ProjectFolder] == nil {
depChangedDeps[rp.ProjectFolder] = make(map[string]bool)
}
depChangedDeps[rp.ProjectFolder]["*"] = true
}
}
// Add dep-affected projects to the changed set (they count as directly changed)
for folder := range depChangedDeps {
for _, rp := range rushConfig.Projects {
if rp.ProjectFolder == folder {
if relevantPackages != nil && !relevantPackages[rp.PackageName] {
break
}
if changedProjects[rp.PackageName] == nil {
changedProjects[rp.PackageName] = projectMap[rp.PackageName]
}
break
}
}
}
// Find the full affected subgraph: directly changed + all transitive dependents
var seeds []string
for pkgName := range changedProjects {
seeds = append(seeds, pkgName)
}
affectedSet := rush.FindTransitiveDependents(projectMap, seeds)
// Narrow to relevant packages when TARGETS is set
if relevantPackages != nil {
for pkg := range affectedSet {
if !relevantPackages[pkg] {
delete(affectedSet, pkg)
}
}
}
// Topologically sort: level 0 = lowest-level (no deps on other affected packages)
levels := rush.TopologicalSort(projectMap, affectedSet)
logf("Merge base: %s\n\n", mergeBase)
logf("Directly changed projects: %d\n", len(changedProjects))
logf("Dep-affected projects (lockfile): %d\n", len(depChangedDeps))
logf("Total affected projects (incl. transitive dependents): %d\n", len(affectedSet))
logf("Processing in %d levels (bottom-up):\n\n", len(levels))
// Track affected exports per package for cross-package propagation.
allUpstreamTaint := make(map[string]map[string]bool)
// Seed upstream taint for libraries in version-changed subspaces.
// A lockfileVersion change means we can't reliably diff individual deps,
// so treat all exports as tainted. This propagates through the analysis loop.
for _, rp := range rushConfig.Projects {
subspace := rp.SubspaceName
if subspace == "" {
subspace = "default"
}
if !versionChangedSubspaces[subspace] {
continue
}
info := projectMap[rp.PackageName]
if info == nil {
continue
}
if analyzer.IsLibrary(info.Package) {
if allUpstreamTaint[rp.PackageName] == nil {
allUpstreamTaint[rp.PackageName] = make(map[string]bool)
}
allUpstreamTaint[rp.PackageName]["*"] = true
}
}
type pkgResult struct {
pkgName string
affected []analyzer.AffectedExport
}
for levelIdx, level := range levels {
logf("--- Level %d (%d packages) ---\n\n", levelIdx, len(level))
var wg sync.WaitGroup
resultsCh := make(chan pkgResult, len(level))
for _, pkgName := range level {
info := projectMap[pkgName]
if info == nil {
continue
}
pkg := info.Package
lib := analyzer.IsLibrary(pkg)
directlyChanged := changedProjects[pkgName] != nil
changedDeps := depChangedDeps[info.ProjectFolder]
isDepAffected := len(changedDeps) > 0
logf("=== %s (%s) ===\n", pkgName, info.ProjectFolder)
if directlyChanged && isDepAffected {
logf(" [directly changed + dep change in lockfile]\n")
} else if directlyChanged {
logf(" [directly changed]\n")
} else if isDepAffected {
logf(" [dep change in lockfile]\n")
} else {
logf(" [affected via dependencies]\n")
}
if !lib {
logf(" Type: app (not a library) — skipping export analysis\n\n")
continue
}
logf(" Type: library\n")
entrypoints := analyzer.FindEntrypoints(info.ProjectFolder, pkg)
if len(entrypoints) == 0 {
logf(" No entrypoints found — skipping\n\n")
continue
}
logf(" Entrypoints:\n")
for _, ep := range entrypoints {
logf(" %s → %s\n", ep.ExportPath, ep.SourceFile)
}
if isDepAffected {
depNames := make([]string, 0, len(changedDeps))
for d := range changedDeps {
depNames = append(depNames, d)
}
logf(" Changed external deps: %s\n", strings.Join(depNames, ", "))
}
// Build upstream taint for this package from its dependencies.
// allUpstreamTaint is only read here — writes happen after the level completes.
pkgUpstreamTaint := make(map[string]map[string]bool)
for _, dep := range info.DependsOn {
for specifier, names := range allUpstreamTaint {
if strings.HasPrefix(specifier, dep) {
if pkgUpstreamTaint[specifier] == nil {
pkgUpstreamTaint[specifier] = make(map[string]bool)
}
for n := range names {
pkgUpstreamTaint[specifier][n] = true
}
}
}
}
wg.Add(1)
go func(pkgName string, projectFolder string, entrypoints []analyzer.Entrypoint, pkgUpstreamTaint map[string]map[string]bool, changedDeps map[string]bool) {
defer wg.Done()
affected, err := analyzer.AnalyzeLibraryPackage(projectFolder, entrypoints, mergeBase, changedFiles, flagIncludeTypes, pkgUpstreamTaint, changedDeps)
if err != nil {
fmt.Fprintf(os.Stderr, " Error analyzing package %s: %v\n", pkgName, err)
return
}
if len(affected) > 0 {
resultsCh <- pkgResult{pkgName: pkgName, affected: affected}
}
}(pkgName, info.ProjectFolder, entrypoints, pkgUpstreamTaint, changedDeps)
}
wg.Wait()
close(resultsCh)
// Merge results into allUpstreamTaint after all goroutines in this level are done
for res := range resultsCh {
logf(" Affected exports for %s:\n", res.pkgName)
for _, ae := range res.affected {
logf(" Entrypoint %q:\n", ae.EntrypointPath)
for _, name := range ae.ExportNames {
logf(" - %s\n", name)
}
specifier := res.pkgName
if ae.EntrypointPath != "." {
specifier = res.pkgName + strings.TrimPrefix(ae.EntrypointPath, ".")
}
if allUpstreamTaint[specifier] == nil {
allUpstreamTaint[specifier] = make(map[string]bool)
}
for _, name := range ae.ExportNames {
allUpstreamTaint[specifier][name] = true
}
}
logf("\n")
}
}
// CSS/SCSS taint propagation: when --include-css is set, any changed CSS/SCSS
// file in a library taints all style imports from that library in downstream packages.
if flagIncludeCSS {
cssTaintedPkgs := analyzer.FindCSSTaintedPackages(changedFiles, rushConfig, projectMap)
for pkgName := range cssTaintedPkgs {
key := analyzer.CSSTaintPrefix + pkgName
if allUpstreamTaint[key] == nil {
allUpstreamTaint[key] = make(map[string]bool)
}
allUpstreamTaint[key]["*"] = true
if flagDebug {
fmt.Fprintf(os.Stderr, "[DEBUG] CSS taint: %s\n", pkgName)
}
}
// Propagate CSS taint through SCSS @use chains across libraries
analyzer.PropagateCSSTaint(rushConfig, projectMap, allUpstreamTaint)
}
// Detect affected targets from .goodchangesrc.json configs.
changedE2E := make(map[string]*TargetResult)
defaultChangeDirs := []rush.ChangeDir{{Glob: "**/*"}}
for _, rp := range rushConfig.Projects {
cfg := configMap[rp.ProjectFolder]
if cfg == nil {
continue
}
for _, td := range cfg.Targets {
name := td.OutputName(rp.PackageName)
if len(targetPatterns) > 0 && !matchesTargetFilter(name, targetPatterns) {
continue
}
// Merge global + per-target ignores for this target's detection
targetCfg := cfg.WithTargetIgnores(td)
// Quick check: lockfile dep changes (project-wide)
if len(depChangedDeps[rp.ProjectFolder]) > 0 {
changedE2E[name] = &TargetResult{Name: name}
continue
}
// Quick check: app taint
if td.App != nil {
appInfo := projectMap[*td.App]
if appInfo != nil {
if changedProjects[*td.App] != nil {
changedE2E[name] = &TargetResult{Name: name}
continue
}
if len(depChangedDeps[appInfo.ProjectFolder]) > 0 {
changedE2E[name] = &TargetResult{Name: name}
continue
}
if analyzer.HasTaintedImports(appInfo.ProjectFolder, allUpstreamTaint, nil) {
changedE2E[name] = &TargetResult{Name: name}
continue
}
}
}
// ChangeDirs detection (defaults to **/* if not configured)
changeDirs := td.ChangeDirs
if len(changeDirs) == 0 {
changeDirs = defaultChangeDirs
}
normalTriggered := false
var fineGrainedDetections []string
for _, cd := range changeDirs {
if cd.IsFineGrained() {
filterPattern := ""
if cd.Filter != nil {
filterPattern = *cd.Filter
}
detected := analyzer.FindAffectedFiles(cd.Glob, filterPattern, allUpstreamTaint, changedFiles, rp.ProjectFolder, targetCfg, depChangedDeps[rp.ProjectFolder], mergeBase, flagIncludeTypes)
if len(detected) > 0 {
fineGrainedDetections = append(fineGrainedDetections, detected...)
}
} else {
// Normal: check for any changed file matching the glob
for _, f := range changedFiles {
if !strings.HasPrefix(f, rp.ProjectFolder+"/") {
continue
}
relPath := strings.TrimPrefix(f, rp.ProjectFolder+"/")
if targetCfg.IsIgnored(relPath) {
continue
}
if matched, _ := doublestar.Match(cd.Glob, relPath); matched {
normalTriggered = true
break
}
}
if !normalTriggered {
if analyzer.HasTaintedImportsForGlob(rp.ProjectFolder, cd.Glob, allUpstreamTaint, targetCfg) {
normalTriggered = true
}
}
}
if normalTriggered {
break
}
}
if normalTriggered {
changedE2E[name] = &TargetResult{Name: name}
} else if len(fineGrainedDetections) > 0 {
sort.Strings(fineGrainedDetections)
changedE2E[name] = &TargetResult{
Name: name,
Detections: fineGrainedDetections,
}
}
}
}
// Build sorted list of affected targets
e2eList := make([]*TargetResult, 0, len(changedE2E))
for _, result := range changedE2E {
e2eList = append(e2eList, result)
}
sort.Slice(e2eList, func(i, j int) bool {
return e2eList[i].Name < e2eList[j].Name
})
if flagLog {
logf("Affected e2e packages (%d):\n", len(e2eList))
for _, result := range e2eList {
if len(result.Detections) > 0 {
logf(" - %s (fine-grained: %d files)\n", result.Name, len(result.Detections))
for _, d := range result.Detections {
logf(" %s\n", d)
}
} else {
logf(" - %s\n", result.Name)
}
}
}
// Always output JSON to stdout
jsonBytes, _ := json.Marshal(e2eList)
fmt.Println(string(jsonBytes))
}
// findLockfileAffectedProjects checks each subspace's pnpm-lock.yaml for dep changes.
// Returns:
// - depChanges: project folder → set of changed external dep package names
// - versionChanges: subspace name → true for subspaces where lockfileVersion changed
func findLockfileAffectedProjects(config *rush.Config, mergeBase string) (map[string]map[string]bool, map[string]bool) {
// Collect subspaces: "default" for projects without subspaceName, plus named ones
subspaces := make(map[string]bool)
subspaces["default"] = true
for _, p := range config.Projects {
if p.SubspaceName != "" {
subspaces[p.SubspaceName] = true
}
}
result := make(map[string]map[string]bool)
versionChanged := make(map[string]bool)
for subspace := range subspaces {
lockfilePath := filepath.Join("common", "config", "subspaces", subspace, "pnpm-lock.yaml")
if _, err := os.Stat(lockfilePath); err != nil {
continue
}
// Compare lockfileVersion between base commit and current
newContent, err := os.ReadFile(lockfilePath)
if err != nil {
continue
}
oldContent, _ := git.ShowFile(mergeBase, lockfilePath)
oldVersion := lockfile.ParseLockfileVersion([]byte(oldContent))
newVersion := lockfile.ParseLockfileVersion(newContent)
if oldVersion != newVersion {
versionChanged[subspace] = true
logf("lockfileVersion changed in subspace %q: %q → %q\n", subspace, oldVersion, newVersion)
}
diffText, err := git.DiffSincePath(mergeBase, lockfilePath)
if err != nil || diffText == "" {
continue
}
affected := lockfile.FindDepAffectedProjects(lockfilePath, subspace, diffText)
for folder, deps := range affected {
if result[folder] == nil {
result[folder] = make(map[string]bool)
}
for dep := range deps {
result[folder][dep] = true
}
}
}
return result, versionChanged
}
// matchesTargetFilter checks if a target name matches any of the given patterns.
// Patterns support * as a wildcard matching any characters (including /).
func matchesTargetFilter(name string, patterns []string) bool {
for _, p := range patterns {
p = strings.TrimSpace(p)
if p == "" {
continue
}
// Convert glob pattern to regex: * -> .*, escape the rest
var re strings.Builder
re.WriteString("^")
for _, ch := range p {
if ch == '*' {
re.WriteString(".*")
} else {
re.WriteString(regexp.QuoteMeta(string(ch)))
}
}
re.WriteString("$")
if matched, _ := regexp.MatchString(re.String(), name); matched {
return true
}
}
return false
}