|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package components |
| 5 | + |
| 6 | +import ( |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "log/slog" |
| 10 | + "path" |
| 11 | + "path/filepath" |
| 12 | + "slices" |
| 13 | + "strings" |
| 14 | + |
| 15 | + "github.com/bmatcuk/doublestar/v4" |
| 16 | + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev" |
| 17 | + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" |
| 18 | + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" |
| 19 | +) |
| 20 | + |
| 21 | +// patternDiscoveredComponent captures the result of expanding a single |
| 22 | +// project-level [projectconfig.ComponentConfig.OverlayFiles] entry that |
| 23 | +// contains the `{component}` placeholder. |
| 24 | +type patternDiscoveredComponent struct { |
| 25 | + // Name of the discovered component (the captured {component} segment). |
| 26 | + Name string |
| 27 | + // ReferenceDir is the absolute directory the pattern captured for this |
| 28 | + // component (i.e. the prefix directory + captured name). Used as the |
| 29 | + // component's reference directory for downstream operations. |
| 30 | + ReferenceDir string |
| 31 | + // OverlayFiles is the deduplicated, sorted list of absolute overlay file |
| 32 | + // paths matched by the winning pattern for this component. |
| 33 | + OverlayFiles []string |
| 34 | + // SourcePattern is the exact entry string that produced this match, used |
| 35 | + // in shadow-lint diagnostics. |
| 36 | + SourcePattern string |
| 37 | +} |
| 38 | + |
| 39 | +// discoverComponentsFromPatterns walks the project-level |
| 40 | +// default-component-config, expands every 'overlay-files' entry that contains |
| 41 | +// the `{component}` placeholder, and returns the resulting pattern-discovered |
| 42 | +// components. Two entries at project scope producing the same component name |
| 43 | +// is a hard error. |
| 44 | +// |
| 45 | +// The caller is responsible for further precedence against explicitly-declared |
| 46 | +// components (that override happens at the resolver layer; see |
| 47 | +// [Resolver.patternDiscoveredComponents]). |
| 48 | +func discoverComponentsFromPatterns(env *azldev.Env) (map[string]*patternDiscoveredComponent, error) { |
| 49 | + result := make(map[string]*patternDiscoveredComponent) |
| 50 | + |
| 51 | + config := env.Config() |
| 52 | + if config == nil { |
| 53 | + return result, nil |
| 54 | + } |
| 55 | + |
| 56 | + var patterns []string |
| 57 | + |
| 58 | + for _, entry := range config.DefaultComponentConfig.OverlayFiles { |
| 59 | + if strings.Contains(entry, projectconfig.OverlayFilesComponentPlaceholder) { |
| 60 | + patterns = append(patterns, entry) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if len(patterns) == 0 { |
| 65 | + return result, nil |
| 66 | + } |
| 67 | + |
| 68 | + for _, pattern := range patterns { |
| 69 | + byName, err := expandSinglePattern(env, pattern) |
| 70 | + if err != nil { |
| 71 | + return nil, fmt.Errorf("project 'overlay-files': %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + for name, match := range byName { |
| 75 | + if existing, ok := result[name]; ok { |
| 76 | + return nil, fmt.Errorf( |
| 77 | + "%w: component %#q is discovered by both %#q and %#q; "+ |
| 78 | + "restrict one of the patterns or rename one of the directories", |
| 79 | + ErrPatternDiscoveryCollision, name, existing.SourcePattern, match.SourcePattern, |
| 80 | + ) |
| 81 | + } |
| 82 | + |
| 83 | + result[name] = match |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return result, nil |
| 88 | +} |
| 89 | + |
| 90 | +// expandSinglePattern expands a single validated pattern and groups matched |
| 91 | +// files by captured component name. |
| 92 | +func expandSinglePattern(env *azldev.Env, pattern string) (map[string]*patternDiscoveredComponent, error) { |
| 93 | + prefix, suffix := projectconfig.SplitOverlayFilesPlaceholder(pattern) |
| 94 | + |
| 95 | + // Substitute a single-segment wildcard for {component} to build the actual |
| 96 | + // glob. Because {component} is validated as a whole path segment (see |
| 97 | + // ConfigFile.Validate), replacing it with "*" produces a well-formed |
| 98 | + // doublestar pattern that captures exactly one path segment. |
| 99 | + globPattern := prefix + "*" + suffix |
| 100 | + |
| 101 | + // Ignore IO errors here, mirroring findComponentGroupSpecPaths: we may |
| 102 | + // legitimately hit unreadable subtrees under the project root. |
| 103 | + matches, err := fileutils.Glob(env.FS(), globPattern, doublestar.WithFilesOnly()) |
| 104 | + if err != nil { |
| 105 | + return nil, fmt.Errorf("failed to expand pattern %#q:\n%w", pattern, err) |
| 106 | + } |
| 107 | + |
| 108 | + byName := make(map[string]*patternDiscoveredComponent) |
| 109 | + |
| 110 | + for _, match := range matches { |
| 111 | + name, referenceDir, err := extractCapturedName(pattern, prefix, match) |
| 112 | + if err != nil { |
| 113 | + // Skip matches we can't parse (should not happen with a validated |
| 114 | + // pattern, but guard anyway). |
| 115 | + slog.Debug("pattern-discovery: skipping unparseable match", |
| 116 | + "pattern", pattern, "match", match, "err", err) |
| 117 | + |
| 118 | + continue |
| 119 | + } |
| 120 | + |
| 121 | + bucket, ok := byName[name] |
| 122 | + if !ok { |
| 123 | + bucket = &patternDiscoveredComponent{ |
| 124 | + Name: name, |
| 125 | + ReferenceDir: referenceDir, |
| 126 | + SourcePattern: pattern, |
| 127 | + } |
| 128 | + byName[name] = bucket |
| 129 | + } |
| 130 | + |
| 131 | + bucket.OverlayFiles = append(bucket.OverlayFiles, match) |
| 132 | + } |
| 133 | + |
| 134 | + // Sort the overlay-files list per component (filename first, then full path). |
| 135 | + for _, bucket := range byName { |
| 136 | + slices.SortFunc(bucket.OverlayFiles, func(left, right string) int { |
| 137 | + if result := strings.Compare(filepath.Base(left), filepath.Base(right)); result != 0 { |
| 138 | + return result |
| 139 | + } |
| 140 | + |
| 141 | + return strings.Compare(left, right) |
| 142 | + }) |
| 143 | + } |
| 144 | + |
| 145 | + return byName, nil |
| 146 | +} |
| 147 | + |
| 148 | +// extractCapturedName strips prefix from match and returns the first path |
| 149 | +// segment (the captured component name) together with the concrete directory |
| 150 | +// that captured segment lives in. The returned ReferenceDir is the natural |
| 151 | +// per-component anchor for downstream operations. |
| 152 | +func extractCapturedName(pattern, prefix, match string) (name, referenceDir string, err error) { |
| 153 | + rel := match |
| 154 | + if prefix != "" { |
| 155 | + if !strings.HasPrefix(match, prefix) { |
| 156 | + return "", "", fmt.Errorf( |
| 157 | + "match %#q does not start with expected prefix %#q for pattern %#q", |
| 158 | + match, prefix, pattern, |
| 159 | + ) |
| 160 | + } |
| 161 | + |
| 162 | + rel = match[len(prefix):] |
| 163 | + } |
| 164 | + |
| 165 | + // The captured segment is everything up to (but not including) the first |
| 166 | + // path separator in the residual, or the entire residual if there is no |
| 167 | + // suffix. Patterns are validated to use '/' only. |
| 168 | + sep := strings.IndexByte(rel, '/') |
| 169 | + if sep < 0 { |
| 170 | + name = rel |
| 171 | + } else { |
| 172 | + name = rel[:sep] |
| 173 | + } |
| 174 | + |
| 175 | + if name == "" { |
| 176 | + return "", "", fmt.Errorf( |
| 177 | + "empty captured component name for match %#q against pattern %#q", |
| 178 | + match, pattern, |
| 179 | + ) |
| 180 | + } |
| 181 | + |
| 182 | + // The reference dir is the prefix + captured segment (no trailing separator). |
| 183 | + // Use path.Clean (POSIX '/') rather than filepath.Clean so ReferenceDir stays |
| 184 | + // consistent with the placeholder contract, which validates and operates on |
| 185 | + // POSIX-style separators only (filepath.Clean would emit '\' on Windows). |
| 186 | + referenceDir = path.Clean(prefix + name) |
| 187 | + |
| 188 | + return name, referenceDir, nil |
| 189 | +} |
| 190 | + |
| 191 | +// logShadowedByDeclaration emits a warning when an explicit component |
| 192 | +// declaration overrides pattern-discovered overlay files for the same name. |
| 193 | +func logShadowedByDeclaration(shadowed *patternDiscoveredComponent) { |
| 194 | + slog.Warn( |
| 195 | + "project 'overlay-files' pattern match shadowed by explicit component declaration; overlay files will not be applied", |
| 196 | + "component", shadowed.Name, |
| 197 | + "shadowed_pattern", shadowed.SourcePattern, |
| 198 | + "shadowed_files", shadowed.OverlayFiles, |
| 199 | + ) |
| 200 | +} |
| 201 | + |
| 202 | +// ErrPatternDiscoveryCollision wraps project-scope pattern collision errors so |
| 203 | +// tests can assert on them. |
| 204 | +var ErrPatternDiscoveryCollision = errors.New("project 'overlay-files' pattern collision") |
0 commit comments