builder.go 1.65 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
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
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package image

import (
	"fmt"
	"strings"

	"github.com/opencontainers/runtime-spec/specs-go"
)

type builder struct {
	env    map[string]string
	mounts []specs.Mount
}

// New creates a new DTK image from the input options.
func New(opt ...Option) (DTK, error) {
	b := &builder{}
	for _, o := range opt {
		if err := o(b); err != nil {
			return DTK{}, err
		}
	}
	if b.env == nil {
		b.env = make(map[string]string)
	}

	return b.build()
}

// build creates a DTK image from the builder.
func (b builder) build() (DTK, error) {
	c := DTK{
		env:    b.env,
		mounts: b.mounts,
	}
	return c, nil
}

// Option is a functional option for creating a DTK image.
type Option func(*builder) error

// WithEnv sets the environment variables to use when creating the DTK image.
// Note that this also overwrites the values set with WithEnvMap.
func WithEnv(envs []string) Option {
	return func(b *builder) error {
		envmap := make(map[string]string)
		for _, env := range envs {
			parts := strings.SplitN(env, "=", 2)
			if len(parts) != 2 {
				return fmt.Errorf("invalid environment variables: %v", env)
			}
			envmap[parts[0]] = parts[1]
		}
		return WithEnvMap(envmap)(b)
	}
}

// WithEnvMap sets the environment variable map to use when creating the DTK image.
// Note that this also overwrites the values set with WithEnv.
func WithEnvMap(env map[string]string) Option {
	return func(b *builder) error {
		b.env = env
		return nil
	}
}

// WithMounts sets the mounts associated with the DTK image.
func WithMounts(mounts []specs.Mount) Option {
	return func(b *builder) error {
		b.mounts = mounts
		return nil
	}
}