summaryrefslogtreecommitdiff
path: root/internal/config/config.go
blob: 812cca2a67bb98e77a19516bab1de93736b8640a (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package config

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

const (
	defaultWeekWorkHours = 40.0
	defaultWorktimeDBDir = "~/git/worktime"
	configDirName        = "timr"
	configFileName       = "config.json"
)

var (
	defaultPlusFor     = []string{"off", "bank", "bufferuse", "sick"}
	defaultWeekendDays = []string{"Sat", "Sun"}
	defaultMinusFor    = []string{"lunch"}
	defaultBufferFor   = []string{
		"tools",
		"pet",
		"selfdevelopment",
		"workrebalance",
		"compensate",
		"travel",
		"rebalance",
	}
)

// Config defines runtime settings for timer and worktime integrations.
type Config struct {
	WeekWorkHours     float64  `json:"weekworkhours"`
	PlusFor           []string `json:"plusfor"`
	WeekendDays       []string `json:"weekendays"`
	MinusFor          []string `json:"minusfor"`
	BufferFor         []string `json:"bufferfor"`
	WorktimeDBDir     string   `json:"worktime_db_dir"`
	Hostname          string   `json:"hostname"`
	AutoWorktimeLogin bool     `json:"auto_worktime_login"`
}

// Default returns the default configuration values.
func Default() Config {
	return Config{
		WeekWorkHours:     defaultWeekWorkHours,
		PlusFor:           cloneStrings(defaultPlusFor),
		WeekendDays:       cloneStrings(defaultWeekendDays),
		MinusFor:          cloneStrings(defaultMinusFor),
		BufferFor:         cloneStrings(defaultBufferFor),
		WorktimeDBDir:     defaultWorktimeDBDir,
		Hostname:          "",
		AutoWorktimeLogin: false,
	}
}

// DefaultPath returns the default config file location.
func DefaultPath() (string, error) {
	configDir, err := os.UserConfigDir()
	if err != nil {
		return "", fmt.Errorf("resolve user config directory: %w", err)
	}

	return filepath.Join(configDir, configDirName, configFileName), nil
}

// Load reads config from path. If path is empty, the default path is used.
// Missing config files return defaults.
func Load(path string) (Config, error) {
	cfg := Default()

	configPath, err := resolveConfigPath(path)
	if err != nil {
		return cfg, err
	}

	data, err := os.ReadFile(configPath)
	if err != nil {
		if os.IsNotExist(err) {
			return normalizeConfig(cfg)
		}
		return cfg, fmt.Errorf("read config %q: %w", configPath, err)
	}

	if err := json.Unmarshal(data, &cfg); err != nil {
		return cfg, fmt.Errorf("parse config %q: %w", configPath, err)
	}

	applyDefaults(&cfg)
	return normalizeConfig(cfg)
}

// Save writes config to path. If path is empty, the default path is used.
func Save(path string, cfg Config) error {
	configPath, err := resolveConfigPath(path)
	if err != nil {
		return err
	}

	applyDefaults(&cfg)
	cfg, err = normalizeConfig(cfg)
	if err != nil {
		return err
	}

	data, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return fmt.Errorf("encode config: %w", err)
	}
	data = append(data, '\n')

	if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
		return fmt.Errorf("create config directory for %q: %w", configPath, err)
	}

	if err := os.WriteFile(configPath, data, 0o644); err != nil {
		return fmt.Errorf("write config %q: %w", configPath, err)
	}

	return nil
}

// EffectiveHostname resolves hostname using config, then ~/.hostnameoverride, then os.Hostname().
func (c Config) EffectiveHostname() (string, error) {
	if host := strings.TrimSpace(c.Hostname); host != "" {
		return host, nil
	}

	overridePath, err := expandHome("~/.hostnameoverride")
	if err != nil {
		return "", err
	}

	data, err := os.ReadFile(overridePath)
	if err == nil {
		if host := strings.TrimSpace(string(data)); host != "" {
			return host, nil
		}
	} else if !os.IsNotExist(err) {
		return "", fmt.Errorf("read hostname override %q: %w", overridePath, err)
	}

	host, err := os.Hostname()
	if err != nil {
		return "", fmt.Errorf("resolve os hostname: %w", err)
	}

	return host, nil
}

func applyDefaults(cfg *Config) {
	if cfg.WeekWorkHours == 0 {
		cfg.WeekWorkHours = defaultWeekWorkHours
	}
	if cfg.PlusFor == nil {
		cfg.PlusFor = cloneStrings(defaultPlusFor)
	}
	if cfg.WeekendDays == nil {
		cfg.WeekendDays = cloneStrings(defaultWeekendDays)
	}
	if cfg.MinusFor == nil {
		cfg.MinusFor = cloneStrings(defaultMinusFor)
	}
	if cfg.BufferFor == nil {
		cfg.BufferFor = cloneStrings(defaultBufferFor)
	}
	if strings.TrimSpace(cfg.WorktimeDBDir) == "" {
		cfg.WorktimeDBDir = defaultWorktimeDBDir
	}
}

func normalizeConfig(cfg Config) (Config, error) {
	worktimeDir, err := expandHome(cfg.WorktimeDBDir)
	if err != nil {
		return cfg, fmt.Errorf("expand worktime_db_dir %q: %w", cfg.WorktimeDBDir, err)
	}
	cfg.WorktimeDBDir = worktimeDir
	return cfg, nil
}

func resolveConfigPath(path string) (string, error) {
	if strings.TrimSpace(path) == "" {
		return DefaultPath()
	}

	resolvedPath, err := expandHome(path)
	if err != nil {
		return "", fmt.Errorf("expand config path %q: %w", path, err)
	}
	return resolvedPath, nil
}

func expandHome(path string) (string, error) {
	if path == "" {
		return "", nil
	}

	if path != "~" && !strings.HasPrefix(path, "~/") {
		return path, nil
	}

	homeDir, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("resolve home directory: %w", err)
	}

	if path == "~" {
		return homeDir, nil
	}

	return filepath.Join(homeDir, path[2:]), nil
}

func cloneStrings(values []string) []string {
	copied := make([]string, len(values))
	copy(copied, values)
	return copied
}