package config import ( "encoding/base64" "encoding/json" "fmt" "io/fs" "os" "path" "git.dayanhub.com/sagi/envoid/internal/errors" "git.dayanhub.com/sagi/envoid/internal/types" "github.com/creasty/defaults" ) type Config struct { PWD string `json:"-"` Projects []*types.Project `default:"[]" json:"projects"` } var configPath string var configStruct *Config func (c *Config) GetProject(projectPath string) (*types.Project, error) { var p *types.Project for _, project := range configStruct.Projects { if project.Path == projectPath { p = project break } } if p == nil { return nil, errors.NewProjectNotFoundError(projectPath) } return p, nil } func (c *Config) RemoveProject(project *types.Project) { projects := []*types.Project{} for _, p := range c.Projects { if p.Name != project.Name && p.Path != project.Path { projects = append(projects, p) } } c.Projects = projects } func (c *Config) NewProject(name string, path string, password string) (*types.Project, error) { encPass := base64.RawStdEncoding.EncodeToString([]byte(password)) p := &types.Project{ Name: name, Path: path, Password: encPass, Environments: []*types.Environment{}, } configStruct.Projects = append(configStruct.Projects, p) SaveConfig() return p, nil } func GetConfig() *Config { return configStruct } func (c *Config) Save() { SaveConfig() } func CreateConfigIfNotExists() error { return nil } func init() { userConfigDir, err := os.UserConfigDir() configDir := path.Join(userConfigDir, "envoid") configPath = path.Join(configDir, "config.json") if err != nil { fmt.Printf("[ERROR] Failed to fetch user config directory. %e\n", err) os.Exit(1) } if _, err := os.Stat(configDir); os.IsNotExist(err) { var folderPermissions fs.FileMode = 0o700 err := os.MkdirAll(configDir, folderPermissions) if err != nil { panic(err) } } var configFile *os.File if _, err := os.Stat(configPath); os.IsNotExist(err) { configFile, err = os.Create(configPath) if err != nil { fmt.Printf("[ERROR] Failed to create config file @ %s. %e\n", configPath, err) os.Exit(1) } defer configFile.Close() } configStruct, err = loadConfig() if err != nil { fmt.Printf("[ERROR] Failed to load config file @ %s. %e\n", configPath, err) configFile.Close() panic("") } } func loadConfig() (*Config, error) { c := &Config{} err := defaults.Set(c) if err != nil { panic(err) } file, err := os.ReadFile(configPath) if err != nil { return nil, err } if len(file) == 0 { return c, nil } if err = json.Unmarshal(file, c); err != nil { return nil, err } pwd, err := os.Getwd() if err != nil { return nil, err } c.PWD = pwd return c, nil } func SaveConfig() { yml, err := json.Marshal(configStruct) if err != nil { fmt.Printf("[ERROR] Failed to convert config to json. %e\n", err) os.Exit(1) } var filePermissions fs.FileMode = 0o600 err = os.WriteFile(configPath, yml, filePermissions) if err != nil { fmt.Printf("[ERROR] Failed to save config file @ %s. %e\n", configPath, err) os.Exit(1) } }