manifest becomes kustomization

This commit is contained in:
Jeffrey Regan
2018-04-12 13:31:52 -07:00
parent 5c684d789c
commit 8f0a04c84d
32 changed files with 289 additions and 287 deletions

View File

@@ -35,9 +35,9 @@ type Application interface {
Resources() (resource.ResourceCollection, error) Resources() (resource.ResourceCollection, error)
// SemiResources computes and returns the resources without name hash and name reference for the app // SemiResources computes and returns the resources without name hash and name reference for the app
SemiResources() (resource.ResourceCollection, error) SemiResources() (resource.ResourceCollection, error)
// RawResources computes and returns the raw resources from the kustomize config file. // RawResources computes and returns the raw resources from the kustomization file.
// It contains resources from // It contains resources from
// 1) untransformed resources from current kustomize config file // 1) untransformed resources from current kustomization file
// 2) transformed resources from sub packages // 2) transformed resources from sub packages
RawResources() (resource.ResourceCollection, error) RawResources() (resource.ResourceCollection, error)
} }
@@ -46,27 +46,26 @@ var _ Application = &applicationImpl{}
// Private implementation of the Application interface // Private implementation of the Application interface
type applicationImpl struct { type applicationImpl struct {
manifest *types.Manifest kustomization *types.Kustomization
loader loader.Loader loader loader.Loader
} }
// NewApp parses the kustomize config file at the path using the loader. // NewApp parses the kustomization file at the path using the loader.
func New(loader loader.Loader) (Application, error) { func New(loader loader.Loader) (Application, error) {
// load the kustomize config file using the loader content, err := loader.Load(constants.KustomizationFileName)
manifestBytes, err := loader.Load(constants.KustomizeFileName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var m types.Manifest var m types.Kustomization
err = unmarshal(manifestBytes, &m) err = unmarshal(content, &m)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &applicationImpl{manifest: &m, loader: loader}, nil return &applicationImpl{kustomization: &m, loader: loader}, nil
} }
// Resources computes and returns the resources from the kustomize config file. // Resources computes and returns the resources from the kustomization file.
// The namehashing for configmap/secrets and resolving name reference is only done // The namehashing for configmap/secrets and resolving name reference is only done
// in the most top overlay once at the end of getting resources. // in the most top overlay once at the end of getting resources.
func (a *applicationImpl) Resources() (resource.ResourceCollection, error) { func (a *applicationImpl) Resources() (resource.ResourceCollection, error) {
@@ -87,17 +86,17 @@ func (a *applicationImpl) Resources() (resource.ResourceCollection, error) {
// SemiResources computes and returns the resources without name hash and name reference for the app // SemiResources computes and returns the resources without name hash and name reference for the app
func (a *applicationImpl) SemiResources() (resource.ResourceCollection, error) { func (a *applicationImpl) SemiResources() (resource.ResourceCollection, error) {
errs := &interror.ManifestErrors{} errs := &interror.KustomizationErrors{}
raw, err := a.rawResources() raw, err := a.rawResources()
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
} }
cms, err := resource.NewFromConfigMaps(a.loader, a.manifest.ConfigMapGenerator) cms, err := resource.NewFromConfigMaps(a.loader, a.kustomization.ConfigMapGenerator)
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
} }
secrets, err := resource.NewFromSecretGenerators(a.loader.Root(), a.manifest.SecretGenerator) secrets, err := resource.NewFromSecretGenerators(a.loader.Root(), a.kustomization.SecretGenerator)
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
} }
@@ -111,7 +110,7 @@ func (a *applicationImpl) SemiResources() (resource.ResourceCollection, error) {
return nil, err return nil, err
} }
patches, err := resource.NewFromPatches(a.loader, a.manifest.Patches) patches, err := resource.NewFromPatches(a.loader, a.kustomization.Patches)
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
} }
@@ -132,7 +131,7 @@ func (a *applicationImpl) SemiResources() (resource.ResourceCollection, error) {
return allRes, nil return allRes, nil
} }
// RawResources computes and returns the raw resources from the kustomize config file. // RawResources computes and returns the raw resources from the kustomization file.
// The namehashing for configmap/secrets and resolving name reference is only done // The namehashing for configmap/secrets and resolving name reference is only done
// in the most top overlay once at the end of getting resources. // in the most top overlay once at the end of getting resources.
func (a *applicationImpl) RawResources() (resource.ResourceCollection, error) { func (a *applicationImpl) RawResources() (resource.ResourceCollection, error) {
@@ -153,7 +152,7 @@ func (a *applicationImpl) RawResources() (resource.ResourceCollection, error) {
func (a *applicationImpl) rawResources() (resource.ResourceCollection, error) { func (a *applicationImpl) rawResources() (resource.ResourceCollection, error) {
subAppResources, errs := a.subAppResources() subAppResources, errs := a.subAppResources()
resources, err := resource.NewFromResources(a.loader, a.manifest.Resources) resources, err := resource.NewFromResources(a.loader, a.kustomization.Resources)
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
} }
@@ -165,10 +164,10 @@ func (a *applicationImpl) rawResources() (resource.ResourceCollection, error) {
return resource.Merge(resources, subAppResources) return resource.Merge(resources, subAppResources)
} }
func (a *applicationImpl) subAppResources() (resource.ResourceCollection, *interror.ManifestErrors) { func (a *applicationImpl) subAppResources() (resource.ResourceCollection, *interror.KustomizationErrors) {
sliceOfSubAppResources := []resource.ResourceCollection{} sliceOfSubAppResources := []resource.ResourceCollection{}
errs := &interror.ManifestErrors{} errs := &interror.KustomizationErrors{}
for _, pkgPath := range a.manifest.Bases { for _, pkgPath := range a.kustomization.Bases {
subloader, err := a.loader.New(pkgPath) subloader, err := a.loader.New(pkgPath)
if err != nil { if err != nil {
errs.Append(err) errs.Append(err)
@@ -208,19 +207,19 @@ func (a *applicationImpl) getTransformer(patches []*resource.Resource) (transfor
} }
ts = append(ts, ot) ts = append(ts, ot)
npt, err := transformers.NewDefaultingNamePrefixTransformer(string(a.manifest.NamePrefix)) npt, err := transformers.NewDefaultingNamePrefixTransformer(string(a.kustomization.NamePrefix))
if err != nil { if err != nil {
return nil, err return nil, err
} }
ts = append(ts, npt) ts = append(ts, npt)
lt, err := transformers.NewDefaultingLabelsMapTransformer(a.manifest.ObjectLabels) lt, err := transformers.NewDefaultingLabelsMapTransformer(a.kustomization.ObjectLabels)
if err != nil { if err != nil {
return nil, err return nil, err
} }
ts = append(ts, lt) ts = append(ts, lt)
at, err := transformers.NewDefaultingAnnotationsMapTransformer(a.manifest.ObjectAnnotations) at, err := transformers.NewDefaultingAnnotationsMapTransformer(a.kustomization.ObjectAnnotations)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -32,7 +32,7 @@ import (
) )
func setupTest(t *testing.T) loader.Loader { func setupTest(t *testing.T) loader.Loader {
manifestContent := []byte(`kustomizationName: nginx-app kustomizationContent := []byte(`kustomizationName: nginx-app
namePrefix: foo- namePrefix: foo-
objectLabels: objectLabels:
app: nginx app: nginx
@@ -59,7 +59,7 @@ metadata:
`) `)
loader := loadertest.NewFakeLoader("/testpath") loader := loadertest.NewFakeLoader("/testpath")
err := loader.AddFile("/testpath/kustomize.yaml", manifestContent) err := loader.AddFile("/testpath/kustomize.yaml", kustomizationContent)
if err != nil { if err != nil {
t.Fatalf("Failed to setup fake loader.") t.Fatalf("Failed to setup fake loader.")
} }

View File

@@ -31,14 +31,13 @@ type addResourceOptions struct {
resourceFilePath string resourceFilePath string
} }
// newCmdAddResource adds the name of a file containing a resource to the manifest. // newCmdAddResource adds the name of a file containing a resource to the kustomization file.
func newCmdAddResource(out, errOut io.Writer, fsys fs.FileSystem) *cobra.Command { func newCmdAddResource(out, errOut io.Writer, fsys fs.FileSystem) *cobra.Command {
var o addResourceOptions var o addResourceOptions
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "resource", Use: "resource",
Short: "Add the name of a file containing a resource to the manifest.", Short: "Add the name of a file containing a resource to the kustomization file.",
Long: "Add the name of a file containing a resource to the manifest.",
Example: ` Example: `
add resource {filepath}`, add resource {filepath}`,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@@ -86,7 +85,7 @@ func (o *addResourceOptions) RunAddResource(out, errOut io.Writer, fsys fs.FileS
return err return err
} }
mf, err := newManifestFile(constants.KustomizeFileName, fsys) mf, err := newKustomizationFile(constants.KustomizationFileName, fsys)
if err != nil { if err != nil {
return err return err
} }
@@ -97,7 +96,7 @@ func (o *addResourceOptions) RunAddResource(out, errOut io.Writer, fsys fs.FileS
} }
if stringInSlice(o.resourceFilePath, m.Resources) { if stringInSlice(o.resourceFilePath, m.Resources) {
return fmt.Errorf("resource %s already in manifest", o.resourceFilePath) return fmt.Errorf("resource %s already in kustomization file", o.resourceFilePath)
} }
m.Resources = append(m.Resources, o.resourceFilePath) m.Resources = append(m.Resources, o.resourceFilePath)

View File

@@ -39,7 +39,7 @@ func TestAddResourceHappyPath(t *testing.T) {
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
fakeFS := fs.MakeFakeFS() fakeFS := fs.MakeFakeFS()
fakeFS.WriteFile(resourceFileName, []byte(resourceFileContent)) fakeFS.WriteFile(resourceFileName, []byte(resourceFileContent))
fakeFS.WriteFile(constants.KustomizeFileName, []byte(manifestTemplate)) fakeFS.WriteFile(constants.KustomizationFileName, []byte(kustomizationTemplate))
cmd := newCmdAddResource(buf, os.Stderr, fakeFS) cmd := newCmdAddResource(buf, os.Stderr, fakeFS)
args := []string{resourceFileName} args := []string{resourceFileName}
@@ -47,12 +47,12 @@ func TestAddResourceHappyPath(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("unexpected cmd error: %v", err) t.Errorf("unexpected cmd error: %v", err)
} }
content, err := fakeFS.ReadFile(constants.KustomizeFileName) content, err := fakeFS.ReadFile(constants.KustomizationFileName)
if err != nil { if err != nil {
t.Errorf("unexpected read error: %v", err) t.Errorf("unexpected read error: %v", err)
} }
if !strings.Contains(string(content), resourceFileName) { if !strings.Contains(string(content), resourceFileName) {
t.Errorf("expected resource name in manifest") t.Errorf("expected resource name in kustomization")
} }
} }
@@ -60,7 +60,7 @@ func TestAddResourceAlreadyThere(t *testing.T) {
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
fakeFS := fs.MakeFakeFS() fakeFS := fs.MakeFakeFS()
fakeFS.WriteFile(resourceFileName, []byte(resourceFileContent)) fakeFS.WriteFile(resourceFileName, []byte(resourceFileContent))
fakeFS.WriteFile(constants.KustomizeFileName, []byte(manifestTemplate)) fakeFS.WriteFile(constants.KustomizationFileName, []byte(kustomizationTemplate))
cmd := newCmdAddResource(buf, os.Stderr, fakeFS) cmd := newCmdAddResource(buf, os.Stderr, fakeFS)
args := []string{resourceFileName} args := []string{resourceFileName}
@@ -74,7 +74,7 @@ func TestAddResourceAlreadyThere(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("expected already there problem") t.Errorf("expected already there problem")
} }
if err.Error() != "resource "+resourceFileName+" already in manifest" { if err.Error() != "resource "+resourceFileName+" already in kustomization file" {
t.Errorf("unexpected error %v", err) t.Errorf("unexpected error %v", err)
} }
} }

View File

@@ -34,7 +34,7 @@ import (
) )
type buildOptions struct { type buildOptions struct {
manifestPath string kustomizationPath string
} }
// newCmdBuild creates a new build command. // newCmdBuild creates a new build command.
@@ -43,7 +43,7 @@ func newCmdBuild(out, errOut io.Writer, fs fs.FileSystem) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "build [path]", Use: "build [path]",
Short: "Print current configuration per contents of " + constants.KustomizeFileName, Short: "Print current configuration per contents of " + constants.KustomizationFileName,
Example: ` Example: `
# Use the kustomize.yaml file under somedir/ to generate a set of api resources. # Use the kustomize.yaml file under somedir/ to generate a set of api resources.
build somedir/`, build somedir/`,
@@ -66,13 +66,13 @@ func newCmdBuild(out, errOut io.Writer, fs fs.FileSystem) *cobra.Command {
// Validate validates build command. // Validate validates build command.
func (o *buildOptions) Validate(args []string) error { func (o *buildOptions) Validate(args []string) error {
if len(args) > 1 { if len(args) > 1 {
return errors.New("specify one path to manifest") return errors.New("specify one path to kustomization file")
} }
if len(args) == 0 { if len(args) == 0 {
o.manifestPath = "./" o.kustomizationPath = "./"
return nil return nil
} }
o.manifestPath = args[0] o.kustomizationPath = args[0]
return nil return nil
} }
@@ -80,7 +80,7 @@ func (o *buildOptions) Validate(args []string) error {
func (o *buildOptions) RunBuild(out, errOut io.Writer, fs fs.FileSystem) error { func (o *buildOptions) RunBuild(out, errOut io.Writer, fs fs.FileSystem) error {
l := loader.Init([]loader.SchemeLoader{loader.NewFileLoader(fs)}) l := loader.Init([]loader.SchemeLoader{loader.NewFileLoader(fs)})
absPath, err := filepath.Abs(o.manifestPath) absPath, err := filepath.Abs(o.kustomizationPath)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -50,7 +50,7 @@ func TestBuildValidate(t *testing.T) {
{"noargs", []string{}, "./", ""}, {"noargs", []string{}, "./", ""},
{"file", []string{"beans"}, "beans", ""}, {"file", []string{"beans"}, "beans", ""},
{"path", []string{"a/b/c"}, "a/b/c", ""}, {"path", []string{"a/b/c"}, "a/b/c", ""},
{"path", []string{"too", "many"}, "", "specify one path to manifest"}, {"path", []string{"too", "many"}, "", "specify one path to kustomization file"},
} }
for _, mycase := range cases { for _, mycase := range cases {
opts := buildOptions{} opts := buildOptions{}
@@ -68,8 +68,8 @@ func TestBuildValidate(t *testing.T) {
t.Errorf("%s: unknown error %v", mycase.name, e) t.Errorf("%s: unknown error %v", mycase.name, e)
continue continue
} }
if opts.manifestPath != mycase.path { if opts.kustomizationPath != mycase.path {
t.Errorf("%s: expected path '%s', got '%s'", mycase.name, mycase.path, opts.manifestPath) t.Errorf("%s: expected path '%s', got '%s'", mycase.name, mycase.path, opts.kustomizationPath)
} }
} }
} }
@@ -115,7 +115,7 @@ func TestBuild(t *testing.T) {
} }
ops := &buildOptions{ ops := &buildOptions{
manifestPath: testcase.Filename, kustomizationPath: testcase.Filename,
} }
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
err = ops.RunBuild(buf, os.Stderr, fs) err = ops.RunBuild(buf, os.Stderr, fs)

View File

@@ -60,10 +60,10 @@ More info at https://github.com/kubernetes/kubectl/tree/master/cmd/kustomize
func newCmdEdit(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command { func newCmdEdit(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command {
c := &cobra.Command{ c := &cobra.Command{
Use: "edit", Use: "edit",
Short: "Edits a manifest file", Short: "Edits a kustomization file",
Long: "", Long: "",
Example: ` Example: `
# Adds a configmap to the manifest # Adds a configmap to the kustomization file
kustomize edit add configmap NAME --from-literal=k=v kustomize edit add configmap NAME --from-literal=k=v
# Sets the nameprefix field # Sets the nameprefix field
@@ -82,16 +82,16 @@ func newCmdEdit(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command {
func newCmdAdd(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command { func newCmdAdd(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command {
c := &cobra.Command{ c := &cobra.Command{
Use: "add", Use: "add",
Short: "Adds configmap/resource/secret to the manifest.", Short: "Adds configmap/resource/secret to the kustomization file.",
Long: "", Long: "",
Example: ` Example: `
# Adds a configmap to the manifest # Adds a configmap to the kustomization file
kustomize edit add configmap NAME --from-literal=k=v kustomize edit add configmap NAME --from-literal=k=v
# Adds a secret to the manifest # Adds a secret to the kustomization file
kustomize edit add secret NAME --from-literal=k=v kustomize edit add secret NAME --from-literal=k=v
# Adds a resource to the manifest # Adds a resource to the kustomization
kustomize edit add resource <filepath> kustomize edit add resource <filepath>
`, `,
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
@@ -107,7 +107,7 @@ func newCmdAdd(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command {
func newCmdSet(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command { func newCmdSet(stdOut, stdErr io.Writer, fsys fs.FileSystem) *cobra.Command {
c := &cobra.Command{ c := &cobra.Command{
Use: "set", Use: "set",
Short: "Sets the value of different fields in manifest.", Short: "Sets the value of different fields in kustomization file.",
Long: "", Long: "",
Example: ` Example: `
# Sets the nameprefix field # Sets the nameprefix field

View File

@@ -32,13 +32,13 @@ func newCmdAddConfigMap(errOut io.Writer, fsys fs.FileSystem) *cobra.Command {
var config dataConfig var config dataConfig
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1]", Use: "configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1]",
Short: "Adds a configmap to the kustomize config file.", Short: "Adds a configmap to the kustomization file.",
Long: "", Long: "",
Example: ` Example: `
# Adds a configmap to the kustomize config file (with a specified key) # Adds a configmap to the kustomization file (with a specified key)
kustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345 kustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345
# Adds a configmap to the kustomize config file (key is the filename) # Adds a configmap to the kustomization file (key is the filename)
kustomize edit add configmap my-configmap --from-file=file/path kustomize edit add configmap my-configmap --from-file=file/path
# Adds a configmap from env-file # Adds a configmap from env-file
@@ -50,8 +50,8 @@ func newCmdAddConfigMap(errOut io.Writer, fsys fs.FileSystem) *cobra.Command {
return err return err
} }
// Load in the kustomize config file. // Load in the kustomization file.
mf, err := newManifestFile(constants.KustomizeFileName, fsys) mf, err := newKustomizationFile(constants.KustomizationFileName, fsys)
if err != nil { if err != nil {
return err return err
} }
@@ -61,28 +61,40 @@ func newCmdAddConfigMap(errOut io.Writer, fsys fs.FileSystem) *cobra.Command {
return err return err
} }
// Add the config map to the kustomize config file. // Add the config map to the kustomization file.
err = addConfigMap(m, config) err = addConfigMap(m, config)
if err != nil { if err != nil {
return err return err
} }
// Write out the kustomize config file with added configmap. // Write out the kustomization file with added configmap.
return mf.write(m) return mf.write(m)
}, },
} }
cmd.Flags().StringSliceVar(&config.FileSources, "from-file", []string{}, "Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key.") cmd.Flags().StringSliceVar(
cmd.Flags().StringArrayVar(&config.LiteralSources, "from-literal", []string{}, "Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)") &config.FileSources,
cmd.Flags().StringVar(&config.EnvFileSource, "from-env-file", "", "Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).") "from-file",
[]string{},
"Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key.")
cmd.Flags().StringArrayVar(
&config.LiteralSources,
"from-literal",
[]string{},
"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)")
cmd.Flags().StringVar(
&config.EnvFileSource,
"from-env-file",
"",
"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).")
return cmd return cmd
} }
// addConfigMap updates a configmap within a kustomize config file, using the data in config. // addConfigMap updates a configmap within a kustomization file, using the data in config.
// Note: error may leave kustomize config file in an undefined state. Suggest passing a copy // Note: error may leave kustomization file in an undefined state. Suggest passing a copy
// of kustomize config file. // of kustomization file.
func addConfigMap(m *types.Manifest, config dataConfig) error { func addConfigMap(m *types.Kustomization, config dataConfig) error {
cm := getOrCreateConfigMap(m, config.Name) cm := getOrCreateConfigMap(m, config.Name)
err := mergeData(&cm.DataSources, config) err := mergeData(&cm.DataSources, config)
@@ -99,13 +111,13 @@ func addConfigMap(m *types.Manifest, config dataConfig) error {
return nil return nil
} }
func getOrCreateConfigMap(m *types.Manifest, name string) *types.ConfigMapArgs { func getOrCreateConfigMap(m *types.Kustomization, name string) *types.ConfigMapArgs {
for i, v := range m.ConfigMapGenerator { for i, v := range m.ConfigMapGenerator {
if name == v.Name { if name == v.Name {
return &m.ConfigMapGenerator[i] return &m.ConfigMapGenerator[i]
} }
} }
// config map not found, create new one and add it to the kustomize config file. // config map not found, create new one and add it to the kustomization file.
cm := &types.ConfigMapArgs{Name: name} cm := &types.ConfigMapArgs{Name: name}
m.ConfigMapGenerator = append(m.ConfigMapGenerator, *cm) m.ConfigMapGenerator = append(m.ConfigMapGenerator, *cm)
return &m.ConfigMapGenerator[len(m.ConfigMapGenerator)-1] return &m.ConfigMapGenerator[len(m.ConfigMapGenerator)-1]

View File

@@ -32,34 +32,34 @@ func TestNewAddConfigMapIsNotNil(t *testing.T) {
func TestGetOrCreateConfigMap(t *testing.T) { func TestGetOrCreateConfigMap(t *testing.T) {
cmName := "test-config-name" cmName := "test-config-name"
manifest := &types.Manifest{ kustomization := &types.Kustomization{
NamePrefix: "test-name-prefix", NamePrefix: "test-name-prefix",
} }
if len(manifest.ConfigMapGenerator) != 0 { if len(kustomization.ConfigMapGenerator) != 0 {
t.Fatal("Initial manifest should not have any configmaps") t.Fatal("Initial kustomization should not have any configmaps")
} }
cm := getOrCreateConfigMap(manifest, cmName) cm := getOrCreateConfigMap(kustomization, cmName)
if cm == nil { if cm == nil {
t.Fatalf("ConfigMap should always be non-nil") t.Fatalf("ConfigMap should always be non-nil")
} }
if len(manifest.ConfigMapGenerator) != 1 { if len(kustomization.ConfigMapGenerator) != 1 {
t.Fatalf("Manifest should have newly created configmap") t.Fatalf("Kustomization should have newly created configmap")
} }
if &manifest.ConfigMapGenerator[len(manifest.ConfigMapGenerator)-1] != cm { if &kustomization.ConfigMapGenerator[len(kustomization.ConfigMapGenerator)-1] != cm {
t.Fatalf("Pointer address for newly inserted configmap should be same") t.Fatalf("Pointer address for newly inserted configmap should be same")
} }
existingCM := getOrCreateConfigMap(manifest, cmName) existingCM := getOrCreateConfigMap(kustomization, cmName)
if existingCM != cm { if existingCM != cm {
t.Fatalf("should have returned an existing cm with name: %v", cmName) t.Fatalf("should have returned an existing cm with name: %v", cmName)
} }
if len(manifest.ConfigMapGenerator) != 1 { if len(kustomization.ConfigMapGenerator) != 1 {
t.Fatalf("Should not insert configmap for an existing name: %v", cmName) t.Fatalf("Should not insert configmap for an existing name: %v", cmName)
} }
} }

View File

@@ -31,7 +31,7 @@ import (
) )
type diffOptions struct { type diffOptions struct {
manifestPath string kustomizationPath string
} }
// newCmdDiff makes the diff command. // newCmdDiff makes the diff command.
@@ -56,7 +56,7 @@ func newCmdDiff(out, errOut io.Writer, fs fs.FileSystem) *cobra.Command {
}, },
} }
cmd.Flags().StringVarP(&o.manifestPath, "filename", "f", "", "Pass in a kustomize.yaml file or a directory that contains the file.") cmd.Flags().StringVarP(&o.kustomizationPath, "filename", "f", "", "Pass in a kustomize.yaml file or a directory that contains the file.")
cmd.MarkFlagRequired("filename") cmd.MarkFlagRequired("filename")
return cmd return cmd
} }
@@ -85,7 +85,7 @@ func (o *diffOptions) RunDiff(out, errOut io.Writer, fs fs.FileSystem) error {
l := loader.Init([]loader.SchemeLoader{loader.NewFileLoader(fs)}) l := loader.Init([]loader.SchemeLoader{loader.NewFileLoader(fs)})
absPath, err := filepath.Abs(o.manifestPath) absPath, err := filepath.Abs(o.kustomizationPath)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -86,7 +86,7 @@ func TestDiff(t *testing.T) {
} }
diffOps := &diffOptions{ diffOps := &diffOptions{
manifestPath: testcase.Filename, kustomizationPath: testcase.Filename,
} }
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
err = diffOps.RunDiff(buf, os.Stderr, fs) err = diffOps.RunDiff(buf, os.Stderr, fs)

View File

@@ -27,11 +27,7 @@ import (
"k8s.io/kubectl/pkg/kustomize/util/fs" "k8s.io/kubectl/pkg/kustomize/util/fs"
) )
const manifestTemplate = `apiVersion: manifest.k8s.io/v1alpha1 const kustomizationTemplate = `kustomizationName: helloworld
kind: Manifest
metadata:
name: helloworld
description: helloworld does useful stuff.
namePrefix: some-prefix namePrefix: some-prefix
# Labels to add to all objects and selectors. # Labels to add to all objects and selectors.
# These labels would also be used to form the selector for apply --prune # These labels would also be used to form the selector for apply --prune
@@ -58,9 +54,9 @@ func newCmdInit(out, errOut io.Writer, fs fs.FileSystem) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "init", Use: "init",
Short: "Creates a file called \"" + constants.KustomizeFileName + "\" in the current directory", Short: "Creates a file called \"" + constants.KustomizationFileName + "\" in the current directory",
Long: "Creates a file called \"" + Long: "Creates a file called \"" +
constants.KustomizeFileName + "\" in the current directory with example values.", constants.KustomizationFileName + "\" in the current directory with example values.",
Example: `init`, Example: `init`,
SilenceUsage: true, SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@@ -91,10 +87,10 @@ func (o *initOptions) Complete(cmd *cobra.Command, args []string) error {
return nil return nil
} }
// RunInit writes a manifest file. // RunInit writes a kustomization file.
func (o *initOptions) RunInit(out, errOut io.Writer, fs fs.FileSystem) error { func (o *initOptions) RunInit(out, errOut io.Writer, fs fs.FileSystem) error {
if _, err := fs.Stat(constants.KustomizeFileName); err == nil { if _, err := fs.Stat(constants.KustomizationFileName); err == nil {
return fmt.Errorf("%q already exists", constants.KustomizeFileName) return fmt.Errorf("%q already exists", constants.KustomizationFileName)
} }
return fs.WriteFile(constants.KustomizeFileName, []byte(manifestTemplate)) return fs.WriteFile(constants.KustomizationFileName, []byte(kustomizationTemplate))
} }

View File

@@ -34,21 +34,21 @@ func TestInitHappyPath(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
f, err := fakeFS.Open(constants.KustomizeFileName) f, err := fakeFS.Open(constants.KustomizationFileName)
if err != nil { if err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
file := f.(*fs.FakeFile) file := f.(*fs.FakeFile)
if !file.ContentMatches([]byte(manifestTemplate)) { if !file.ContentMatches([]byte(kustomizationTemplate)) {
t.Fatalf("actual: %v doesn't match expected: %v", t.Fatalf("actual: %v doesn't match expected: %v",
string(file.GetContent()), manifestTemplate) string(file.GetContent()), kustomizationTemplate)
} }
} }
func TestInitFileAlreadyExist(t *testing.T) { func TestInitFileAlreadyExist(t *testing.T) {
content := "hey there" content := "hey there"
fakeFS := fs.MakeFakeFS() fakeFS := fs.MakeFakeFS()
fakeFS.WriteFile(constants.KustomizeFileName, []byte(content)) fakeFS.WriteFile(constants.KustomizationFileName, []byte(content))
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
cmd := newCmdInit(buf, os.Stderr, fakeFS) cmd := newCmdInit(buf, os.Stderr, fakeFS)
@@ -56,7 +56,7 @@ func TestInitFileAlreadyExist(t *testing.T) {
if err == nil { if err == nil {
t.Fatalf("expected error") t.Fatalf("expected error")
} }
if err.Error() != `"`+constants.KustomizeFileName+`" already exists` { if err.Error() != `"`+constants.KustomizationFileName+`" already exists` {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
} }

View File

@@ -30,19 +30,17 @@ type setNamePrefixOptions struct {
prefix string prefix string
} }
// newCmdSetNamePrefix sets the value of the namePrefix field in the manifest. // newCmdSetNamePrefix sets the value of the namePrefix field in the kustomization.
func newCmdSetNamePrefix(out, errOut io.Writer, fsys fs.FileSystem) *cobra.Command { func newCmdSetNamePrefix(out, errOut io.Writer, fsys fs.FileSystem) *cobra.Command {
var o setNamePrefixOptions var o setNamePrefixOptions
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "nameprefix", Use: "nameprefix",
Short: "Sets the value of the namePrefix field in the manifest.", Short: "Sets the value of the namePrefix field in the kustomization file.",
Long: "Sets the value of the namePrefix field in the manifest.",
//
Example: ` Example: `
The command The command
set nameprefix acme- set nameprefix acme-
will add the field "namePrefix: acme-" to the manifest file if it doesn't exist, will add the field "namePrefix: acme-" to the kustomization file if it doesn't exist,
and overwrite the value with "acme-" if the field does exist. and overwrite the value with "acme-" if the field does exist.
`, `,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@@ -77,7 +75,7 @@ func (o *setNamePrefixOptions) Complete(cmd *cobra.Command, args []string) error
// RunSetNamePrefix runs setNamePrefix command (does real work). // RunSetNamePrefix runs setNamePrefix command (does real work).
func (o *setNamePrefixOptions) RunSetNamePrefix(out, errOut io.Writer, fsys fs.FileSystem) error { func (o *setNamePrefixOptions) RunSetNamePrefix(out, errOut io.Writer, fsys fs.FileSystem) error {
mf, err := newManifestFile(constants.KustomizeFileName, fsys) mf, err := newKustomizationFile(constants.KustomizationFileName, fsys)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -34,7 +34,7 @@ const (
func TestSetNamePrefixHappyPath(t *testing.T) { func TestSetNamePrefixHappyPath(t *testing.T) {
buf := bytes.NewBuffer([]byte{}) buf := bytes.NewBuffer([]byte{})
fakeFS := fs.MakeFakeFS() fakeFS := fs.MakeFakeFS()
fakeFS.WriteFile(constants.KustomizeFileName, []byte(manifestTemplate)) fakeFS.WriteFile(constants.KustomizationFileName, []byte(kustomizationTemplate))
cmd := newCmdSetNamePrefix(buf, os.Stderr, fakeFS) cmd := newCmdSetNamePrefix(buf, os.Stderr, fakeFS)
args := []string{goodPrefixValue} args := []string{goodPrefixValue}
@@ -42,12 +42,12 @@ func TestSetNamePrefixHappyPath(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("unexpected cmd error: %v", err) t.Errorf("unexpected cmd error: %v", err)
} }
content, err := fakeFS.ReadFile(constants.KustomizeFileName) content, err := fakeFS.ReadFile(constants.KustomizationFileName)
if err != nil { if err != nil {
t.Errorf("unexpected read error: %v", err) t.Errorf("unexpected read error: %v", err)
} }
if !strings.Contains(string(content), goodPrefixValue) { if !strings.Contains(string(content), goodPrefixValue) {
t.Errorf("expected prefix value in manifest") t.Errorf("expected prefix value in kustomization file")
} }
} }

View File

@@ -30,13 +30,13 @@ import (
"k8s.io/kubectl/pkg/kustomize/util/fs" "k8s.io/kubectl/pkg/kustomize/util/fs"
) )
type manifestFile struct { type kustomizationFile struct {
mPath string path string
fsys fs.FileSystem fsys fs.FileSystem
} }
func newManifestFile(mPath string, fsys fs.FileSystem) (*manifestFile, error) { func newKustomizationFile(mPath string, fsys fs.FileSystem) (*kustomizationFile, error) {
mf := &manifestFile{mPath: mPath, fsys: fsys} mf := &kustomizationFile{path: mPath, fsys: fsys}
err := mf.validate() err := mf.validate()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -44,52 +44,52 @@ func newManifestFile(mPath string, fsys fs.FileSystem) (*manifestFile, error) {
return mf, nil return mf, nil
} }
func (mf *manifestFile) validate() error { func (mf *kustomizationFile) validate() error {
f, err := mf.fsys.Stat(mf.mPath) f, err := mf.fsys.Stat(mf.path)
if err != nil { if err != nil {
errorMsg := fmt.Sprintf("Missing kustomize config file '%s'.\n", mf.mPath) errorMsg := fmt.Sprintf("Missing kustomization file '%s'.\n", mf.path)
merr := interror.ManifestError{ManifestFilepath: mf.mPath, ErrorMsg: errorMsg} merr := interror.KustomizationError{KustomizationPath: mf.path, ErrorMsg: errorMsg}
return merr return merr
} }
if f.IsDir() { if f.IsDir() {
mf.mPath = path.Join(mf.mPath, constants.KustomizeFileName) mf.path = path.Join(mf.path, constants.KustomizationFileName)
_, err = mf.fsys.Stat(mf.mPath) _, err = mf.fsys.Stat(mf.path)
if err != nil { if err != nil {
errorMsg := fmt.Sprintf("Missing kustomize config file '%s'.\n", mf.mPath) errorMsg := fmt.Sprintf("Missing kustomization file '%s'.\n", mf.path)
merr := interror.ManifestError{ManifestFilepath: mf.mPath, ErrorMsg: errorMsg} merr := interror.KustomizationError{KustomizationPath: mf.path, ErrorMsg: errorMsg}
return merr return merr
} }
} else { } else {
if !strings.HasSuffix(mf.mPath, constants.KustomizeFileName) { if !strings.HasSuffix(mf.path, constants.KustomizationFileName) {
errorMsg := fmt.Sprintf("Kustomize config file path (%s) should have %s suffix\n", mf.mPath, constants.KustomizeSuffix) errorMsg := fmt.Sprintf("Kustomization file path (%s) should have %s suffix\n", mf.path, constants.KustomizationSuffix)
merr := interror.ManifestError{ManifestFilepath: mf.mPath, ErrorMsg: errorMsg} merr := interror.KustomizationError{KustomizationPath: mf.path, ErrorMsg: errorMsg}
return merr return merr
} }
} }
return nil return nil
} }
func (mf *manifestFile) read() (*types.Manifest, error) { func (mf *kustomizationFile) read() (*types.Kustomization, error) {
bytes, err := mf.fsys.ReadFile(mf.mPath) bytes, err := mf.fsys.ReadFile(mf.path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var manifest types.Manifest var kustomization types.Kustomization
err = yaml.Unmarshal(bytes, &manifest) err = yaml.Unmarshal(bytes, &kustomization)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &manifest, err return &kustomization, err
} }
func (mf *manifestFile) write(manifest *types.Manifest) error { func (mf *kustomizationFile) write(kustomization *types.Kustomization) error {
if manifest == nil { if kustomization == nil {
return errors.New("util: kustomize config file arg is nil.") return errors.New("util: kustomization file arg is nil.")
} }
bytes, err := yaml.Marshal(manifest) bytes, err := yaml.Marshal(kustomization)
if err != nil { if err != nil {
return err return err
} }
return mf.fsys.WriteFile(mf.mPath, bytes) return mf.fsys.WriteFile(mf.path, bytes)
} }

View File

@@ -26,35 +26,35 @@ import (
) )
func TestWriteAndRead(t *testing.T) { func TestWriteAndRead(t *testing.T) {
manifest := &types.Manifest{ kustomization := &types.Kustomization{
NamePrefix: "prefix", NamePrefix: "prefix",
} }
fsys := fs.MakeFakeFS() fsys := fs.MakeFakeFS()
fsys.Create("kustomize.yaml") fsys.Create("kustomize.yaml")
mf, err := newManifestFile("kustomize.yaml", fsys) mf, err := newKustomizationFile("kustomize.yaml", fsys)
if err != nil { if err != nil {
t.Fatalf("Unexpected Error: %v", err) t.Fatalf("Unexpected Error: %v", err)
} }
if err := mf.write(manifest); err != nil { if err := mf.write(kustomization); err != nil {
t.Fatalf("Couldn't write manifest file: %v\n", err) t.Fatalf("Couldn't write kustomization file: %v\n", err)
} }
readManifest, err := mf.read() content, err := mf.read()
if err != nil { if err != nil {
t.Fatalf("Couldn't read manifest file: %v\n", err) t.Fatalf("Couldn't read kustomization file: %v\n", err)
} }
if !reflect.DeepEqual(manifest, readManifest) { if !reflect.DeepEqual(kustomization, content) {
t.Fatal("Read manifest is different from written manifest") t.Fatal("Read kustomization is different from written kustomization")
} }
} }
func TestEmptyFile(t *testing.T) { func TestEmptyFile(t *testing.T) {
fsys := fs.MakeFakeFS() fsys := fs.MakeFakeFS()
_, err := newManifestFile("", fsys) _, err := newKustomizationFile("", fsys)
if err == nil { if err == nil {
t.Fatalf("Creat manifestFile from empty filename should fail") t.Fatalf("Creat kustomizationFile from empty filename should fail")
} }
} }
@@ -63,22 +63,22 @@ func TestNewNotExist(t *testing.T) {
fakeFS := fs.MakeFakeFS() fakeFS := fs.MakeFakeFS()
fakeFS.Mkdir(".", 0644) fakeFS.Mkdir(".", 0644)
fakeFS.Create(badSuffix) fakeFS.Create(badSuffix)
_, err := newManifestFile("kustomize.yaml", fakeFS) _, err := newKustomizationFile("kustomize.yaml", fakeFS)
if err == nil { if err == nil {
t.Fatalf("expect an error") t.Fatalf("expect an error")
} }
contained := "Missing kustomize config file" contained := "Missing kustomization file"
if !strings.Contains(err.Error(), contained) { if !strings.Contains(err.Error(), contained) {
t.Fatalf("expect an error contains %q, but got %v", contained, err) t.Fatalf("expect an error contains %q, but got %v", contained, err)
} }
_, err = newManifestFile("kustomize.yaml", fakeFS) _, err = newKustomizationFile("kustomize.yaml", fakeFS)
if err == nil { if err == nil {
t.Fatalf("expect an error") t.Fatalf("expect an error")
} }
if !strings.Contains(err.Error(), contained) { if !strings.Contains(err.Error(), contained) {
t.Fatalf("expect an error contains %q, but got %v", contained, err) t.Fatalf("expect an error contains %q, but got %v", contained, err)
} }
_, err = newManifestFile(badSuffix, fakeFS) _, err = newKustomizationFile(badSuffix, fakeFS)
if err == nil { if err == nil {
t.Fatalf("expect an error") t.Fatalf("expect an error")
} }

View File

@@ -16,9 +16,10 @@ limitations under the License.
package constants package constants
// KustomizeFileName is the Well-Known File Name for a kubernetes app manifest. const KustomizationSuffix = ".yaml"
const KustomizeSuffix = ".yaml"
const KustomizeFileName = "kustomize" + KustomizeSuffix // KustomizationFileName is the Well-Known File Name for a kustomize configuration file
const KustomizationFileName = "kustomize" + KustomizationSuffix
// Configmap behaviors // Configmap behaviors
const CreateBehavior = "create" const CreateBehavior = "create"

View File

@@ -19,10 +19,10 @@ package error
import "fmt" import "fmt"
type ConfigmapError struct { type ConfigmapError struct {
ManifestFilepath string Path string
ErrorMsg string ErrorMsg string
} }
func (e ConfigmapError) Error() string { func (e ConfigmapError) Error() string {
return fmt.Sprintf("Manifest file [%s] encounters a configmap error: %s\n", e.ManifestFilepath, e.ErrorMsg) return fmt.Sprintf("Kustomization file [%s] encounters a configmap error: %s\n", e.Path, e.ErrorMsg)
} }

View File

@@ -24,7 +24,7 @@ import (
func TestConfigmapError_Error(t *testing.T) { func TestConfigmapError_Error(t *testing.T) {
filepath := "/path/to/kustomize.yaml" filepath := "/path/to/kustomize.yaml"
errorMsg := "configmap name is missing" errorMsg := "configmap name is missing"
me := ConfigmapError{ManifestFilepath: filepath, ErrorMsg: errorMsg} me := ConfigmapError{Path: filepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) { if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect ConfigmapError.Error() message \n") t.Errorf("Incorrect ConfigmapError.Error() message \n")

View File

@@ -21,37 +21,37 @@ import (
) )
// First pass to encapsulate fields for more informative error messages. // First pass to encapsulate fields for more informative error messages.
type ManifestError struct { type KustomizationError struct {
ManifestFilepath string KustomizationPath string
ErrorMsg string ErrorMsg string
} }
func (me ManifestError) Error() string { func (ke KustomizationError) Error() string {
return fmt.Sprintf("Manifest File [%s]: %s\n", me.ManifestFilepath, me.ErrorMsg) return fmt.Sprintf("Kustomization File [%s]: %s\n", ke.KustomizationPath, ke.ErrorMsg)
} }
type ManifestErrors struct { type KustomizationErrors struct {
merrors []error kErrors []error
} }
func (me *ManifestErrors) Error() string { func (ke *KustomizationErrors) Error() string {
errormsg := "" errormsg := ""
for _, e := range me.merrors { for _, e := range ke.kErrors {
errormsg += e.Error() + "\n" errormsg += e.Error() + "\n"
} }
return errormsg return errormsg
} }
func (me *ManifestErrors) Append(e error) { func (ke *KustomizationErrors) Append(e error) {
me.merrors = append(me.merrors, e) ke.kErrors = append(ke.kErrors, e)
} }
func (me *ManifestErrors) Get() []error { func (ke *KustomizationErrors) Get() []error {
return me.merrors return ke.kErrors
} }
func (me *ManifestErrors) BatchAppend(e ManifestErrors) { func (ke *KustomizationErrors) BatchAppend(e KustomizationErrors) {
for _, err := range e.Get() { for _, err := range e.Get() {
me.merrors = append(me.merrors, err) ke.kErrors = append(ke.kErrors, err)
} }
} }

View File

@@ -0,0 +1,92 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package error
import (
"fmt"
"strings"
"testing"
)
func TestKustomizationError_Error(t *testing.T) {
filepath := "/path/to/kustomize.yaml"
errorMsg := "Kustomization not found"
me := KustomizationError{KustomizationPath: filepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect KustomizationError.Error() message \n")
t.Errorf("Expected filepath %s, but unfound\n", filepath)
}
if !strings.Contains(me.Error(), errorMsg) {
t.Errorf("Incorrect KustomizationError.Error() message \n")
t.Errorf("Expected errorMsg %s, but unfound\n", errorMsg)
}
}
func TestKustomizationErrors_Error(t *testing.T) {
filepath := "/path/to/kustomize"
me := KustomizationError{KustomizationPath: filepath, ErrorMsg: "Kustomization not found"}
ce := ConfigmapError{Path: filepath, ErrorMsg: "can't find configmap name"}
pe := PatchError{KustomizationPath: filepath, PatchFilepath: filepath, ErrorMsg: "can't find patch file"}
re := ResourceError{KustomizationPath: filepath, ResourceFilepath: filepath, ErrorMsg: "can't find resource file"}
se := SecretError{KustomizationPath: filepath, ErrorMsg: "can't find secret name"}
mes := KustomizationErrors{kErrors: []error{me, ce, pe, re, se}}
expectedErrorMsg := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n", me.Error(), ce.Error(), pe.Error(), re.Error(), se.Error())
if mes.Error() != expectedErrorMsg {
t.Errorf("Incorrect KustomizationErrors.Error() message\n")
t.Errorf(" Expected: %s\n", expectedErrorMsg)
t.Errorf(" Got: %s\n", mes.Error())
}
}
func TestKustomizationErrors_Get(t *testing.T) {
ce := ConfigmapError{Path: "kustomization/filepath", ErrorMsg: "can't find configmap name"}
mes := KustomizationErrors{kErrors: []error{ce}}
if len(mes.Get()) != 1 {
t.Errorf("Incorrect KustomizationErrors.Get()\n")
t.Errorf(" Expected: %v\n", []error{ce})
t.Errorf(" Got: %s\n", mes.Get())
}
}
func TestKustomizationErrors_Append(t *testing.T) {
ce := ConfigmapError{Path: "kustomization/filepath", ErrorMsg: "can't find configmap name"}
pe := PatchError{KustomizationPath: "kustomization/filepath", PatchFilepath: "patch/path", ErrorMsg: "can't find patch file"}
mes := KustomizationErrors{kErrors: []error{ce}}
mes.Append(pe)
if len(mes.Get()) != 2 {
t.Errorf("Incorrect KustomizationErrors.Append()\n")
t.Errorf(" Expected: %d error\n%v/n", 2, []error{ce, pe})
t.Errorf(" Got: %d error\n%v\n", len(mes.Get()), mes.Get())
}
}
func TestKustomizationErrors_BatchAppend(t *testing.T) {
ce := ConfigmapError{Path: "kustomization/filepath", ErrorMsg: "can't find configmap name"}
pe := PatchError{KustomizationPath: "kustomization/filepath", PatchFilepath: "patch/path", ErrorMsg: "can't find patch file"}
mes := KustomizationErrors{kErrors: []error{ce}}
me := KustomizationErrors{kErrors: []error{pe}}
mes.BatchAppend(me)
if len(mes.Get()) != 2 {
t.Errorf("Incorrect KustomizationErrors.Append()\n")
t.Errorf(" Expected: %d error\n%v/n", 2, []error{ce, pe})
t.Errorf(" Got: %d error\n%v\n", len(mes.Get()), mes.Get())
}
}

View File

@@ -1,92 +0,0 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package error
import (
"fmt"
"strings"
"testing"
)
func TestManifestError_Error(t *testing.T) {
filepath := "/path/to/kustomize.yaml"
errorMsg := "Manifest not found"
me := ManifestError{ManifestFilepath: filepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect ManifestError.Error() message \n")
t.Errorf("Expected filepath %s, but unfound\n", filepath)
}
if !strings.Contains(me.Error(), errorMsg) {
t.Errorf("Incorrect ManifestError.Error() message \n")
t.Errorf("Expected errorMsg %s, but unfound\n", errorMsg)
}
}
func TestManifestErrors_Error(t *testing.T) {
filepath := "/path/to/kustomize"
me := ManifestError{ManifestFilepath: filepath, ErrorMsg: "Manifest not found"}
ce := ConfigmapError{ManifestFilepath: filepath, ErrorMsg: "can't find configmap name"}
pe := PatchError{ManifestFilepath: filepath, PatchFilepath: filepath, ErrorMsg: "can't find patch file"}
re := ResourceError{ManifestFilepath: filepath, ResourceFilepath: filepath, ErrorMsg: "can't find resource file"}
se := SecretError{ManifestFilepath: filepath, ErrorMsg: "can't find secret name"}
mes := ManifestErrors{merrors: []error{me, ce, pe, re, se}}
expectedErrorMsg := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n", me.Error(), ce.Error(), pe.Error(), re.Error(), se.Error())
if mes.Error() != expectedErrorMsg {
t.Errorf("Incorrect ManifestErrors.Error() message\n")
t.Errorf(" Expected: %s\n", expectedErrorMsg)
t.Errorf(" Got: %s\n", mes.Error())
}
}
func TestManifestErrors_Get(t *testing.T) {
ce := ConfigmapError{ManifestFilepath: "manifest/filepath", ErrorMsg: "can't find configmap name"}
mes := ManifestErrors{merrors: []error{ce}}
if len(mes.Get()) != 1 {
t.Errorf("Incorrect ManifestErrors.Get()\n")
t.Errorf(" Expected: %v\n", []error{ce})
t.Errorf(" Got: %s\n", mes.Get())
}
}
func TestManifestErrors_Append(t *testing.T) {
ce := ConfigmapError{ManifestFilepath: "manifest/filepath", ErrorMsg: "can't find configmap name"}
pe := PatchError{ManifestFilepath: "manifest/filepath", PatchFilepath: "patch/path", ErrorMsg: "can't find patch file"}
mes := ManifestErrors{merrors: []error{ce}}
mes.Append(pe)
if len(mes.Get()) != 2 {
t.Errorf("Incorrect ManifestErrors.Append()\n")
t.Errorf(" Expected: %d error\n%v/n", 2, []error{ce, pe})
t.Errorf(" Got: %d error\n%v\n", len(mes.Get()), mes.Get())
}
}
func TestManifestErrors_BatchAppend(t *testing.T) {
ce := ConfigmapError{ManifestFilepath: "manifest/filepath", ErrorMsg: "can't find configmap name"}
pe := PatchError{ManifestFilepath: "manifest/filepath", PatchFilepath: "patch/path", ErrorMsg: "can't find patch file"}
mes := ManifestErrors{merrors: []error{ce}}
me := ManifestErrors{merrors: []error{pe}}
mes.BatchAppend(me)
if len(mes.Get()) != 2 {
t.Errorf("Incorrect ManifestErrors.Append()\n")
t.Errorf(" Expected: %d error\n%v/n", 2, []error{ce, pe})
t.Errorf(" Got: %d error\n%v\n", len(mes.Get()), mes.Get())
}
}

View File

@@ -21,11 +21,11 @@ import (
) )
type PatchError struct { type PatchError struct {
ManifestFilepath string KustomizationPath string
PatchFilepath string PatchFilepath string
ErrorMsg string ErrorMsg string
} }
func (e PatchError) Error() string { func (e PatchError) Error() string {
return fmt.Sprintf("Manifest file [%s] encounters a patch error for [%s]: %s\n", e.ManifestFilepath, e.PatchFilepath, e.ErrorMsg) return fmt.Sprintf("Kustomization file [%s] encounters a patch error for [%s]: %s\n", e.KustomizationPath, e.PatchFilepath, e.ErrorMsg)
} }

View File

@@ -25,7 +25,7 @@ func TestPatchError_Error(t *testing.T) {
filepath := "/path/to/kustomize.yaml" filepath := "/path/to/kustomize.yaml"
patchfilepath := "/path/to/patch/patch.yaml" patchfilepath := "/path/to/patch/patch.yaml"
errorMsg := "file not found" errorMsg := "file not found"
me := PatchError{ManifestFilepath: filepath, PatchFilepath: patchfilepath, ErrorMsg: errorMsg} me := PatchError{KustomizationPath: filepath, PatchFilepath: patchfilepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) { if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect PatchError.Error() message \n") t.Errorf("Incorrect PatchError.Error() message \n")
t.Errorf("Expected filepath %s, but unfound\n", filepath) t.Errorf("Expected filepath %s, but unfound\n", filepath)

View File

@@ -20,11 +20,11 @@ import "fmt"
// First pass to encapsulate fields for more informative error messages. // First pass to encapsulate fields for more informative error messages.
type ResourceError struct { type ResourceError struct {
ManifestFilepath string KustomizationPath string
ResourceFilepath string ResourceFilepath string
ErrorMsg string ErrorMsg string
} }
func (e ResourceError) Error() string { func (e ResourceError) Error() string {
return fmt.Sprintf("Manifest file [%s] encounters a resource error for [%s]: %s\n", e.ManifestFilepath, e.ResourceFilepath, e.ErrorMsg) return fmt.Sprintf("Kustomization file [%s] encounters a resource error for [%s]: %s\n", e.KustomizationPath, e.ResourceFilepath, e.ErrorMsg)
} }

View File

@@ -25,7 +25,7 @@ func TestResourceError_Error(t *testing.T) {
filepath := "/path/to/kustomize.yaml" filepath := "/path/to/kustomize.yaml"
resourcefilepath := "/path/to/resource/deployment.yaml" resourcefilepath := "/path/to/resource/deployment.yaml"
errorMsg := "file not found" errorMsg := "file not found"
me := ResourceError{ManifestFilepath: filepath, ResourceFilepath: resourcefilepath, ErrorMsg: errorMsg} me := ResourceError{KustomizationPath: filepath, ResourceFilepath: resourcefilepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) { if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect ResourceError.Error() message \n") t.Errorf("Incorrect ResourceError.Error() message \n")
t.Errorf("Expected filepath %s, but unfound\n", filepath) t.Errorf("Expected filepath %s, but unfound\n", filepath)

View File

@@ -19,10 +19,10 @@ package error
import "fmt" import "fmt"
type SecretError struct { type SecretError struct {
ManifestFilepath string KustomizationPath string
ErrorMsg string ErrorMsg string
} }
func (e SecretError) Error() string { func (e SecretError) Error() string {
return fmt.Sprintf("Manifest file [%s] encounters a secret error: %s\n", e.ManifestFilepath, e.ErrorMsg) return fmt.Sprintf("Kustomization file [%s] encounters a secret error: %s\n", e.KustomizationPath, e.ErrorMsg)
} }

View File

@@ -24,7 +24,7 @@ import (
func TestSecretError_Error(t *testing.T) { func TestSecretError_Error(t *testing.T) {
filepath := "/path/to/secret.yaml" filepath := "/path/to/secret.yaml"
errorMsg := "missing a command" errorMsg := "missing a command"
me := SecretError{ManifestFilepath: filepath, ErrorMsg: errorMsg} me := SecretError{KustomizationPath: filepath, ErrorMsg: errorMsg}
if !strings.Contains(me.Error(), filepath) { if !strings.Contains(me.Error(), filepath) {
t.Errorf("Incorrect SecretError.Error() message \n") t.Errorf("Incorrect SecretError.Error() message \n")
t.Errorf("Expected filepath %s, but unfound\n", filepath) t.Errorf("Expected filepath %s, but unfound\n", filepath)

View File

@@ -20,7 +20,7 @@ import (
"k8s.io/kubectl/pkg/loader" "k8s.io/kubectl/pkg/loader"
) )
// NewFromResources returns a ResourceCollection given a resource path slice from manifest file. // NewFromResources returns a ResourceCollection given a resource path slice from kustomization file.
func NewFromResources(loader loader.Loader, paths []string) (ResourceCollection, error) { func NewFromResources(loader loader.Loader, paths []string) (ResourceCollection, error) {
allResources := []ResourceCollection{} allResources := []ResourceCollection{}
for _, path := range paths { for _, path := range paths {
@@ -38,7 +38,7 @@ func NewFromResources(loader loader.Loader, paths []string) (ResourceCollection,
return Merge(allResources...) return Merge(allResources...)
} }
// NewFromPatches returns a slice of Resources given a patch path slice from manifest file. // NewFromPatches returns a slice of Resources given a patch path slice from kustomization file.
func NewFromPatches(loader loader.Loader, paths []string) ([]*Resource, error) { func NewFromPatches(loader loader.Loader, paths []string) ([]*Resource, error) {
allResources := []*Resource{} allResources := []*Resource{}
for _, path := range paths { for _, path := range paths {

View File

@@ -130,7 +130,7 @@ func addKV(m map[string]string, kv kvPair) error {
return nil return nil
} }
// NewFromConfigMaps returns a Resource slice given a configmap metadata slice from kustomize config file. // NewFromConfigMaps returns a Resource slice given a configmap metadata slice from kustomization file.
func NewFromConfigMaps(loader loader.Loader, cmList []types.ConfigMapArgs) (ResourceCollection, error) { func NewFromConfigMaps(loader loader.Loader, cmList []types.ConfigMapArgs) (ResourceCollection, error) {
allResources := []*Resource{} allResources := []*Resource{}
for _, cm := range cmList { for _, cm := range cmList {

View File

@@ -16,18 +16,15 @@ limitations under the License.
package types package types
// Manifest has all the information to expand of generate the k8s api resources. // Kustomization holds the information needed to generate customized k8s api resources.
// It can be used by kubectl or some other tooling. type Kustomization struct {
// A manifest could be either a Base or an Overlay.
// TODO: rename Manifest to Kustomization
type Manifest struct {
// KustomizationName is a documentation field - a name for the customizations // KustomizationName is a documentation field - a name for the customizations
// in a marshalled version of this struct, that survives YAML unmarshalling // in a marshalled version of this struct, that survives YAML unmarshalling
// that discards comments. // that discards comments.
KustomizationName string `json:"kustomizationName,omitempty" yaml:"kustomizationName,omitempty"` KustomizationName string `json:"kustomizationName,omitempty" yaml:"kustomizationName,omitempty"`
// NamePrefix will prefix the names of all resources mentioned in the manifest // NamePrefix will prefix the names of all resources mentioned in the kustomization
// including generated configmaps and secrets. // file including generated configmaps and secrets.
NamePrefix string `json:"namePrefix,omitempty" yaml:"namePrefix,omitempty"` NamePrefix string `json:"namePrefix,omitempty" yaml:"namePrefix,omitempty"`
// Labels to add to all objects and selectors. // Labels to add to all objects and selectors.
@@ -39,7 +36,7 @@ type Manifest struct {
// Annotations to add to all objects. // Annotations to add to all objects.
ObjectAnnotations map[string]string `json:"objectAnnotations,omitempty" yaml:"objectAnnotations,omitempty"` ObjectAnnotations map[string]string `json:"objectAnnotations,omitempty" yaml:"objectAnnotations,omitempty"`
// Bases contain the paths to other packages that this manifest depends on. // Bases contain the paths to other packages that this kustomization depends on.
// Each path should be either a path to a kustomize.yaml or a path of // Each path should be either a path to a kustomize.yaml or a path of
// a directory that contains a kustomize.yaml file. // a directory that contains a kustomize.yaml file.
Bases []string `json:"bases,omitempty" yaml:"bases,omitempty"` Bases []string `json:"bases,omitempty" yaml:"bases,omitempty"`
@@ -72,7 +69,7 @@ type Manifest struct {
// ConfigMapArg contains the metadata of how to generate a configmap. // ConfigMapArg contains the metadata of how to generate a configmap.
type ConfigMapArgs struct { type ConfigMapArgs struct {
// Name of the configmap. // Name of the configmap.
// The full name should be Manifest.NamePrefix + Configmap.Name + // The full name should be Kustomization.NamePrefix + Configmap.Name +
// hash(content of configmap). // hash(content of configmap).
Name string `json:"name,omitempty" yaml:"name,omitempty"` Name string `json:"name,omitempty" yaml:"name,omitempty"`
@@ -89,7 +86,7 @@ type ConfigMapArgs struct {
// SecretGenerator contains the metadata of how to generate a secret. // SecretGenerator contains the metadata of how to generate a secret.
type SecretArgs struct { type SecretArgs struct {
// Name of the secret. // Name of the secret.
// The full name should be Manifest.NamePrefix + SecretGenerator.Name + // The full name should be Kustomization.NamePrefix + SecretGenerator.Name +
// hash(content of secret). // hash(content of secret).
Name string `json:"name,omitempty" yaml:"name,omitempty"` Name string `json:"name,omitempty" yaml:"name,omitempty"`