-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathtekton.go
81 lines (66 loc) · 1.78 KB
/
tekton.go
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
package main
import (
"bytes"
"io"
"os"
"path/filepath"
"regexp"
pipeline "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"github.com/tektoncd/pipeline/pkg/substitution"
"github.com/zregvart/tkn-fmt/format"
"sigs.k8s.io/kustomize/api/krusty"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/filesys"
"sigs.k8s.io/yaml"
)
func loadTask(path string) (*pipeline.Task, error) {
if filepath.Base(path) == "kustomization.yaml" {
return renderTask(filepath.Dir(path))
}
return readTask(path)
}
func readTask(path string) (*pipeline.Task, error) {
b, err := os.ReadFile(path) // #nosec G304 -- we want to read the file as Task, nothing to worry about here
if err != nil {
return nil, err
}
b = bytes.TrimLeft(b, "---\n")
task := pipeline.Task{}
return &task, yaml.Unmarshal(b, &task)
}
func renderTask(path string) (*pipeline.Task, error) {
opts := krusty.MakeDefaultOptions()
opts.LoadRestrictions = types.LoadRestrictionsNone
kustomize := krusty.MakeKustomizer(opts)
result, err := kustomize.Run(filesys.MakeFsOnDisk(), path)
if err != nil {
return nil, err
}
b, err := result.AsYaml()
if err != nil {
return nil, err
}
task := pipeline.Task{}
return &task, yaml.Unmarshal(b, &task)
}
func writeTask(task *pipeline.Task, writer io.Writer) error {
if c, ok := writer.(io.Closer); ok {
defer c.Close()
}
b, err := yaml.Marshal(task)
if err != nil {
return err
}
buf := bytes.NewBuffer(b)
return format.Format(buf, writer)
}
func applyReplacements(in string, replacements map[string]string) string {
return substitution.ApplyReplacements(in, replacements)
}
func applyRegexReplacements(in string, replacements map[*regexp.Regexp]string) string {
out := in
for ex, new := range replacements {
out = ex.ReplaceAllString(out, new)
}
return out
}