|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + CONFIG_1 = ".envok.yaml" |
| 12 | + CONFIG_2 = ".envok.yml" |
| 13 | +) |
| 14 | + |
| 15 | +func getCurrentProfile() string { |
| 16 | + const currentProfileNameFilePath = ".config/envok/prof_name.txt" |
| 17 | + |
| 18 | + home, err := os.UserHomeDir() |
| 19 | + filePath := fmt.Sprintf("%s/%s", home, currentProfileNameFilePath) |
| 20 | + data, err := os.ReadFile(filePath) |
| 21 | + var currentProfileName string |
| 22 | + |
| 23 | + if err != nil { |
| 24 | + fmt.Printf("%s\n", err) |
| 25 | + currentProfileName = "" |
| 26 | + } else { |
| 27 | + currentProfileName = strings.TrimSpace(string(data)) |
| 28 | + } |
| 29 | + |
| 30 | + return currentProfileName |
| 31 | +} |
| 32 | + |
| 33 | +func getConfigPath() (string, error) { |
| 34 | + |
| 35 | + fileName, err := searchFileUpwards(CONFIG_1) |
| 36 | + if err != nil { |
| 37 | + fileName, err = searchFileUpwards(CONFIG_2) |
| 38 | + if err != nil { |
| 39 | + return "", fmt.Errorf("failed to get config file %s (or %s)\n", CONFIG_1, CONFIG_2) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return fileName, nil |
| 44 | + |
| 45 | +} |
| 46 | + |
| 47 | +func searchFileUpwards(filename string) (string, error) { |
| 48 | + currentDir, err := os.Getwd() |
| 49 | + if err != nil { |
| 50 | + return "", fmt.Errorf("failed to get current directory: %w", err) |
| 51 | + } |
| 52 | + |
| 53 | + homeDir, err := os.UserHomeDir() |
| 54 | + if err != nil { |
| 55 | + return "", fmt.Errorf("failed to get home directory: %w", err) |
| 56 | + } |
| 57 | + |
| 58 | + for { |
| 59 | + filePath := filepath.Join(currentDir, filename) |
| 60 | + |
| 61 | + if _, err := os.Stat(filePath); err == nil { |
| 62 | + return filePath, nil // File found |
| 63 | + } |
| 64 | + if currentDir == homeDir || currentDir == "/" { |
| 65 | + break |
| 66 | + } |
| 67 | + |
| 68 | + // Move up one directory |
| 69 | + currentDir = filepath.Dir(currentDir) |
| 70 | + } |
| 71 | + |
| 72 | + return "", fmt.Errorf("file %q not found", filename) |
| 73 | +} |
0 commit comments