-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
67 lines (54 loc) · 1.53 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/json"
"fmt"
"os"
"path"
"github.com/adrg/xdg"
"github.com/motemen/go-gitconfig"
)
const (
patEnvName = "GITHUB_PAT"
editorEnvName = "EDITOR"
)
type config struct {
Owner string `json:"owner" gitconfig:"user.name"`
Repo string `json:"repo"`
Branch string `json:"branch"`
CommitterName string `json:"committer_name" gitconfig:"user.name"`
CommitterEmail string `json:"committer_email" gitconfig:"user.email"`
PAT string `json:"pat"`
Editor string `json:"editor"`
}
func newConfig(gitCfg gitconfig.Config) (*config, error) {
cfg := &config{
Repo: "diary",
Branch: "main",
PAT: os.Getenv(patEnvName),
Editor: os.Getenv(editorEnvName),
}
if err := gitCfg.Load(cfg); err != nil {
return nil, fmt.Errorf("failed to load gitconfig: %w", err)
}
return cfg, nil
}
func (cfg *config) getConfigPath(configPath string) string {
if configPath != "" {
return configPath
}
return path.Join(xdg.ConfigHome, "hubdiary", "config.json")
}
func (cfg *config) loadFile(configPath string) error {
configPath = cfg.getConfigPath(configPath)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return fmt.Errorf("config file %s doesn't exist: %w", configPath, err)
}
data, err := os.ReadFile(configPath)
if err != nil {
return fmt.Errorf("failed to read config file `%s`: %w", configPath, err)
}
if err := json.Unmarshal(data, cfg); err != nil {
return fmt.Errorf("failed to unmarshal config file: `%s`: %w", configPath, err)
}
return nil
}