Add config package basic funcs
This commit is contained in:
parent
ae13697461
commit
6bd0a99a32
3 changed files with 67 additions and 5 deletions
|
@ -16,7 +16,7 @@ func RootCmd() *cobra.Command {
|
|||
cmd.AddCommand(
|
||||
TokenCmd(),
|
||||
)
|
||||
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
|
|
@ -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",
|
||||
}
|
||||
|
||||
|
|
62
config/config.go
Normal file
62
config/config.go
Normal file
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue