-
Notifications
You must be signed in to change notification settings - Fork 208
/
load.go
346 lines (275 loc) · 7.97 KB
/
load.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package config
import (
"errors"
"fmt"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/spf13/afero"
"github.com/spf13/viper"
"github.com/evilmartians/lefthook/internal/git"
"github.com/evilmartians/lefthook/internal/log"
)
const (
DefaultConfigName = "lefthook.yml"
DefaultSourceDir = ".lefthook"
DefaultSourceDirLocal = ".lefthook-local"
)
var (
hookKeyRegexp = regexp.MustCompile(`^(?P<hookName>[^.]+)\.(scripts|commands)`)
localConfigNames = []string{"lefthook-local", ".lefthook-local"}
)
// NotFoundError wraps viper.ConfigFileNotFoundError for lefthook.
type NotFoundError struct {
message string
}
// Error returns message of viper.ConfigFileNotFoundError.
func (err NotFoundError) Error() string {
return err.message
}
// Loads configs from the given directory with extensions.
func Load(fs afero.Fs, repo *git.Repository) (*Config, error) {
global, err := readOne(fs, repo.RootPath, []string{"lefthook", ".lefthook"})
if err != nil {
return nil, err
}
extends, err := mergeAll(fs, repo)
if err != nil {
return nil, err
}
var config Config
config.SourceDir = DefaultSourceDir
config.SourceDirLocal = DefaultSourceDirLocal
err = unmarshalConfigs(global, extends, &config)
if err != nil {
return nil, err
}
log.SetColors(config.Colors)
return &config, nil
}
func read(fs afero.Fs, path string, name string) (*viper.Viper, error) {
v := newViper(fs, path)
v.SetConfigName(name)
if err := v.ReadInConfig(); err != nil {
return nil, err
}
return v, nil
}
func newViper(fs afero.Fs, path string) *viper.Viper {
v := viper.New()
v.SetFs(fs)
v.AddConfigPath(path)
// Allow overwriting settings with ENV variables
v.SetEnvPrefix("LEFTHOOK")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
return v
}
func readOne(fs afero.Fs, path string, names []string) (*viper.Viper, error) {
for _, name := range names {
v, err := read(fs, path, name)
if err != nil {
var notFoundErr viper.ConfigFileNotFoundError
if ok := errors.As(err, ¬FoundErr); ok {
continue
}
return nil, err
}
return v, nil
}
return nil, NotFoundError{fmt.Sprintf("No config files with names %q have been found in \"%s\"", names, path)}
}
// mergeAll merges configs using the following order.
// - lefthook/.lefthook
// - files from `extends`
// - files from `remotes`
// - lefthook-local/.lefthook-local.
func mergeAll(fs afero.Fs, repo *git.Repository) (*viper.Viper, error) {
extends, err := readOne(fs, repo.RootPath, []string{"lefthook", ".lefthook"})
if err != nil {
return nil, err
}
if err := extend(fs, extends, repo.RootPath); err != nil {
return nil, err
}
// Save global extends to compare them after merging local config
globalExtends := extends.GetStringSlice("extends")
if err := mergeRemotes(fs, repo, extends); err != nil {
return nil, err
}
//nolint:nestif
if err := mergeLocal(extends); err == nil {
// Local extends need to be re-applied only if they have different settings
localExtends := extends.GetStringSlice("extends")
if !slices.Equal(globalExtends, localExtends) {
if err = extend(fs, extends, repo.RootPath); err != nil {
return nil, err
}
}
} else {
var notFoundErr viper.ConfigFileNotFoundError
if ok := errors.As(err, ¬FoundErr); !ok {
return nil, err
}
}
return extends, nil
}
// mergeRemotes merges remote configs to the current one.
func mergeRemotes(fs afero.Fs, repo *git.Repository, v *viper.Viper) error {
var remote *Remote // Deprecated
var remotes []*Remote
err := v.UnmarshalKey("remotes", &remotes)
if err != nil {
return err
}
// Deprecated
err = v.UnmarshalKey("remote", &remote)
if err != nil {
return err
}
// Backward compatibility
if remote != nil {
remotes = append(remotes, remote)
}
for _, remote := range remotes {
if !remote.Configured() {
continue
}
// Use for backward compatibility with "remote(s).config"
if remote.Config != "" {
remote.Configs = append(remote.Configs, remote.Config)
}
if len(remote.Configs) == 0 {
remote.Configs = append(remote.Configs, DefaultConfigName)
}
for _, config := range remote.Configs {
remotePath := repo.RemoteFolder(remote.GitURL, remote.Ref)
configFile := config
configPath := filepath.Join(remotePath, configFile)
log.Debugf("Merging remote config: %s: %s", remote.GitURL, configPath)
_, err = fs.Stat(configPath)
if err != nil {
continue
}
if err = merge("remotes", configPath, v); err != nil {
return err
}
if err = extend(fs, v, filepath.Dir(configPath)); err != nil {
return err
}
}
// Reset extends to omit issues when extending with remote extends.
err = v.MergeConfigMap(map[string]interface{}{"extends": nil})
if err != nil {
return err
}
}
return nil
}
// extend merges all files listed in 'extends' option into the config.
func extend(fs afero.Fs, v *viper.Viper, root string) error {
return extendRecursive(fs, v, root, make(map[string]struct{}))
}
// extendRecursive merges extends.
// If extends contain other extends they get merged too.
func extendRecursive(fs afero.Fs, v *viper.Viper, root string, extends map[string]struct{}) error {
for _, path := range v.GetStringSlice("extends") {
if _, contains := extends[path]; contains {
return fmt.Errorf("possible recursion in extends: path %s is specified multiple times", path)
}
extends[path] = struct{}{}
if !filepath.IsAbs(path) {
path = filepath.Join(root, path)
}
extendV := newViper(fs, root)
extendV.SetConfigFile(path)
if err := extendV.ReadInConfig(); err != nil {
return err
}
if err := extendRecursive(fs, extendV, root, extends); err != nil {
return err
}
if err := v.MergeConfigMap(extendV.AllSettings()); err != nil {
return err
}
}
return nil
}
// merge merges the configuration using viper builtin MergeInConfig.
func merge(name, path string, v *viper.Viper) error {
v.SetConfigName(name)
v.SetConfigFile(path)
return v.MergeInConfig()
}
func mergeLocal(v *viper.Viper) error {
for _, name := range localConfigNames {
err := merge(name, "", v)
if err == nil {
break
}
var notFoundErr viper.ConfigFileNotFoundError
if ok := errors.As(err, ¬FoundErr); !ok {
return err
}
}
return nil
}
func unmarshalConfigs(base, extra *viper.Viper, c *Config) error {
c.Hooks = make(map[string]*Hook)
for _, hookName := range AvailableHooks {
if err := addHook(hookName, base, extra, c); err != nil {
return err
}
}
// For extra non-git hooks.
// This behavior may be deprecated in next versions.
// Notice that with append we're allowing extra hooks to be added in local config
for _, maybeHook := range append(base.AllKeys(), extra.AllKeys()...) {
if !hookKeyRegexp.MatchString(maybeHook) {
continue
}
matches := hookKeyRegexp.FindStringSubmatch(maybeHook)
hookName := matches[hookKeyRegexp.SubexpIndex("hookName")]
if _, ok := c.Hooks[hookName]; ok {
continue
}
if err := addHook(hookName, base, extra, c); err != nil {
return err
}
}
// Merge config and unmarshal it
if err := base.MergeConfigMap(extra.AllSettings()); err != nil {
return err
}
if err := base.Unmarshal(c); err != nil {
return err
}
// Deprecation handling
if c.Remote != nil {
log.Warn("DEPRECATED: \"remote\" option is deprecated and will be omitted in the next major release, use \"remotes\" option instead")
c.Remotes = append(c.Remotes, c.Remote)
}
c.Remote = nil
for _, remote := range c.Remotes {
if remote.Config != "" {
log.Warn("DEPRECATED: \"remotes\".\"config\" option is deprecated and will be omitted in the next major release, use \"configs\" option instead")
remote.Configs = append(remote.Configs, remote.Config)
}
remote.Config = ""
}
return nil
}
func addHook(hookName string, base, extra *viper.Viper, c *Config) error {
baseHook := base.Sub(hookName)
extraHook := extra.Sub(hookName)
resultHook, err := unmarshalHooks(baseHook, extraHook)
if err != nil {
return err
}
if resultHook == nil {
return nil
}
c.Hooks[hookName] = resultHook
return nil
}