cli/cmd/utils.go: refactor getKubeconfig
It moves expansion function to separate function, so it can be tested
independently and change the errors handling flow, to better represent
the hierarchical selection of kubeconfig path.
@@ -86,36 +86,43 @@ func getAssetDir() (string, error) {
return cfg.GetAssetDir(), nil
}
-// getKubeconfig finds the kubeconfig to be used. Precedence takes a specified
-// flag or environment variable. Then the asset directory of the cluster is searched
-// and finally the global default value is used. This cannot be done in Viper
-// because we need the other values from Viper to find the asset directory.
-func getKubeconfig() (string, error) {
- expand := func(path string) string {
- expandedPath, err := homedir.Expand(path)
- if err != nil {
+// expandKubeconfigPath tries to expand ~ in the given kubeconfig path.
+// However, if that fails, it just returns original path as the best effort.
+func expandKubeconfigPath(path string) string {
+ if expandedPath, err := homedir.Expand(path); err == nil {
+ return expandedPath
+ }
+
// homedir.Expand is too restrictive for the ~ prefix,
// i.e., it errors on "~somepath" which is a valid path,
// so just return the original path.
return path
}
- return expandedPath
- }
+// getKubeconfig finds the kubeconfig to be used. Precedence takes a specified
+// flag or environment variable. Then the asset directory of the cluster is searched
+// and finally the global default value is used. This cannot be done in Viper
+// because we need the other values from Viper to find the asset directory.
+func getKubeconfig() (string, error) {
kubeconfig := viper.GetString("kubeconfig")
if kubeconfig != "" {
- return expand(kubeconfig), nil
+ return expandKubeconfigPath(kubeconfig), nil
}
assetDir, err := getAssetDir()
if err != nil {
return "", err
}
- if assetDir == "" {
- return expand("~/.kube/config"), nil
+
+ if assetDir != "" {
+ return expandKubeconfigPath(assetsKubeconfig(assetDir)), nil
+ }
+
+ return expandKubeconfigPath("~/.kube/config"), nil
}
- return expand(filepath.Join(assetDir, "cluster-assets", "auth", "kubeconfig")), nil
+func assetsKubeconfig(assetDir string) string {
+ return filepath.Join(assetDir, "cluster-assets", "auth", "kubeconfig")
}
// doesKubeconfigExist checks if the kubeconfig provided by user exists
