dotfiles/config.go

61 lines
1.1 KiB
Go
Raw Normal View History

2021-01-12 03:53:51 +00:00
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
type Config struct {
2021-01-18 04:28:06 +00:00
// Read when run
Path string `json:"-"`
// Read from file
2021-01-12 03:53:51 +00:00
Apps map[string]App `json:"apps"`
}
type App struct {
2021-01-18 04:28:06 +00:00
Files []FromToPath `json:"files"`
Folders []FromToPath `json:"folders"`
}
type FromToPath struct {
From string `json:"from"`
To string `json:"to"`
2021-01-12 03:53:51 +00:00
}
// Load config from file
2021-01-18 04:28:06 +00:00
func LoadConfig(path string) (result Config, err error) {
2021-01-12 03:53:51 +00:00
configPath := getConfigPath(path)
f, err := os.Open(configPath)
if err != nil {
// https://github.com/golang/go/blob/3e1e13ce6d1271f49f3d8ee359689145a6995bad/src/os/error.go#L90-L91
if errors.Is(err, os.ErrNotExist) {
2021-01-18 04:28:06 +00:00
err = fmt.Errorf("file not exist %s: %w", configPath, err)
return
2021-01-12 03:53:51 +00:00
}
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
2021-01-18 04:28:06 +00:00
err = fmt.Errorf("failed to read %s: %w", configPath, err)
return
2021-01-12 03:53:51 +00:00
}
if err := json.Unmarshal(bytes, &result); err != nil {
2021-01-18 04:28:06 +00:00
err = fmt.Errorf("failed to unmarshal: %w", err)
return
2021-01-12 03:53:51 +00:00
}
2021-01-18 04:28:06 +00:00
result.Path = configPath
return
2021-01-12 03:53:51 +00:00
}
func getConfigPath(path string) string {
return filepath.Join(path, "configs/config.json")
}