~nvkv/amitm

ref: bffe321917e01d7fb2f6516c6a4bafb506c339d5 amitm/internal/config/v1/config.go -rw-r--r-- 883 bytes
bffe3219Semyon Novikov Make amitm minimally useful 3 months ago
                                                                                
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
package config

import (
	"github.com/pelletier/go-toml"
	"io/ioutil"
)

type PipelineStep struct {
	Exec []string
}

type Rule struct {
	Name     string
	Action   string
	Globs    []string
	Pipeline []PipelineStep
}

type Config struct {
	actionmap map[string][]*Rule
	Rules     []Rule
}

func (cfg *Config) RulesForAction(action string) ([]*Rule, bool) {
	rules, ok := cfg.actionmap[action]
	return rules, ok
}

func ReadConfigFile(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return NewConfig(data)
}

func NewConfig(data []byte) (*Config, error) {
	cfg := &Config{}
	err := toml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	cfg.actionmap = make(map[string][]*Rule)
	for i, rule := range cfg.Rules {
		cfg.actionmap[rule.Action] = append(cfg.actionmap[rule.Action], &cfg.Rules[i])
	}
	return cfg, nil
}