|
| 1 | +package status |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "time" |
| 8 | + |
| 9 | + viperlib "github.com/spf13/viper" |
| 10 | +) |
| 11 | + |
| 12 | +var initialised bool = false |
| 13 | +var viper *viperlib.Viper = viperlib.New() |
| 14 | + |
| 15 | +// EnsureInitialised reads the config. Will quit if config is invalid |
| 16 | +func EnsureInitialised() { |
| 17 | + if !initialised { |
| 18 | + viper.SetConfigName("devcontainer-cli-status") |
| 19 | + viper.SetConfigType("json") |
| 20 | + |
| 21 | + viper.AddConfigPath(getConfigPath()) |
| 22 | + |
| 23 | + // TODO - allow env var for config |
| 24 | + if err := viper.ReadInConfig(); err != nil { |
| 25 | + if _, ok := err.(viperlib.ConfigFileNotFoundError); ok { |
| 26 | + // Config file not found; ignore error if desired |
| 27 | + } else { |
| 28 | + fmt.Printf("Error loading status file: %s\n", err) |
| 29 | + os.Exit(1) |
| 30 | + } |
| 31 | + } |
| 32 | + initialised = true |
| 33 | + } |
| 34 | +} |
| 35 | +func getConfigPath() string { |
| 36 | + path := os.Getenv("DEVCONTAINERX_STATUS_PATH") |
| 37 | + if path != "" { |
| 38 | + return path |
| 39 | + } |
| 40 | + if os.Getenv("HOME") != "" { |
| 41 | + path = filepath.Join("$HOME", ".devcontainer-cli/") |
| 42 | + } else { |
| 43 | + // if HOME not set, assume Windows and use USERPROFILE env var |
| 44 | + path = filepath.Join("$USERPROFILE", ".devcontainer-cli/") |
| 45 | + } |
| 46 | + return os.ExpandEnv(path) |
| 47 | +} |
| 48 | + |
| 49 | +func GetLastUpdateCheck() time.Time { |
| 50 | + EnsureInitialised() |
| 51 | + return viper.GetTime("lastUpdateCheck") |
| 52 | +} |
| 53 | +func SetLastUpdateCheck(t time.Time) { |
| 54 | + EnsureInitialised() |
| 55 | + viper.Set("lastUpdateCheck", t) |
| 56 | +} |
| 57 | +func GetAll() map[string]interface{} { |
| 58 | + EnsureInitialised() |
| 59 | + return viper.AllSettings() |
| 60 | +} |
| 61 | + |
| 62 | +func SaveStatus() error { |
| 63 | + EnsureInitialised() |
| 64 | + configPath := getConfigPath() |
| 65 | + configPath = os.ExpandEnv(configPath) |
| 66 | + if err := os.MkdirAll(configPath, 0755); err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + configFilePath := filepath.Join(configPath, "devcontainer-cli-status.json") |
| 70 | + fmt.Printf("HERE: %q\n", configFilePath) |
| 71 | + return viper.WriteConfigAs(configFilePath) |
| 72 | +} |
0 commit comments