File: utils.go

package info (click to toggle)
golang-k8s-sigs-kustomize-api 0.20.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,768 kB
  • sloc: makefile: 206; sh: 67
file content (240 lines) | stat: -rw-r--r-- 6,099 bytes parent folder | download | duplicates (2)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package utils

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"time"

	"sigs.k8s.io/kustomize/api/konfig"
	"sigs.k8s.io/kustomize/api/resmap"
	"sigs.k8s.io/kustomize/api/resource"
	"sigs.k8s.io/kustomize/api/types"
	"sigs.k8s.io/kustomize/kyaml/filesys"
	"sigs.k8s.io/yaml"
)

const (
	idAnnotation       = "kustomize.config.k8s.io/id"
	HashAnnotation     = "kustomize.config.k8s.io/needs-hash"
	BehaviorAnnotation = "kustomize.config.k8s.io/behavior"
)

func GoBin() string {
	return filepath.Join(runtime.GOROOT(), "bin", "go")
}

// DeterminePluginSrcRoot guesses where the user
// has her ${g}/${v}/$lower(${k})/${k}.go files.
func DeterminePluginSrcRoot(fSys filesys.FileSystem) (string, error) {
	return konfig.FirstDirThatExistsElseError(
		"plugin src root", fSys, []konfig.NotedFunc{
			{
				Note: "relative to unit test",
				F: func() string {
					return filepath.Clean(
						filepath.Join(
							os.Getenv("PWD"),
							"..", "..",
							konfig.RelPluginHome))
				},
			},
			{
				Note: "relative to unit test (internal pkg)",
				F: func() string {
					return filepath.Clean(
						filepath.Join(
							os.Getenv("PWD"),
							"..", "..", "..", "..",
							konfig.RelPluginHome))
				},
			},
			{
				Note: "relative to api package",
				F: func() string {
					return filepath.Clean(
						filepath.Join(
							os.Getenv("PWD"),
							"..", "..", "..",
							konfig.RelPluginHome))
				},
			},
			{
				Note: "old style $GOPATH",
				F: func() string {
					return filepath.Join(
						os.Getenv("GOPATH"),
						"src", konfig.DomainName,
						konfig.ProgramName, konfig.RelPluginHome)
				},
			},
			{
				Note: "HOME with literal 'gopath'",
				F: func() string {
					return filepath.Join(
						konfig.HomeDir(), "gopath",
						"src", konfig.DomainName,
						konfig.ProgramName, konfig.RelPluginHome)
				},
			},
			{
				Note: "home directory",
				F: func() string {
					return filepath.Join(
						konfig.HomeDir(), konfig.DomainName,
						konfig.ProgramName, konfig.RelPluginHome)
				},
			},
		})
}

// FileYoungerThan returns true if the file both exists and has an
// age is <= the Duration argument.
func FileYoungerThan(path string, d time.Duration) bool {
	fi, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return time.Since(fi.ModTime()) <= d
}

// FileModifiedAfter returns true if the file both exists and was
// modified after the given time..
func FileModifiedAfter(path string, t time.Time) bool {
	fi, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return fi.ModTime().After(t)
}

func FileExists(path string) bool {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// GetResMapWithIDAnnotation returns a new copy of the given ResMap with the ResIds annotated in each Resource
func GetResMapWithIDAnnotation(rm resmap.ResMap) (resmap.ResMap, error) {
	inputRM := rm.DeepCopy()
	for _, r := range inputRM.Resources() {
		idString, err := yaml.Marshal(r.CurId())
		if err != nil {
			return nil, err
		}
		annotations := r.GetAnnotations()
		annotations[idAnnotation] = string(idString)
		if err = r.SetAnnotations(annotations); err != nil {
			return nil, err
		}
	}
	return inputRM, nil
}

// UpdateResMapValues updates the Resource value in the given ResMap
// with the emitted Resource values in output.
func UpdateResMapValues(pluginName string, h *resmap.PluginHelpers, output []byte, rm resmap.ResMap) error {
	mapFactory := h.ResmapFactory()
	resFactory := mapFactory.RF()
	resources, err := resFactory.SliceFromBytes(output)
	if err != nil {
		return err
	}
	// Don't use resources here, or error message will be unfriendly to plugin builders
	newMap, err := mapFactory.NewResMapFromBytes([]byte{})
	if err != nil {
		return err
	}

	for _, r := range resources {
		// stale--not manipulated by plugin transformers
		if err = removeIDAnnotation(r); err != nil {
			return err
		}

		// Add to the new map, checking for duplicates
		if err := newMap.Append(r); err != nil {
			prettyID, err := json.Marshal(r.CurId())
			if err != nil {
				prettyID = []byte(r.CurId().String())
			}
			return fmt.Errorf("plugin %s generated duplicate resource: %s", pluginName, prettyID)
		}

		// Add to or update the old map
		oldIdx, err := rm.GetIndexOfCurrentId(r.CurId())
		if err != nil {
			return err
		}
		if oldIdx != -1 {
			rm.GetByIndex(oldIdx).ResetRNode(r)
		} else {
			if err := rm.Append(r); err != nil {
				return err
			}
		}
	}

	// Remove items the transformer deleted from the old map
	for _, id := range rm.AllIds() {
		newIdx, _ := newMap.GetIndexOfCurrentId(id)
		if newIdx == -1 {
			if err = rm.Remove(id); err != nil {
				return err
			}
		}
	}

	return nil
}

func removeIDAnnotation(r *resource.Resource) error {
	// remove the annotation set by Kustomize to track the resource
	annotations := r.GetAnnotations()
	delete(annotations, idAnnotation)
	return r.SetAnnotations(annotations)
}

// UpdateResourceOptions updates the generator options for each resource in the
// given ResMap based on plugin provided annotations.
func UpdateResourceOptions(rm resmap.ResMap) (resmap.ResMap, error) {
	for _, r := range rm.Resources() {
		// Disable name hashing by default and require plugin to explicitly
		// request it for each resource.
		annotations := r.GetAnnotations()
		behavior := annotations[BehaviorAnnotation]
		var needsHash bool
		if val, ok := annotations[HashAnnotation]; ok {
			b, err := strconv.ParseBool(val)
			if err != nil {
				return nil, fmt.Errorf(
					"the annotation %q contains an invalid value (%q)",
					HashAnnotation, val)
			}
			needsHash = b
		}
		delete(annotations, HashAnnotation)
		delete(annotations, BehaviorAnnotation)
		if err := r.SetAnnotations(annotations); err != nil {
			return nil, err
		}
		if needsHash {
			r.EnableHashSuffix()
		}
		r.SetBehavior(types.NewGenerationBehavior(behavior))
	}
	return rm, nil
}