diff --git a/cmd/root.go b/cmd/root.go index 5906027..22f1801 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -16,7 +16,7 @@ func RootCmd() *cobra.Command { cmd.AddCommand( TokenCmd(), ) - + return cmd } diff --git a/cmd/token.go b/cmd/token.go index 4df1055..230d4a0 100644 --- a/cmd/token.go +++ b/cmd/token.go @@ -6,21 +6,21 @@ import ( func TokenSetJiraCmd() *cobra.Command { return &cobra.Command{ - Use: "jira", + Use: "jira", Short: "Sets the value of the jira token", } } func TokenSetGithubCmd() *cobra.Command { return &cobra.Command{ - Use: "github", + Use: "github", Short: "Sets the value of the github token", } } func TokenSetCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "set", + Use: "set", Short: "Sets the value of the platform tokens", } @@ -34,7 +34,7 @@ func TokenSetCmd() *cobra.Command { func TokenCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "token", + Use: "token", Short: "Subcommands related to tokens", } diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..d640007 --- /dev/null +++ b/config/config.go @@ -0,0 +1,62 @@ +package config + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "os/user" +) + +type Config struct { + GithubToken string `json:"github_token"` + JiraToken string `json:"jira_token"` +} + +func getConfigPath() (string, error) { + user, err := user.Current() + if err != nil { + return "", err + } + return user.HomeDir + "/.campaigner", nil +} + +func ReadConfig() (*Config, error) { + configPath, err := getConfigPath() + if err != nil { + return nil, err + } + + if _, err := os.Stat(configPath); err != nil { + return nil, fmt.Errorf("cannot read campaigner config file: %w", err) + } + + fileContents, err := ioutil.ReadFile(configPath) + if err != nil { + return nil, fmt.Errorf("there was a problem reading the config file: %w", err) + } + + var config Config + if err := json.Unmarshal(fileContents, &config); err != nil { + return nil, fmt.Errorf("there was a problem parsing the config file: %w", err) + } + + return &config, nil +} + +func SaveConfig(config *Config) error { + configPath, err := getConfigPath() + if err != nil { + return err + } + + marshaledConfig, err := json.MarshalIndent(config, "", " ") + if err != nil { + return err + } + + if err := ioutil.WriteFile(configPath, marshaledConfig, 0600); err != nil { + return fmt.Errorf("cannot save the config: %w", err) + } + return nil +}