File: mutate.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (80 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download
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
// Copyright 2023 Sylabs Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

package mutate

import (
	"errors"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/types"
)

type Mutation func(*image) error

var errInvalidLayerIndex = errors.New("invalid layer index")

// SetLayer sets the layer at index i to l.
func SetLayer(i int, l v1.Layer) Mutation {
	return func(img *image) error {
		if i >= len(img.overrides) {
			return errInvalidLayerIndex
		}

		img.overrides[i] = l

		return nil
	}
}

// ReplaceLayers replaces all layers in the image with l. The layer is annotated with the specified
// values.
func ReplaceLayers(l v1.Layer) Mutation {
	return func(img *image) error {
		img.overrides = []v1.Layer{l}
		return nil
	}
}

// SetHistory replaces the history in an image with the specified entry.
func SetHistory(history v1.History) Mutation {
	return func(img *image) error {
		img.history = &history
		return nil
	}
}

// SetConfig replaces the config with the specified raw content of type t.
func SetConfig(configFile any, configType types.MediaType) Mutation {
	return func(img *image) error {
		img.configFileOverride = configFile
		img.configTypeOverride = configType
		return nil
	}
}

// Apply performs the specified mutation(s) to a base image, returning the resulting image.
func Apply(base v1.Image, ms ...Mutation) (v1.Image, error) {
	if len(ms) == 0 {
		return base, nil
	}

	layers, err := base.Layers()
	if err != nil {
		return nil, err
	}

	img := image{
		base:      base,
		overrides: make([]v1.Layer, len(layers)),
	}

	for _, m := range ms {
		if err := m(&img); err != nil {
			return nil, err
		}
	}

	return &img, nil
}