From fa8a5a4f661056e1ef279322b287723b79ee377c Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Thu, 6 Jun 2024 20:55:27 +0000 Subject: [PATCH 1/6] add create kubeconfig file --- cmd/root.go | 1 + cmd/utils.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/cmd/root.go b/cmd/root.go index 45e6cc77..e75e1274 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -33,6 +33,7 @@ import ( ) var ( + // cfgFile represents the path to the configuration file. cfgFile string uiSize int macNotify bool diff --git a/cmd/utils.go b/cmd/utils.go index d6854e82..fb9b3b0c 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -408,6 +408,13 @@ func printWarning(out io.Writer, name string) { ct.ResetColor() } +func FailOnError(err error, message string) { + if err != nil { + printWarning(os.Stdout, fmt.Sprintf("%s: %s\n", message, err.Error())) + os.Exit(1) + } +} + func appendConfig(c1, c2 *clientcmdapi.Config) *clientcmdapi.Config { config := clientcmdapi.NewConfig() _ = mergo.Merge(config, c1) @@ -420,6 +427,9 @@ func CheckAndTransformFilePath(path string) (string, error) { if strings.HasPrefix(path, "~/") { path = filepath.Join(homeDir(), path[2:]) } + if !Exists(path) { + CreateDirectory(path) + } // read files info _, err := os.Stat(path) if err != nil { @@ -481,3 +491,36 @@ func validateContextTemplate(contextTemplate []string) error { } return nil } + +// checkes if a path exists +func Exists(path string) bool { + printYellow(os.Stdout, "Start Checking if Path Exist") + _, err := os.Stat(path) + if err == nil { + printYellow(os.Stdout, "Path Exist") + return true + } + if os.IsNotExist(err) { + printYellow(os.Stdout, "Path Dose NOT Exist") + return false + } + return false +} + +func CreateDirectory(path string) { + dir := filepath.Dir(path) + var create string + if Exists(dir) { + printYellow(os.Stdout, dir+" Path Exist") + } else { + printYellow(os.Stdout, "Createing Directory: "+filepath.Dir(path)) + if !filepath.IsAbs(dir) { + printYellow(os.Stdout, dir+" Path is Not Absolute") + create = "./" + dir + } else { + create = dir + } + err := os.MkdirAll(create, 0777) + FailOnError(err, "Failed to Create Directory") + } +} From 766e36a9492544d6fbc0fa343d03fa1ba74071cb Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Thu, 6 Jun 2024 22:24:57 +0000 Subject: [PATCH 2/6] improve logic to craate default path config --- cmd/add.go | 2 +- cmd/merge.go | 2 +- cmd/root.go | 4 +++- cmd/utils.go | 58 +++++++++++++++++++++-------------------------- cmd/utils_test.go | 18 +++++++++++---- 5 files changed, 45 insertions(+), 39 deletions(-) diff --git a/cmd/add.go b/cmd/add.go index cad0722b..7044a33a 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -81,7 +81,7 @@ func (ac *AddCommand) runAdd(cmd *cobra.Command, args []string) error { } } else { // check path - file, err := CheckAndTransformFilePath(file) + file, err := CheckAndTransformFilePath(file, cfgCreate) if err != nil { return err } diff --git a/cmd/merge.go b/cmd/merge.go index 88e5cf1f..d1f168f0 100644 --- a/cmd/merge.go +++ b/cmd/merge.go @@ -52,7 +52,7 @@ func (mc MergeCommand) runMerge(command *cobra.Command, args []string) error { } if folder != "" { - folder, err = CheckAndTransformFilePath(folder) + folder, err = CheckAndTransformFilePath(folder, cfgCreate) if err != nil { return err } diff --git a/cmd/root.go b/cmd/root.go index e75e1274..5a3babd7 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -38,6 +38,7 @@ var ( uiSize int macNotify bool silenceTable bool + cfgCreate bool ) // Cli cmd struct @@ -69,6 +70,7 @@ func (cli *Cli) setFlags() { } flags := cli.rootCmd.PersistentFlags() flags.StringVar(&cfgFile, "config", kubeconfig, "path of kubeconfig") + flags.BoolVar(&cfgCreate, "create", false, "Create a new kubeconfig file if not exists") // let the `make doc-gen` command generate consistent output rather than parsing different $HOME environment variables for different users. flags.Lookup("config").DefValue = "$HOME/.kube/config" flags.IntVarP(&uiSize, "ui-size", "u", 4, "number of list items to show in menu at once") @@ -79,7 +81,7 @@ func (cli *Cli) setFlags() { // Run command func (cli *Cli) Run() error { // check and format kubeconfig path - config, err := CheckAndTransformFilePath(cfgFile) + config, err := CheckAndTransformFilePath(cfgFile, cfgCreate) if err != nil { return err } diff --git a/cmd/utils.go b/cmd/utils.go index fb9b3b0c..ac98c573 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -340,7 +340,7 @@ func WriteConfig(cover bool, file string, outConfig *clientcmdapi.Config) error // UpdateConfigFile update kubeconfig func UpdateConfigFile(file string, updateConfig *clientcmdapi.Config) error { - file, err := CheckAndTransformFilePath(file) + file, err := CheckAndTransformFilePath(file, cfgCreate) if err != nil { return err } @@ -423,12 +423,30 @@ func appendConfig(c1, c2 *clientcmdapi.Config) *clientcmdapi.Config { } // CheckAndTransformFilePath return converted path -func CheckAndTransformFilePath(path string) (string, error) { +func CheckAndTransformFilePath(path string, autoCreate bool) (string, error) { if strings.HasPrefix(path, "~/") { path = filepath.Join(homeDir(), path[2:]) } - if !Exists(path) { - CreateDirectory(path) + if IsFile(path) { + printYellow(os.Stdout, path+" Path Exist\n") + } else { + if !autoCreate { + return path, errors.New("path Not Exist") + } + printYellow(os.Stdout, "Createing Directory: "+filepath.Dir(path)+"\n") + printYellow(os.Stdout, path+" Path is Not Absolute, setting path to home dir\n") + pathDir := filepath.Join(homeDir(), ".kube") + path = filepath.Join(pathDir, "config") + err := os.MkdirAll(pathDir, 0777) + if err != nil { + return path, err + } + file, err := os.Create(path) + if err != nil { + return path, err + } + defer file.Close() + return path, err } // read files info _, err := os.Stat(path) @@ -493,34 +511,10 @@ func validateContextTemplate(contextTemplate []string) error { } // checkes if a path exists -func Exists(path string) bool { - printYellow(os.Stdout, "Start Checking if Path Exist") - _, err := os.Stat(path) - if err == nil { - printYellow(os.Stdout, "Path Exist") - return true - } - if os.IsNotExist(err) { - printYellow(os.Stdout, "Path Dose NOT Exist") +func IsFile(path string) bool { + info, err := os.Stat(path) + if err != nil { return false } - return false -} - -func CreateDirectory(path string) { - dir := filepath.Dir(path) - var create string - if Exists(dir) { - printYellow(os.Stdout, dir+" Path Exist") - } else { - printYellow(os.Stdout, "Createing Directory: "+filepath.Dir(path)) - if !filepath.IsAbs(dir) { - printYellow(os.Stdout, dir+" Path is Not Absolute") - create = "./" + dir - } else { - create = dir - } - err := os.MkdirAll(create, 0777) - FailOnError(err, "Failed to Create Directory") - } + return !info.IsDir() } diff --git a/cmd/utils_test.go b/cmd/utils_test.go index ddb0f881..49f66dae 100644 --- a/cmd/utils_test.go +++ b/cmd/utils_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "os/user" + "path/filepath" "reflect" "strings" "testing" @@ -195,9 +196,10 @@ func TestExitOption(t *testing.T) { } func TestCheckAndTransformFilePath(t *testing.T) { - wantPath := homeDir() + wantPath := filepath.Join(homeDir(), ".kube", "config") type args struct { - path string + path string + cfgCreate bool } tests := []struct { name string @@ -206,11 +208,13 @@ func TestCheckAndTransformFilePath(t *testing.T) { wantErr bool }{ // TODO: Add test cases. - {"test-~", args{path: "~/"}, wantPath, false}, + {"test -~ with no auto create", args{path: "~/", cfgCreate: false}, homeDir(), true}, + {"test -~ with auto create enabled", args{path: "~/", cfgCreate: true}, wantPath, false}, + {"test - false config path no auto create", args{path: "", cfgCreate: false}, "", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := CheckAndTransformFilePath(tt.args.path) + got, err := CheckAndTransformFilePath(tt.args.path, tt.args.cfgCreate) if (err != nil) != tt.wantErr { t.Errorf("CheckAndTransformFilePath() error = %v, wantErr %v", err, tt.wantErr) return @@ -219,6 +223,12 @@ func TestCheckAndTransformFilePath(t *testing.T) { t.Errorf("CheckAndTransformFilePath() got = %v, want %v", got, tt.want) } }) + if tt.args.cfgCreate { + t.Cleanup(func() { + // Remove the file from wantPath after the test run is done + os.RemoveAll(filepath.Join(homeDir(), ".kube")) + }) + } } } From abcc28771bc5d2d1032ba48025422279c8510e8e Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Thu, 6 Jun 2024 22:48:16 +0000 Subject: [PATCH 3/6] revert dir check for merge --- cmd/merge.go | 2 +- cmd/utils.go | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/cmd/merge.go b/cmd/merge.go index d1f168f0..03363de3 100644 --- a/cmd/merge.go +++ b/cmd/merge.go @@ -52,7 +52,7 @@ func (mc MergeCommand) runMerge(command *cobra.Command, args []string) error { } if folder != "" { - folder, err = CheckAndTransformFilePath(folder, cfgCreate) + folder, err = CheckAndTransformDirPath(folder) if err != nil { return err } diff --git a/cmd/utils.go b/cmd/utils.go index ac98c573..fe53c957 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -518,3 +518,16 @@ func IsFile(path string) bool { } return !info.IsDir() } + +// CheckAndTransformFilePath return converted path +func CheckAndTransformDirPath(path string) (string, error) { + if strings.HasPrefix(path, "~/") { + path = filepath.Join(homeDir(), path[2:]) + } + // read files info + _, err := os.Stat(path) + if err != nil { + return "", err + } + return path, nil +} From 5d3a0ae20b5cf1d8d1ba8a74010477ab857fea9f Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Thu, 6 Jun 2024 22:57:21 +0000 Subject: [PATCH 4/6] removed a func that is not used --- cmd/utils.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/cmd/utils.go b/cmd/utils.go index fe53c957..addad10f 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -408,13 +408,6 @@ func printWarning(out io.Writer, name string) { ct.ResetColor() } -func FailOnError(err error, message string) { - if err != nil { - printWarning(os.Stdout, fmt.Sprintf("%s: %s\n", message, err.Error())) - os.Exit(1) - } -} - func appendConfig(c1, c2 *clientcmdapi.Config) *clientcmdapi.Config { config := clientcmdapi.NewConfig() _ = mergo.Merge(config, c1) From b0b07bee979744ba847a007f34593e65f435baa7 Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Fri, 7 Jun 2024 06:17:20 +0000 Subject: [PATCH 5/6] added unit tests --- cmd/utils_test.go | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/cmd/utils_test.go b/cmd/utils_test.go index 49f66dae..a09b87e3 100644 --- a/cmd/utils_test.go +++ b/cmd/utils_test.go @@ -231,6 +231,67 @@ func TestCheckAndTransformFilePath(t *testing.T) { } } } +func TestCheckAndTransformDirPath(t *testing.T) { + type args struct { + path string + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + // TODO: Add test cases. + {"test -~ home dir - should pass", args{path: "~/"}, homeDir(), false}, + {"test -~ with auto create enabled", args{path: ""}, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := CheckAndTransformDirPath(tt.args.path) + if (err != nil) != tt.wantErr { + t.Errorf("CheckAndTransformDirPath() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("CheckAndTransformDirPath() got = %v, want %v", got, tt.want) + } + }) + } +} + +func TestIsFile(t *testing.T) { + type args struct { + path string + } + tests := []struct { + name string + args args + want bool + }{ + // TODO: Add test cases. + {"test -~ not a file", args{path: "."}, false}, + {"test - is a file", args{path: "./test.file"}, true}, + {"test - is a config file", args{path: "./config"}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.want { + // Create a file at the path + _ = os.WriteFile(tt.args.path, []byte{}, 0666) + } + got := IsFile(tt.args.path) + if got != tt.want { + t.Errorf("IsFile() got = %v, want %v", got, tt.want) + } + }) + if tt.want { + t.Cleanup(func() { + // Remove the file from wantPath after the test run is done + os.ReadFile(tt.args.path) + }) + } + } +} func TestCheckValidContext(t *testing.T) { clearWrongConfig := wrongFederalConfig.DeepCopy() From 225031e3eb996f544d72d688b47bcd7254f402a8 Mon Sep 17 00:00:00 2001 From: AdamRussak Date: Fri, 7 Jun 2024 06:22:07 +0000 Subject: [PATCH 6/6] fix unit tests --- cmd/utils_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/utils_test.go b/cmd/utils_test.go index a09b87e3..c4383892 100644 --- a/cmd/utils_test.go +++ b/cmd/utils_test.go @@ -287,7 +287,7 @@ func TestIsFile(t *testing.T) { if tt.want { t.Cleanup(func() { // Remove the file from wantPath after the test run is done - os.ReadFile(tt.args.path) + os.Remove(tt.args.path) }) } }