1/*
2Copyright 2018 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package add
18
19import (
20	"errors"
21	"fmt"
22	"strings"
23
24	"github.com/spf13/cobra"
25	"sigs.k8s.io/kustomize/pkg/commands/kustfile"
26	"sigs.k8s.io/kustomize/pkg/fs"
27)
28
29type addBaseOptions struct {
30	baseDirectoryPaths string
31}
32
33// newCmdAddBase adds the file path of the kustomize base to the kustomization file.
34func newCmdAddBase(fsys fs.FileSystem) *cobra.Command {
35	var o addBaseOptions
36
37	cmd := &cobra.Command{
38		Use:   "base",
39		Short: "Adds one or more bases to the kustomization.yaml in current directory",
40		Example: `
41		add base {filepath1},{filepath2}`,
42		RunE: func(cmd *cobra.Command, args []string) error {
43			err := o.Validate(args)
44			if err != nil {
45				return err
46			}
47			err = o.Complete(cmd, args)
48			if err != nil {
49				return err
50			}
51			return o.RunAddBase(fsys)
52		},
53	}
54	return cmd
55}
56
57// Validate validates addBase command.
58func (o *addBaseOptions) Validate(args []string) error {
59	if len(args) != 1 {
60		return errors.New("must specify a base directory")
61	}
62	o.baseDirectoryPaths = args[0]
63	return nil
64}
65
66// Complete completes addBase command.
67func (o *addBaseOptions) Complete(cmd *cobra.Command, args []string) error {
68	return nil
69}
70
71// RunAddBase runs addBase command (do real work).
72func (o *addBaseOptions) RunAddBase(fSys fs.FileSystem) error {
73	mf, err := kustfile.NewKustomizationFile(fSys)
74	if err != nil {
75		return err
76	}
77
78	m, err := mf.Read()
79	if err != nil {
80		return err
81	}
82
83	// split directory paths
84	paths := strings.Split(o.baseDirectoryPaths, ",")
85	for _, path := range paths {
86		if !fSys.Exists(path) {
87			return errors.New(path + " does not exist")
88		}
89		if kustfile.StringInSlice(path, m.Bases) {
90			return fmt.Errorf("base %s already in kustomization file", path)
91		}
92		m.Bases = append(m.Bases, path)
93
94	}
95
96	return mf.Write(m)
97}
98