Create default config file when not present

Fixes #165
This commit is contained in:
erroneousboat 2019-05-18 13:01:01 +02:00
parent 3b88e203ff
commit 6e75095daa

View File

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"github.com/erroneousboat/termui" "github.com/erroneousboat/termui"
@ -31,9 +32,14 @@ type keyMapping map[string]string
func NewConfig(filepath string) (*Config, error) { func NewConfig(filepath string) (*Config, error) {
cfg := getDefaultConfig() cfg := getDefaultConfig()
// Open config file, and when none is found or present create
// a default empty one, at the filepath location
file, err := os.Open(filepath) file, err := os.Open(filepath)
if err != nil { if err != nil {
return &cfg, fmt.Errorf("couldn't find the slack-term config file: %v", err) file, err = CreateConfigFile(filepath)
if err != nil {
return &cfg, fmt.Errorf("couldn't open the slack-term config file: %v", err)
}
} }
if err := json.NewDecoder(file).Decode(&cfg); err != nil { if err := json.NewDecoder(file).Decode(&cfg); err != nil {
@ -65,6 +71,21 @@ func NewConfig(filepath string) (*Config, error) {
return &cfg, nil return &cfg, nil
} }
func CreateConfigFile(filepath string) (*os.File, error) {
payload := "{\"slack_token\": \"\"}"
err := ioutil.WriteFile(filepath, []byte(payload), 0755)
if err != nil {
return nil, err
}
file, err := os.Open(filepath)
if err != nil {
return nil, err
}
return file, nil
}
func getDefaultConfig() Config { func getDefaultConfig() Config {
return Config{ return Config{
SidebarWidth: 1, SidebarWidth: 1,