-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
addreplacement.go
82 lines (72 loc) · 2.21 KB
/
addreplacement.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
82
// Copyright 2023 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package add
import (
"errors"
"fmt"
"github.com/spf13/cobra"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kustomize/v5/commands/internal/kustfile"
"sigs.k8s.io/kustomize/kyaml/filesys"
)
type addReplacementOptions struct {
Replacement types.ReplacementField
}
func newCmdAddReplacement(fSys filesys.FileSystem) *cobra.Command {
var o addReplacementOptions
o.Replacement.Source = &types.SourceSelector{}
o.Replacement.Targets = append(o.Replacement.Targets, &types.TargetSelector{})
cmd := &cobra.Command{
Use: "replacement",
Short: "add an item to replacement field",
Long: `this command will add an item to replacement field in the kustomization file.
the item will be:
- be either a file, or an inline string
`,
Example: `
# Adds a replacement file to the kustomization file
kustomize edit add replacement --path {filepath}
`,
RunE: func(cmd *cobra.Command, args []string) error {
err := o.Validate()
if err != nil {
return err
}
return o.RunAddReplacement(fSys)
},
}
cmd.Flags().StringVar(&o.Replacement.Path, "path", "", "Path to the replacement file.")
return cmd
}
// Validate validate add replacement command
func (o *addReplacementOptions) Validate() error {
if o.Replacement.Path == "" {
return errors.New("must provide path to add replacement")
}
return nil
}
// RunAddReplacement runs addReplacement command
func (o *addReplacementOptions) RunAddReplacement(fSys filesys.FileSystem) error {
mf, err := kustfile.NewKustomizationFile(fSys)
if err != nil {
return fmt.Errorf("failed to load kustomization file: %w", err)
}
m, err := mf.Read()
if err != nil {
return fmt.Errorf("failed to read kustomization file: %w", err)
}
if o.Replacement.Targets != nil {
o.Replacement.Targets = nil
}
if o.Replacement.Source != nil {
o.Replacement.Source = nil
}
for _, r := range m.Replacements {
if len(r.Path) > 0 && r.Path == o.Replacement.Path {
return fmt.Errorf("replacement for path %q already in %s file", r.Path, konfig.DefaultKustomizationFileName())
}
}
m.Replacements = append(m.Replacements, o.Replacement)
return mf.Write(m)
}