summaryrefslogtreecommitdiff
path: root/internal/resource/resource.go
blob: 1cf451ae362604fba3f5722f0a609e8037634aaf (plain)
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
package resource

import (
	"fmt"
	"log"
	"sort"
)

type Applier interface {
	Apply() error
}

type ApplierFunc func() error

func (f ApplierFunc) Apply() error {
	return f()
}

type Resource struct {
	Type      string
	Name      string
	applier   Applier
	dependsOn map[string]struct{}
}

func Register(type_, name string, apply Applier, deps ...string) Resource {
	dependsOn := make(map[string]struct{}, len(deps))
	for _, id := range deps {
		dependsOn[id] = struct{}{}
	}

	r := Resource{
		Type:      type_,
		Name:      name,
		applier:   apply,
		dependsOn: dependsOn,
	}

	if err := getRepository().register(r); err != nil {
		log.Fatalf("resource registration failed: %v", err)
	}

	return r
}

func (r Resource) String() string {
	return r.ID()
}

func (r Resource) ID() string {
	return fmt.Sprintf("%s[%s]", r.Type, r.Name)
}

// Dependencies returns this resource's own ID. It lets a single Resource be
// used as a DependsOn target, mirroring Multi.Dependencies.
func (r Resource) Dependencies() []string {
	return []string{r.ID()}
}

// sortedDependsOn returns the IDs this resource depends on, sorted for stable
// and readable log output.
func (r Resource) sortedDependsOn() []string {
	ids := make([]string, 0, len(r.dependsOn))
	for id := range r.dependsOn {
		ids = append(ids, id)
	}
	sort.Strings(ids)
	return ids
}

func (r Resource) Apply() error {
	return r.applier.Apply()
}