diff --git a/cmd/install.go b/cmd/install.go new file mode 100644 index 0000000..5b680c4 --- /dev/null +++ b/cmd/install.go @@ -0,0 +1,192 @@ +/* +Copyright © 2019 Zee Ahmed + +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 cmd + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "os" + "strings" + + "github.com/dustin/go-humanize" + "github.com/h2non/filetype" + "github.com/spf13/cobra" + "golang.org/x/sys/unix" +) + +var sys, machine string + +// WriteCounter tracks the total number of bytes +type WriteCounter struct { + Total uint64 +} + +// installCmd represents the install command +var installCmd = &cobra.Command{ + Use: "install", + Short: "A tool manage different kubectl versions inside a workspace.", + Run: func(cmd *cobra.Command, args []string) { + if len(args) > 0 { + err := DownloadKubectl(args[0]) + + if err != nil { + log.Fatal(err) + } + + } else { + fmt.Println("specify a kubectl version to install") + } + }, +} + +func init() { + rootCmd.AddCommand(installCmd) +} + +//DownloadKubectl - download user specified version of kubectl +func DownloadKubectl(version string) error { + + // TODO use tmp directory to download instead of kubemngr. + // This was failing originally with the error: invalid cross-link device + // filepath := "/tmp/" + + // TODO better sanity check for checking arg is valid + if len(version) == 0 { + log.Fatal(0) + } + + homeDir, err := os.UserHomeDir() + if err != nil { + log.Fatal(err) + } + + // Check if current version already exists + _, err = os.Stat(homeDir + "/.kubemngr/kubectl-" + version) + if err == nil { + log.Printf("kubectl version %s already exists", version) + return nil + } + + // Create temp file of kubectl version in tmp directory + out, err := os.Create(homeDir + "/.kubemngr/kubectl-" + version) + if err != nil { + log.Fatal(err) + } + + defer out.Close() + + // Get OS information to filter download type i.e linux / darwin + uname := GetOSInfo() + + // Compare system name to set value for building url to download kubectl binary + if arrayToString(uname.Sysname) == "Linux" { + sys = "linux" + } else if arrayToString(uname.Sysname) == "Darwin" { + sys = "darwin" + } else { + sys = "UNKNOWN" + fmt.Println("Unknown system") + } + + if arrayToString(uname.Machine) == "arm" { + machine = "arm" + } else if arrayToString(uname.Machine) == "arm64" { + machine = "arm64" + } else if arrayToString(uname.Machine) == "x86_64" { + machine = "amd64" + } else { + machine = "UNKNOWN" + fmt.Println("Unknown machine") + } + + url := "https://storage.googleapis.com/kubernetes-release/release/" + version + "/bin/" + sys + "/" + machine + "/kubectl" + + resp, err := http.Get(url) + if err != nil { + log.Fatal(err) + } + + defer resp.Body.Close() + + // Initialise WriteCounter and copy the contents of the response body to the tmp file + counter := &WriteCounter{} + _, err = io.Copy(out, io.TeeReader(resp.Body, counter)) + if err != nil { + log.Fatal(err) + } + + // The progress use the same line so print a new line once it's finished downloading + fmt.Println() + + // Check to make sure the file is a binary before moving the contents over to the user's home dir + buf, _ := ioutil.ReadFile(homeDir + "/.kubemngr/kubectl-" + version) + + // elf - application/x-executable check + if !filetype.IsArchive(buf) { + fmt.Println("failed to download kubectl file. Are you sure you specified the right version?") + os.Remove(homeDir + "/.kubemngr/kubectl-" + version) + os.Exit(1) + } + + // Set executable permissions on the kubectl binary + if err := os.Chmod(homeDir+"/.kubemngr/kubectl-"+version, 0755); err != nil { + log.Fatal(err) + } + + // Rename the tmp file back to the original file and store it in the kubemngr directory + currentFilePath := homeDir + "/.kubemngr/kubectl-" + version + newFilePath := homeDir + "/.kubemngr/kubectl-" + version + + err = os.Rename(currentFilePath, newFilePath) + if err != nil { + log.Fatal(err) + } + + return nil +} + +// GetOSInfo - Get operating system information of machine +func GetOSInfo() unix.Utsname { + var uname unix.Utsname + + if err := unix.Uname(&uname); err != nil { + fmt.Printf("Uname: %v", err) + } + + return uname +} + +func (wc *WriteCounter) Write(p []byte) (int, error) { + n := len(p) + wc.Total += uint64(n) + wc.PrintProgress() + return n, nil +} + +// PrintProgress - Helper function to print progress of a download +func (wc WriteCounter) PrintProgress() { + // Clear the line by using a character return to go back to the start and remove + // the remaining characters by filling it with spaces + fmt.Printf("\r%s", strings.Repeat(" ", 50)) + + // Return again and print current status of download + // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) + fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total)) +} diff --git a/cmd/install_darwin.go b/cmd/install_darwin.go index 5e830fc..b58acbb 100644 --- a/cmd/install_darwin.go +++ b/cmd/install_darwin.go @@ -1,4 +1,4 @@ -// +build linux +// +build darwin /* Copyright © 2019 Zee Ahmed @@ -15,195 +15,15 @@ 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 cmd import ( - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "os" "strings" - - "github.com/dustin/go-humanize" - "github.com/h2non/filetype" - "github.com/spf13/cobra" - "golang.org/x/sys/unix" ) -var sys, machine string - -type WriteCounter struct { - Total uint64 -} - -// installCmd represents the install command -var installCmd = &cobra.Command{ - Use: "install", - Short: "A tool manage different kubectl versions inside a workspace.", - Run: func(cmd *cobra.Command, args []string) { - if len(args) > 0 { - err := DownloadKubectl(args[0]) - - if err != nil { - log.Fatal(err) - } - - } else { - fmt.Println("specify a kubectl version to install") - } - }, -} - -func init() { - rootCmd.AddCommand(installCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // installCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // installCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} - -//DownloadKubectl - download user specified version of kubectl -func DownloadKubectl(version string) error { - - // TODO use tmp directory to download instead of kubemngr. - // This was failing originally with the error: invalid cross-link device - // filepath := "/tmp/" - - // TODO better sanity check for checking arg is valid - if len(version) == 0 { - log.Fatal(0) - } - - // Get user home directory path - homeDir, err := os.UserHomeDir() - if err != nil { - log.Fatal(err) - } - - // Check if current version already exists - _, err = os.Stat(homeDir + "/.kubemngr/kubectl-" + version) - if err == nil { - log.Printf("kubectl version %s already exists", version) - return nil - } - - // Create temp file of kubectl version in tmp directory - out, err := os.Create(homeDir + "/.kubemngr/kubectl-" + version) - if err != nil { - log.Fatal(err) - } - - defer out.Close() - - // Get OS information to filter download type i.e linux / darwin - uname := GetOSInfo() - - // Compare system name to set value for building url to download kubectl binary - if ArrayToString(uname.Sysname) == "Linux" { - sys = "linux" - } else if ArrayToString(uname.Sysname) == "Darwin" { - sys = "darwin" - } else { - sys = "UNKNOWN" - fmt.Println("Unknown system") - } - - if ArrayToString(uname.Machine) == "arm" { - machine = "arm" - } else if ArrayToString(uname.Machine) == "arm64" { - machine = "arm64" - } else if ArrayToString(uname.Machine) == "x86_64" { - machine = "amd64" - } else { - machine = "UNKNOWN" - fmt.Println("Unknown machine") - } - - url := "https://storage.googleapis.com/kubernetes-release/release/" + version + "/bin/" + sys + "/" + machine + "/kubectl" - - resp, err := http.Get(url) - if err != nil { - log.Fatal(err) - } - - defer resp.Body.Close() - - // Initialise WriteCounter and copy the contents of the response body to the tmp file - counter := &WriteCounter{} - _, err = io.Copy(out, io.TeeReader(resp.Body, counter)) - if err != nil { - log.Fatal(err) - } - - // The progress use the same line so print a new line once it's finished downloading - fmt.Println() - - // Check to make sure the file is a binary before moving the contents over to the user's home dir - buf, _ := ioutil.ReadFile(homeDir + "/.kubemngr/kubectl-" + version) - - // elf - application/x-executable check - if !filetype.IsArchive(buf) { - fmt.Println("failed to download kubectl file. Are you sure you specified the right version?") - os.Remove(homeDir + "/.kubemngr/kubectl-" + version) - os.Exit(1) - } - - // Set executable permissions on the kubectl binary - if err := os.Chmod(homeDir+"/.kubemngr/kubectl-"+version, 0755); err != nil { - log.Fatal(err) - } - - // Rename the tmp file back to the original file and store it in the kubemngr directory - currentFilePath := homeDir + "/.kubemngr/kubectl-" + version - newFilePath := homeDir + "/.kubemngr/kubectl-" + version - - err = os.Rename(currentFilePath, newFilePath) - if err != nil { - log.Fatal(err) - } - - return nil -} - -// GetOSInfo - Get operating system information of machine -func GetOSInfo() unix.Utsname { - var uname unix.Utsname - - if err := unix.Uname(&uname); err != nil { - fmt.Printf("Uname: %v", err) - } - - return uname -} - -func (wc *WriteCounter) Write(p []byte) (int, error) { - n := len(p) - wc.Total += uint64(n) - wc.PrintProgress() - return n, nil -} - -// PrintProgress - Helper function to print progress of a download -func (wc WriteCounter) PrintProgress() { - // Clear the line by using a character return to go back to the start and remove - // the remaining characters by filling it with spaces - fmt.Printf("\r%s", strings.Repeat(" ", 50)) - - // Return again and print current status of download - // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) - fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total)) -} - -func ArrayToString(x [65]byte) string { - var buf [65]byte +func arrayToString(x [256]byte) string { + var buf [256]byte for i, b := range x { buf[i] = byte(b) } diff --git a/cmd/install_linux.go b/cmd/install_linux.go index 5e830fc..e5c8de4 100644 --- a/cmd/install_linux.go +++ b/cmd/install_linux.go @@ -15,194 +15,14 @@ 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 cmd import ( - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "os" "strings" - - "github.com/dustin/go-humanize" - "github.com/h2non/filetype" - "github.com/spf13/cobra" - "golang.org/x/sys/unix" ) -var sys, machine string - -type WriteCounter struct { - Total uint64 -} - -// installCmd represents the install command -var installCmd = &cobra.Command{ - Use: "install", - Short: "A tool manage different kubectl versions inside a workspace.", - Run: func(cmd *cobra.Command, args []string) { - if len(args) > 0 { - err := DownloadKubectl(args[0]) - - if err != nil { - log.Fatal(err) - } - - } else { - fmt.Println("specify a kubectl version to install") - } - }, -} - -func init() { - rootCmd.AddCommand(installCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // installCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // installCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} - -//DownloadKubectl - download user specified version of kubectl -func DownloadKubectl(version string) error { - - // TODO use tmp directory to download instead of kubemngr. - // This was failing originally with the error: invalid cross-link device - // filepath := "/tmp/" - - // TODO better sanity check for checking arg is valid - if len(version) == 0 { - log.Fatal(0) - } - - // Get user home directory path - homeDir, err := os.UserHomeDir() - if err != nil { - log.Fatal(err) - } - - // Check if current version already exists - _, err = os.Stat(homeDir + "/.kubemngr/kubectl-" + version) - if err == nil { - log.Printf("kubectl version %s already exists", version) - return nil - } - - // Create temp file of kubectl version in tmp directory - out, err := os.Create(homeDir + "/.kubemngr/kubectl-" + version) - if err != nil { - log.Fatal(err) - } - - defer out.Close() - - // Get OS information to filter download type i.e linux / darwin - uname := GetOSInfo() - - // Compare system name to set value for building url to download kubectl binary - if ArrayToString(uname.Sysname) == "Linux" { - sys = "linux" - } else if ArrayToString(uname.Sysname) == "Darwin" { - sys = "darwin" - } else { - sys = "UNKNOWN" - fmt.Println("Unknown system") - } - - if ArrayToString(uname.Machine) == "arm" { - machine = "arm" - } else if ArrayToString(uname.Machine) == "arm64" { - machine = "arm64" - } else if ArrayToString(uname.Machine) == "x86_64" { - machine = "amd64" - } else { - machine = "UNKNOWN" - fmt.Println("Unknown machine") - } - - url := "https://storage.googleapis.com/kubernetes-release/release/" + version + "/bin/" + sys + "/" + machine + "/kubectl" - - resp, err := http.Get(url) - if err != nil { - log.Fatal(err) - } - - defer resp.Body.Close() - - // Initialise WriteCounter and copy the contents of the response body to the tmp file - counter := &WriteCounter{} - _, err = io.Copy(out, io.TeeReader(resp.Body, counter)) - if err != nil { - log.Fatal(err) - } - - // The progress use the same line so print a new line once it's finished downloading - fmt.Println() - - // Check to make sure the file is a binary before moving the contents over to the user's home dir - buf, _ := ioutil.ReadFile(homeDir + "/.kubemngr/kubectl-" + version) - - // elf - application/x-executable check - if !filetype.IsArchive(buf) { - fmt.Println("failed to download kubectl file. Are you sure you specified the right version?") - os.Remove(homeDir + "/.kubemngr/kubectl-" + version) - os.Exit(1) - } - - // Set executable permissions on the kubectl binary - if err := os.Chmod(homeDir+"/.kubemngr/kubectl-"+version, 0755); err != nil { - log.Fatal(err) - } - - // Rename the tmp file back to the original file and store it in the kubemngr directory - currentFilePath := homeDir + "/.kubemngr/kubectl-" + version - newFilePath := homeDir + "/.kubemngr/kubectl-" + version - - err = os.Rename(currentFilePath, newFilePath) - if err != nil { - log.Fatal(err) - } - - return nil -} - -// GetOSInfo - Get operating system information of machine -func GetOSInfo() unix.Utsname { - var uname unix.Utsname - - if err := unix.Uname(&uname); err != nil { - fmt.Printf("Uname: %v", err) - } - - return uname -} - -func (wc *WriteCounter) Write(p []byte) (int, error) { - n := len(p) - wc.Total += uint64(n) - wc.PrintProgress() - return n, nil -} - -// PrintProgress - Helper function to print progress of a download -func (wc WriteCounter) PrintProgress() { - // Clear the line by using a character return to go back to the start and remove - // the remaining characters by filling it with spaces - fmt.Printf("\r%s", strings.Repeat(" ", 50)) - - // Return again and print current status of download - // We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB) - fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total)) -} - -func ArrayToString(x [65]byte) string { +func arrayToString(x [65]byte) string { var buf [65]byte for i, b := range x { buf[i] = byte(b) diff --git a/cmd/remove_linux.go b/cmd/remove.go similarity index 68% rename from cmd/remove_linux.go rename to cmd/remove.go index 5f46e58..53e8172 100644 --- a/cmd/remove_linux.go +++ b/cmd/remove.go @@ -1,5 +1,3 @@ -// +build linux - /* Copyright © 2019 Zee Ahmed @@ -15,6 +13,7 @@ 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 cmd import ( @@ -25,7 +24,6 @@ import ( "github.com/spf13/cobra" ) -// removeCmd represents the remove command var removeCmd = &cobra.Command{ Use: "remove", Short: "Remove a kubectl version from machine", @@ -39,21 +37,10 @@ var removeCmd = &cobra.Command{ func init() { rootCmd.AddCommand(removeCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // removeCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // removeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } // RemoveKubectlVersion - removes specific kubectl version from machine func RemoveKubectlVersion(version string) error { - // Get user home directory path homeDir, err := os.UserHomeDir() if err != nil { log.Fatal(err) @@ -61,14 +48,14 @@ func RemoveKubectlVersion(version string) error { kubectlVersion := homeDir + "/.kubemngr/kubectl-" + version - // Check if version exists to remove it + // Check if version to be removed exists _, err = os.Stat(kubectlVersion) if err == nil { fmt.Printf("Removing kubectl %s", version) os.Remove(kubectlVersion) return nil - } else { - fmt.Printf("kubectl version %s doesn't exist", version) - return nil } + + fmt.Printf("kubectl %s is not installed", version) + return nil } diff --git a/cmd/remove_darwin.go b/cmd/remove_darwin.go deleted file mode 100644 index 280d616..0000000 --- a/cmd/remove_darwin.go +++ /dev/null @@ -1,74 +0,0 @@ -// +build darwin - -/* -Copyright © 2019 Zee Ahmed - -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 cmd - -import ( - "fmt" - "log" - "os" - - "github.com/spf13/cobra" -) - -// removeCmd represents the remove command -var removeCmd = &cobra.Command{ - Use: "remove", - Short: "Remove a kubectl version from machine", - Run: func(cmd *cobra.Command, args []string) { - err := RemoveKubectlVersion(args[0]) - if err != nil { - log.Fatal(err) - } - }, -} - -func init() { - rootCmd.AddCommand(removeCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // removeCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // removeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} - -// RemoveKubectlVersion - removes specific kubectl version from machine -func RemoveKubectlVersion(version string) error { - // Get user home directory path - homeDir, err := os.UserHomeDir() - if err != nil { - log.Fatal(err) - } - - kubectlVersion := homeDir + "/.kubemngr/kubectl-" + version - - // Check if version exists to remove it - _, err = os.Stat(kubectlVersion) - if err == nil { - fmt.Printf("Removing kubectl %s", version) - os.Remove(kubectlVersion) - return nil - } else { - fmt.Printf("kubectl version %s doesn't exist", version) - return nil - } -} diff --git a/cmd/root_linux.go b/cmd/root.go similarity index 67% rename from cmd/root_linux.go rename to cmd/root.go index 761931b..4098516 100644 --- a/cmd/root_linux.go +++ b/cmd/root.go @@ -1,5 +1,3 @@ -// +build linux - /* Copyright © 2019 Zee Ahmed @@ -15,6 +13,7 @@ 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 cmd import ( @@ -30,15 +29,11 @@ import ( var cfgFile string var clientVersion string -// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "kubemngr", Short: "A tool manage different kubectl versions inside a workspace.", Long: `This tool is to help developers run different versions of kubectl within their workspace and to support working with different versions of Kubernetes clusters.`, - // Uncomment the following line if your bare application - // has an action associated with it: - // Run: func(cmd *cobra.Command, args []string) { }, } // Execute adds all child commands to the root command and sets flags appropriately. @@ -54,32 +49,18 @@ func Execute(version string) { func init() { cobra.OnInitialize(initConfig) - - // Here you will define your flags and configuration settings. - // Cobra supports persistent flags, which, if defined here, - // will be global for your application. - - //rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.kubemngr.yaml)") - - // Cobra also supports local flags, which will only run - // when this action is called directly. - rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } -// initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { - // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { - // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } - // Search config in home directory with name ".kubemngr" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".kubemngr") } diff --git a/cmd/root_darwin.go b/cmd/root_darwin.go deleted file mode 100644 index f417ce6..0000000 --- a/cmd/root_darwin.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build darwin - -/* -Copyright © 2019 Zee Ahmed - -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 cmd - -import ( - "fmt" - "os" - "github.com/spf13/cobra" - - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/viper" - -) - - -var cfgFile string -var clientVersion string - -// rootCmd represents the base command when called without any subcommands -var rootCmd = &cobra.Command{ - Use: "kubemngr", - Short: "A tool manage different kubectl versions inside a workspace.", - Long: `This tool is to help developers run different versions of kubectl within their workspace and to support working -with different versions of Kubernetes clusters.`, - // Uncomment the following line if your bare application - // has an action associated with it: - // Run: func(cmd *cobra.Command, args []string) { }, -} - -// Execute adds all child commands to the root command and sets flags appropriately. -// This is called by main.main(). It only needs to happen once to the rootCmd. -func Execute(version string) { - clientVersion = version - - if err := rootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } -} - -func init() { - cobra.OnInitialize(initConfig) - - // Here you will define your flags and configuration settings. - // Cobra supports persistent flags, which, if defined here, - // will be global for your application. - - //rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.kubemngr.yaml)") - - - // Cobra also supports local flags, which will only run - // when this action is called directly. - rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} - - -// initConfig reads in config file and ENV variables if set. -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - // Search config in home directory with name ".kubemngr" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".kubemngr") - } - - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} - diff --git a/cmd/use_darwin.go b/cmd/use.go similarity index 77% rename from cmd/use_darwin.go rename to cmd/use.go index d3197e7..fca12de 100644 --- a/cmd/use_darwin.go +++ b/cmd/use.go @@ -1,5 +1,3 @@ -// +build linux - /* Copyright © 2019 Zee Ahmed @@ -15,6 +13,7 @@ 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 cmd import ( @@ -25,7 +24,6 @@ import ( "github.com/spf13/cobra" ) -// useCmd represents the use command var useCmd = &cobra.Command{ Use: "use", Short: "Use a specific version of one of the downloaded kubectl binaries", @@ -39,16 +37,6 @@ var useCmd = &cobra.Command{ func init() { rootCmd.AddCommand(useCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // useCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // useCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } // UseKubectlBinary - sets kubectl to the version specified diff --git a/cmd/use_linux.go b/cmd/use_linux.go deleted file mode 100644 index d3197e7..0000000 --- a/cmd/use_linux.go +++ /dev/null @@ -1,83 +0,0 @@ -// +build linux - -/* -Copyright © 2019 Zee Ahmed - -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 cmd - -import ( - "fmt" - "log" - "os" - - "github.com/spf13/cobra" -) - -// useCmd represents the use command -var useCmd = &cobra.Command{ - Use: "use", - Short: "Use a specific version of one of the downloaded kubectl binaries", - Run: func(cmd *cobra.Command, args []string) { - err := UseKubectlBinary(args[0]) - if err != nil { - log.Fatal(err) - } - }, -} - -func init() { - rootCmd.AddCommand(useCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // useCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // useCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} - -// UseKubectlBinary - sets kubectl to the version specified -func UseKubectlBinary(version string) error { - - homeDir, err := os.UserHomeDir() - if err != nil { - log.Fatal(err) - } - - kubectlVersion := homeDir + "/.kubemngr/kubectl-" + version - kubectlLink := homeDir + "/.local/bin/kubectl" - - _, err = os.Stat(kubectlVersion) - if os.IsNotExist(err) { - log.Printf("kubectl %s does not exist", version) - os.Exit(1) - } - - if _, err := os.Lstat(kubectlLink); err == nil { - os.Remove(kubectlLink) - } - - err = os.Symlink(kubectlVersion, kubectlLink) - if err != nil { - log.Fatal(err) - } - - fmt.Printf("kubectl version set to %s", version) - - return nil -} diff --git a/cmd/version_linux.go b/cmd/version.go similarity index 98% rename from cmd/version_linux.go rename to cmd/version.go index 7769ab7..765c221 100644 --- a/cmd/version_linux.go +++ b/cmd/version.go @@ -1,5 +1,3 @@ -// +build linux - /* Copyright © 2019 Zee Ahmed @@ -15,6 +13,7 @@ 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 cmd import ( diff --git a/cmd/version_darwin.go b/cmd/version_darwin.go deleted file mode 100644 index bb58523..0000000 --- a/cmd/version_darwin.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build darwin - -/* -Copyright © 2019 Zee Ahmed - -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 cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -// versionCmd represents the version command -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Show the kubemngr client version", - Run: func(cmd *cobra.Command, args []string) { - fmt.Println(rootCmd.Use + " " + clientVersion) - }, -} - -func init() { - rootCmd.AddCommand(versionCmd) -}