cli/cmd: getKubeconfig: refactor into smaller functions
So resulting code is much easier to understand.
@@ -114,28 +114,47 @@ func expandKubeconfigPath(path string) string {
// - KUBECONFIG environment variable.
// - ~/.kube/config path, which is the default for kubectl.
func getKubeconfig() (string, error) {
- kubeconfig := viper.GetString(kubeconfigFlag)
- if kubeconfig != "" {
- return expandKubeconfigPath(kubeconfig), nil
- }
-
- assetDir, err := getAssetDir()
+ assetKubeconfig, err := assetsKubeconfigPath()
if err != nil {
- return "", err
+ return "", fmt.Errorf("reading kubeconfig path from configuration failed: %w", err)
}
paths := []string{
- assetDir,
+ viper.GetString(kubeconfigFlag),
+ assetKubeconfig,
os.Getenv(kubeconfigEnvVariable),
+ defaultKubeconfigPath,
}
- for _, path := range paths {
- if path != "" {
- return expandKubeconfigPath(path), nil
+ return expandKubeconfigPath(pickString(paths...)), nil
}
+
+// pickString returns first non-empty string.
+func pickString(options ...string) string {
+ for _, option := range options {
+ if option != "" {
+ return option
+ }
+ }
+
+ return ""
}
- return expandKubeconfigPath(defaultKubeconfigPath), nil
+// assetsKubeconfigPath reads the lokocfg configuration and returns
+// the kubeconfig path defined in it.
+//
+// If no configuration is defined, empty string is returned.
+func assetsKubeconfigPath() (string, error) {
+ assetDir, err := getAssetDir()
+ if err != nil {
+ return "", err
+ }
+
+ if assetDir != "" {
+ return assetsKubeconfig(assetDir), nil
+ }
+
+ return "", nil
}
func assetsKubeconfig(assetDir string) string {
