-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconfigProcessor.go
More file actions
801 lines (710 loc) · 22.8 KB
/
configProcessor.go
File metadata and controls
801 lines (710 loc) · 22.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
package main
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
)
// RestrictedDevDependenciesUsageViolation represents a violation where a dev dependency is used in production code
type RestrictedDevDependenciesUsageViolation struct {
DevDependency string `json:"devDependency"`
FilePath string `json:"filePath"`
EntryPoint string `json:"entryPoint"`
}
// validateRulePathPackageJson checks if package.json exists in the rule path directory
// and returns true if package.json is missing
func validateRulePathPackageJson(rulePath, cwd string) bool {
// Construct the full path to the rule directory
fullRulePath := filepath.Join(cwd, rulePath)
// Check if the directory exists
if _, err := os.Stat(fullRulePath); os.IsNotExist(err) {
// Directory doesn't exist, no need to check for package.json
return false
}
// Check for package.json file in the rule directory
packageJsonPath := filepath.Join(fullRulePath, "package.json")
if _, err := os.Stat(packageJsonPath); os.IsNotExist(err) {
// package.json doesn't exist
return true
}
return false
}
// RuleResult contains the results for a single rule in the config
type RuleResult struct {
RulePath string
FileCount int
EnabledChecks []string
DependencyTree MinimalDependencyTree
ModuleBoundaryViolations []ModuleBoundaryViolation
CircularDependencies [][]string
OrphanFiles []string
OrphanFilesAutofixable []string
MissingNodeModules []MissingNodeModuleResult
MissingNodeModulesOutputType string
UnusedNodeModules []UnusedNodeModuleIssue
UnusedNodeModulesOutputType string
ImportConventionViolations []ImportConventionViolation
UnusedExports []UnusedExport
UnresolvedImports []UnresolvedImport
RestrictedDevDependenciesUsageViolations []RestrictedDevDependenciesUsageViolation
RestrictedImportsViolations []RestrictedImportViolation
RestrictedImportsFollowMonorepoPackages FollowMonorepoPackagesValue
MissingPackageJson bool
ShouldWarnAboutImportConventionWithPJsonImports bool
}
// ConfigProcessingResult contains the results for processing an entire config
type ConfigProcessingResult struct {
RuleResults []RuleResult
HasFailures bool
FixedFilesCount int
FixedImportsCount int
DeletedFilesCount int
UnfixableAliasingCount int
FixableIssuesCount int
FullTree MinimalDependencyTree
}
// discoverAllFilesForConfig discovers all files for config processing
func discoverAllFilesForConfig(
cwd string,
ignoreFiles []string,
) ([]string, []GlobMatcher, error) {
// Create glob matchers for ignore files
ignoreMatchers := CreateGlobMatchers(ignoreFiles, cwd)
// Always include gitignore patterns
gitignoreMatchers := FindAndProcessGitIgnoreFilesUpToRepoRoot(cwd)
combinedMatchers := append(ignoreMatchers, gitignoreMatchers...)
// Get all files using the existing GetFiles function
files := GetFiles(cwd, []string{}, combinedMatchers)
return files, combinedMatchers, nil
}
func anyRuleChecksForUnusedExports(config *RevDepConfig) bool {
for _, rule := range config.Rules {
if anyEnabled(rule.getUnusedExportsDetections()) {
return true
}
}
return false
}
type enabledOption interface {
IsEnabled() bool
}
func anyEnabled[T enabledOption](items []T) bool {
for _, item := range items {
if item.IsEnabled() {
return true
}
}
return false
}
// buildDependencyTreeForConfig builds dependency tree for config processing
func buildDependencyTreeForConfig(
allFiles []string,
excludePatterns []GlobMatcher,
conditionNames []string,
cwd string,
packageJson string,
tsconfigJson string,
customAssetExtensions []string,
parseMode ParseMode,
) (MinimalDependencyTree, *ResolverManager, error) {
// For config processing, we always resolve type imports (we filter later per-check)
ignoreTypeImports := false
// We always follow monorepo packages for comprehensive analysis
followMonorepoPackages := FollowMonorepoPackagesValue{FollowAll: true}
// Skip resolving missing files for performance
skipResolveMissing := false
// Parse imports from all files
fileImportsArr, _ := ParseImportsFromFiles(allFiles, ignoreTypeImports, parseMode)
slices.Sort(allFiles)
// Resolve imports using the existing resolver
fileImportsArr, _, resolverManager := ResolveImports(
fileImportsArr,
allFiles,
cwd,
ignoreTypeImports,
skipResolveMissing,
packageJson,
tsconfigJson,
excludePatterns,
conditionNames,
followMonorepoPackages,
customAssetExtensions,
parseMode,
NodeModulesMatchingStrategySelfResolver,
)
// Transform to minimal dependency tree
minimalTree := TransformToMinimalDependencyTreeCustomParser(fileImportsArr)
return minimalTree, resolverManager, nil
}
func filterFilesForRule(
fullTree MinimalDependencyTree,
rulePath string,
cwd string,
followMonorepoPackages FollowMonorepoPackagesValue,
resolverManager *ResolverManager,
) ([]string, MinimalDependencyTree) {
normalizedRulePath := NormalizePathForInternal(filepath.Clean(JoinWithCwd(cwd, rulePath)))
normalizedRulePathWithSlash := StandardiseDirPathInternal(normalizedRulePath)
isRuleFile := func(filePath string) bool {
normalizedFilePath := NormalizePathForInternal(filePath)
return strings.HasPrefix(normalizedFilePath, normalizedRulePathWithSlash)
}
filesWithinCwd := []string{}
subTree := MinimalDependencyTree{}
for file := range fullTree {
if isRuleFile(file) {
filesWithinCwd = append(filesWithinCwd, file)
}
}
if !followMonorepoPackages.IsEnabled() {
for _, file := range filesWithinCwd {
subTree[file] = fullTree[file]
}
return filesWithinCwd, subTree
}
// Build graph to trace dependencies from other packages
graph := buildDepsGraphForMultiple(fullTree, filesWithinCwd, nil, false, false)
allowedPackagePathPrefixes := map[string]bool{}
if !followMonorepoPackages.ShouldFollowAll() && resolverManager != nil && resolverManager.monorepoContext != nil {
for packageName, packagePath := range resolverManager.monorepoContext.PackageToPath {
if !followMonorepoPackages.ShouldFollowPackage(packageName) {
continue
}
normalizedPackagePath := NormalizePathForInternal(packagePath)
allowedPackagePathPrefixes[StandardiseDirPathInternal(normalizedPackagePath)] = true
}
}
filteredFiles := make([]string, 0, len(graph.Vertices))
for vertex := range graph.Vertices {
if !followMonorepoPackages.ShouldFollowAll() && !isRuleFile(vertex) {
isInAllowedWorkspacePackage := false
for packagePathPrefix := range allowedPackagePathPrefixes {
if strings.HasPrefix(vertex, packagePathPrefix) {
isInAllowedWorkspacePackage = true
break
}
}
if !isInAllowedWorkspacePackage {
continue
}
}
filteredFiles = append(filteredFiles, vertex)
subTree[vertex] = fullTree[vertex]
}
return filteredFiles, subTree
}
// processRuleChecks runs all enabled checks for a rule in parallel
func processRuleChecks(
rule Rule,
ruleFiles []string,
ruleTree MinimalDependencyTree,
fullTree MinimalDependencyTree,
resolverManager *ResolverManager,
cwd string,
fix bool,
) RuleResult {
// Track enabled checks
enabledChecks := []string{}
// Check which detections are enabled
if anyEnabled(rule.getCircularImportsDetections()) {
enabledChecks = append(enabledChecks, "circular-imports")
}
if anyEnabled(rule.getOrphanFilesDetections()) {
enabledChecks = append(enabledChecks, "orphan-files")
}
if len(rule.ModuleBoundaries) > 0 {
enabledChecks = append(enabledChecks, "module-boundaries")
}
if anyEnabled(rule.getUnusedNodeModulesDetections()) {
enabledChecks = append(enabledChecks, "unused-node-modules")
}
if anyEnabled(rule.getMissingNodeModulesDetections()) {
enabledChecks = append(enabledChecks, "missing-node-modules")
}
if anyEnabled(rule.getUnusedExportsDetections()) {
enabledChecks = append(enabledChecks, "unused-exports")
}
if anyEnabled(rule.getUnresolvedImportsDetections()) {
enabledChecks = append(enabledChecks, "unresolved-imports")
}
if anyEnabled(rule.getDevDepsUsageOnProdDetections()) {
enabledChecks = append(enabledChecks, "dev-deps-usage-on-prod")
}
if anyEnabled(rule.getRestrictedImportsDetections()) {
enabledChecks = append(enabledChecks, "restricted-imports")
}
if len(rule.ImportConventions) > 0 {
enabledChecks = append(enabledChecks, "import-conventions")
}
ruleResult := RuleResult{
RulePath: rule.Path,
FileCount: len(ruleFiles),
EnabledChecks: enabledChecks,
DependencyTree: fullTree, // Include the full dependency tree for circular dependency formatting
RestrictedImportsFollowMonorepoPackages: rule.FollowMonorepoPackages,
}
fullRulePath := StandardiseDirPath(filepath.Join(cwd, rule.Path))
rulePathResolver := resolverManager.GetResolverForFile(fullRulePath)
rulePathNodeModules := make(map[string]bool, 0)
if rulePathResolver != nil {
rulePathNodeModules = rulePathResolver.nodeModules
}
// Detect module-suffix variants to exclude from orphan/unused-exports detection.
// Uses per-file resolver lookup so monorepos with package-level moduleSuffixes work.
moduleSuffixVariants := DetectModuleSuffixVariants(ruleFiles, resolverManager)
var wg sync.WaitGroup
var mu sync.Mutex
// Circular Dependencies
if anyEnabled(rule.getCircularImportsDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
// For circular dependencies, use the full tree since we need complete graph
// Sort rule files as required by FindCircularDependencies
sortedRuleFiles := make([]string, len(ruleFiles))
copy(sortedRuleFiles, ruleFiles)
slices.Sort(sortedRuleFiles)
circularDeps := make([][]string, 0)
for _, detection := range rule.getCircularImportsDetections() {
if !detection.Enabled {
continue
}
circularDeps = append(circularDeps, FindCircularDependencies(
ruleTree,
sortedRuleFiles,
detection.IgnoreTypeImports,
)...)
}
mu.Lock()
ruleResult.CircularDependencies = circularDeps
mu.Unlock()
}()
}
// Orphan Files
if anyEnabled(rule.getOrphanFilesDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
orphanSet := map[string]bool{}
orphanAutofixSet := map[string]bool{}
orphanFiles := make([]string, 0)
orphanFilesAutofixable := make([]string, 0)
for _, detection := range rule.getOrphanFilesDetections() {
if !detection.Enabled {
continue
}
found := FindOrphanFiles(
ruleTree,
detection.ValidEntryPoints,
detection.GraphExclude,
detection.IgnoreTypeImports,
fullRulePath,
moduleSuffixVariants,
)
for _, file := range found {
if !orphanSet[file] {
orphanSet[file] = true
orphanFiles = append(orphanFiles, file)
}
if detection.Autofix && !orphanAutofixSet[file] {
orphanAutofixSet[file] = true
orphanFilesAutofixable = append(orphanFilesAutofixable, file)
}
}
}
slices.Sort(orphanFiles)
slices.Sort(orphanFilesAutofixable)
mu.Lock()
ruleResult.OrphanFiles = orphanFiles
ruleResult.OrphanFilesAutofixable = orphanFilesAutofixable
mu.Unlock()
}()
}
// Module Boundaries
if len(rule.ModuleBoundaries) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
violations := CheckModuleBoundariesFromTree(
ruleTree,
ruleFiles,
rule.ModuleBoundaries,
fullRulePath,
)
mu.Lock()
ruleResult.ModuleBoundaryViolations = violations
mu.Unlock()
}()
}
// Unused Node Modules
if anyEnabled(rule.getUnusedNodeModulesDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
unusedSet := map[string]bool{}
unusedModules := make([]UnusedNodeModuleIssue, 0)
outputType := ""
for _, detection := range rule.getUnusedNodeModulesDetections() {
if !detection.Enabled {
continue
}
found := GetUnusedNodeModulesFromTree(
ruleTree,
rulePathNodeModules,
fullRulePath,
detection.PkgJsonFieldsWithBinaries,
detection.FilesWithBinaries,
detection.FilesWithModules,
"", // use empty path so it is discovered in fullRulePath
"", // use empty path so it is discovered in fullRulePath
detection.IncludeModules,
detection.ExcludeModules,
)
for _, moduleName := range found {
if !unusedSet[moduleName] {
unusedSet[moduleName] = true
unusedModules = append(unusedModules, UnusedNodeModuleIssue{
ModuleName: moduleName,
PackageJsonPath: rulePathResolver.packageJsonPath,
})
}
}
if outputType == "" && detection.OutputType != "" {
outputType = detection.OutputType
}
}
slices.SortFunc(unusedModules, func(a, b UnusedNodeModuleIssue) int {
return strings.Compare(a.ModuleName, b.ModuleName)
})
mu.Lock()
ruleResult.UnusedNodeModules = unusedModules
if outputType != "" {
ruleResult.UnusedNodeModulesOutputType = outputType
}
mu.Unlock()
}()
}
// Missing Node Modules
if anyEnabled(rule.getMissingNodeModulesDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
missingModules := make([]MissingNodeModuleResult, 0)
outputType := ""
for _, detection := range rule.getMissingNodeModulesDetections() {
if !detection.Enabled {
continue
}
missingModules = append(missingModules, GetMissingNodeModulesFromTree(
ruleTree,
detection.IncludeModules,
detection.ExcludeModules,
rulePathNodeModules,
)...)
if outputType == "" && detection.OutputType != "" {
outputType = detection.OutputType
}
}
mu.Lock()
ruleResult.MissingNodeModules = missingModules
if outputType != "" {
ruleResult.MissingNodeModulesOutputType = outputType
}
mu.Unlock()
}()
}
// Import Conventions
if len(rule.ImportConventions) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
violations, shouldWarnAboutImportConventionWithPJsonImports := CheckImportConventionsFromTree(
ruleTree,
ruleFiles,
rule.ImportConventions,
rulePathResolver,
fullRulePath, // Use rule path instead of current working directory
fix,
)
mu.Lock()
ruleResult.ImportConventionViolations = violations
ruleResult.ShouldWarnAboutImportConventionWithPJsonImports = shouldWarnAboutImportConventionWithPJsonImports
mu.Unlock()
}()
}
// Unused Exports
if anyEnabled(rule.getUnusedExportsDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
unusedExports := make([]UnusedExport, 0)
for _, detection := range rule.getUnusedExportsDetections() {
if !detection.Enabled {
continue
}
found := FindUnusedExports(
ruleFiles,
ruleTree,
detection.ValidEntryPoints,
detection.GraphExclude,
detection.IgnoreTypeExports,
detection.Autofix,
fullRulePath,
moduleSuffixVariants,
)
found = FilterUnusedExports(found, detection, fullRulePath)
unusedExports = append(unusedExports, found...)
}
mu.Lock()
ruleResult.UnusedExports = unusedExports
mu.Unlock()
}()
}
// Unresolved Imports
if anyEnabled(rule.getUnresolvedImportsDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
// NotResolvedModule might be actually a node module, but defined rule path package (eg apps/main-app) not in just in time package (pacakges/shared)
// We are not able to detect that during module resolution for config file, becasue we resolve all modules without knowing which workspace contains app and which contains shared code
// During rule evaluation we can assume that package.json in rule path is the one that contains node modules for app build from that rule path
unresolved := make([]UnresolvedImport, 0)
for _, detection := range rule.getUnresolvedImportsDetections() {
if !detection.Enabled {
continue
}
found := DetectUnresolvedImports(ruleTree, rulePathNodeModules)
found = FilterUnresolvedImports(found, detection, fullRulePath)
unresolved = append(unresolved, found...)
}
mu.Lock()
ruleResult.UnresolvedImports = unresolved
mu.Unlock()
}()
}
// Restricted Dev Dependencies Usage
if anyEnabled(rule.getDevDepsUsageOnProdDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
var devDependencies map[string]bool
if rulePathResolver != nil {
devDependencies = rulePathResolver.devNodeModules
}
violations := make([]RestrictedDevDependenciesUsageViolation, 0)
for _, detection := range rule.getDevDepsUsageOnProdDetections() {
if !detection.Enabled {
continue
}
violations = append(violations, FindDevDependenciesInProduction(
ruleTree,
detection.ProdEntryPoints,
detection.IgnoreTypeImports,
fullRulePath,
devDependencies,
)...)
}
mu.Lock()
ruleResult.RestrictedDevDependenciesUsageViolations = violations
mu.Unlock()
}()
}
// Restricted Imports
if anyEnabled(rule.getRestrictedImportsDetections()) {
wg.Add(1)
go func() {
defer wg.Done()
violations := make([]RestrictedImportViolation, 0)
for _, detection := range rule.getRestrictedImportsDetections() {
if !detection.Enabled {
continue
}
violations = append(violations, FindRestrictedImports(
ruleTree,
detection,
fullRulePath,
)...)
}
mu.Lock()
ruleResult.RestrictedImportsViolations = violations
mu.Unlock()
}()
}
wg.Wait()
return ruleResult
}
// ProcessConfig processes a rev-dep configuration with parallel rule and check execution
func ProcessConfig(
config *RevDepConfig,
cwd string,
packageJson string,
tsconfigJson string,
fix bool,
forceDetailed bool,
) (*ConfigProcessingResult, error) {
// Step 1: Discover all files
allFiles, excludePatterns, err := discoverAllFilesForConfig(cwd, config.IgnoreFiles)
if err != nil {
return nil, err
}
// Step 2: Build dependency tree for config
parseMode := ParseModeBasic
if forceDetailed || anyRuleChecksForUnusedExports(config) {
parseMode = ParseModeDetailed
}
fullTree, resolverManager, err := buildDependencyTreeForConfig(
allFiles,
excludePatterns,
config.ConditionNames,
cwd,
packageJson,
tsconfigJson,
config.CustomAssetExtensions,
parseMode,
)
if err != nil {
return nil, err
}
// Step 3: Process each rule in parallel
result := &ConfigProcessingResult{
RuleResults: make([]RuleResult, len(config.Rules)),
HasFailures: false,
FullTree: fullTree,
}
// Validate package.json exists for all rule paths before parallel processing
missingPackageJsonResults := make([]bool, len(config.Rules))
for i, rule := range config.Rules {
missingPackageJsonResults[i] = validateRulePathPackageJson(rule.Path, cwd)
}
var wg sync.WaitGroup
var mu sync.Mutex
for i, rule := range config.Rules {
wg.Add(1)
go func(ruleIndex int, currentRule Rule) {
defer wg.Done()
// Step 3a: Filter files for this rule
ruleFiles, ruleTree := filterFilesForRule(fullTree, currentRule.Path, cwd, currentRule.FollowMonorepoPackages, resolverManager)
// Step 3b: Execute enabled checks in parallel
ruleResult := processRuleChecks(
currentRule,
ruleFiles,
ruleTree,
fullTree,
resolverManager,
cwd,
fix,
)
// Set the missing package.json flag
ruleResult.MissingPackageJson = missingPackageJsonResults[ruleIndex]
// Check for failures and update result
hasFailures := len(ruleResult.CircularDependencies) > 0 ||
len(ruleResult.OrphanFiles) > 0 ||
len(ruleResult.ModuleBoundaryViolations) > 0 ||
len(ruleResult.UnusedNodeModules) > 0 ||
len(ruleResult.MissingNodeModules) > 0 ||
len(ruleResult.ImportConventionViolations) > 0 ||
len(ruleResult.UnusedExports) > 0 ||
len(ruleResult.UnresolvedImports) > 0 ||
len(ruleResult.RestrictedDevDependenciesUsageViolations) > 0 ||
len(ruleResult.RestrictedImportsViolations) > 0
mu.Lock()
result.RuleResults[ruleIndex] = ruleResult
if hasFailures {
result.HasFailures = true
}
mu.Unlock()
}(i, rule)
}
wg.Wait()
// Step 4: Apply fixes if requested
if fix {
changesByFile := make(map[string][]Change)
for i, ruleResult := range result.RuleResults {
ruleCfg := config.Rules[i]
isOrphanFixEnabled := false
for _, orphanCfg := range ruleCfg.getOrphanFilesDetections() {
if orphanCfg.Enabled && orphanCfg.Autofix {
isOrphanFixEnabled = true
break
}
}
// Create a set of orphan files to be deleted by this rule to avoid content fixes on them
orphanFilesToDelete := make(map[string]bool)
if isOrphanFixEnabled {
for _, orphan := range ruleResult.OrphanFilesAutofixable {
orphanFilesToDelete[orphan] = true
}
}
// Handle import convention and unused exports fixes as before
for _, v := range ruleResult.ImportConventionViolations {
if orphanFilesToDelete[v.FilePath] {
continue
}
if v.Fix != nil {
changesByFile[v.FilePath] = append(changesByFile[v.FilePath], *v.Fix)
result.FixedImportsCount++
} else if v.ViolationType == "should-be-aliased" {
result.UnfixableAliasingCount++
}
}
for _, v := range ruleResult.UnusedExports {
if orphanFilesToDelete[v.FilePath] {
continue
}
if v.Fix != nil {
changesByFile[v.FilePath] = append(changesByFile[v.FilePath], *v.Fix)
result.FixedImportsCount++
}
}
// Handle orphan files autofix: delete files when configured
if isOrphanFixEnabled {
for _, orphan := range ruleResult.OrphanFilesAutofixable {
osPath := DenormalizePathForOS(orphan)
if !filepath.IsAbs(osPath) {
osPath = filepath.Join(cwd, osPath)
}
if err := os.Remove(osPath); err != nil {
return result, fmt.Errorf("failed to remove orphan file '%s': %w", osPath, err)
}
result.DeletedFilesCount++
}
}
}
if len(changesByFile) > 0 {
if err := ApplyFileChanges(changesByFile); err != nil {
return result, fmt.Errorf("failed to apply autofixes: %w", err)
}
result.FixedFilesCount += len(changesByFile)
}
} else {
fixableIssuesCount := 0
for i, ruleResult := range result.RuleResults {
for _, v := range ruleResult.ImportConventionViolations {
if v.Fix != nil {
fixableIssuesCount++
}
}
for _, v := range ruleResult.UnusedExports {
if v.Fix != nil {
fixableIssuesCount++
}
}
// Add orphan files to fixable count if autofix is enabled for this rule
rule := config.Rules[i]
isOrphanFixEnabled := false
for _, orphanCfg := range rule.getOrphanFilesDetections() {
if orphanCfg.Enabled && orphanCfg.Autofix {
isOrphanFixEnabled = true
break
}
}
if isOrphanFixEnabled {
fixableIssuesCount += len(ruleResult.OrphanFilesAutofixable)
}
}
result.FixableIssuesCount = fixableIssuesCount
}
return result, nil
}