| 221 | } |
| 222 | |
| 223 | func (s *Spec) compileFeatures(fs billy.Filesystem, devcontainerDir, scratchDir string, containerUser, remoteUser, dockerfileContent string, useBuildContexts bool) (string, map[string]string, error) { |
| 224 | // If there are no features, we don't need to do anything! |
| 225 | if len(s.Features) == 0 { |
| 226 | return dockerfileContent, nil, nil |
| 227 | } |
| 228 | |
| 229 | featuresDir := filepath.Join(scratchDir, "features") |
| 230 | err := fs.MkdirAll(featuresDir, 0o644) |
| 231 | if err != nil { |
| 232 | return "", nil, fmt.Errorf("create features directory: %w", err) |
| 233 | } |
| 234 | featureDirectives := []string{} |
| 235 | featureContexts := make(map[string]string) |
| 236 | |
| 237 | // TODO: Respect the installation order outlined by the spec: |
| 238 | // https://containers.dev/implementors/features/#installation-order |
| 239 | featureOrder := []string{} |
| 240 | for featureRef := range s.Features { |
| 241 | featureOrder = append(featureOrder, featureRef) |
| 242 | } |
| 243 | // It's critical we sort features prior to compilation so the Dockerfile |
| 244 | // is deterministic which allows for caching. |
| 245 | sort.Strings(featureOrder) |
| 246 | |
| 247 | var lines []string |
| 248 | for _, featureRefRaw := range featureOrder { |
| 249 | var ( |
| 250 | featureRef string |
| 251 | ok bool |
| 252 | ) |
| 253 | if _, featureRef, ok = strings.Cut(featureRefRaw, "./"); !ok { |
| 254 | featureRefParsed, err := name.ParseReference(featureRefRaw) |
| 255 | if err != nil { |
| 256 | return "", nil, fmt.Errorf("parse feature ref %s: %w", featureRefRaw, err) |
| 257 | } |
| 258 | featureRef = featureRefParsed.Context().Name() |
| 259 | } |
| 260 | |
| 261 | featureOpts := map[string]any{} |
| 262 | switch t := s.Features[featureRefRaw].(type) { |
| 263 | case string: |
| 264 | // As a shorthand, the value of the `features`` property can be provided as a |
| 265 | // single string. This string is mapped to an option called version. |
| 266 | // https://containers.dev/implementors/features/#devcontainer-json-properties |
| 267 | featureOpts["version"] = t |
| 268 | case map[string]any: |
| 269 | featureOpts = t |
| 270 | } |
| 271 | |
| 272 | // It's important for caching that this directory is static. |
| 273 | // If it changes on each run then the container will not be cached. |
| 274 | // |
| 275 | // devcontainers/cli has a very complex method of computing the feature |
| 276 | // name from the feature reference. We're just going to hash it for simplicity. |
| 277 | featureSha := md5.Sum([]byte(featureRefRaw)) |
| 278 | featureName := filepath.Base(featureRef) |
| 279 | featureDir := filepath.Join(featuresDir, fmt.Sprintf("%s-%x", featureName, featureSha[:4])) |
| 280 | if err := fs.MkdirAll(featureDir, 0o644); err != nil { |