~nvkv/amitm

ref: bffe321917e01d7fb2f6516c6a4bafb506c339d5 amitm/internal/executor/v1/executor.go -rw-r--r-- 1.2 KiB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package executor

import (
	"9fans.net/go/acme"
	"git.sr.ht/~nvkv/amitm/internal/config/v1"

	"fmt"
	"os/exec"
	"path/filepath"
	"strings"
)

func Match(rules []*config.Rule, event acme.LogEvent) []*config.Rule {
	var toApply []*config.Rule

	for _, rule := range rules {
		var applicable = false
		for _, glob := range rule.Globs {
			ok, _ := filepath.Match(glob, filepath.Base(event.Name))
			if ok {
				applicable = true
				break
			}
		}
		if applicable {
			toApply = append(toApply, rule)
		}
	}
	return toApply
}

func Apply(rule *config.Rule, op, file string) ([]byte, error) {
	if op != rule.Action {
		return nil, fmt.Errorf(
			"action mismatch. Can't apply rule for %s to operation %s on file %s",
			rule.Action,
			op,
			file,
		)
	}

	var output []byte

	for _, step := range rule.Pipeline {
		if len(step.Exec) > 0 {
			prog := step.Exec[0]
			origArgs := step.Exec[1:]
			args := make([]string, len(origArgs))
			copy(args, origArgs)

			for i, arg := range args {
				args[i] = strings.Replace(arg, "$file", file, -1)
			}

			cmd := exec.Command(prog, args...)
			out, err := cmd.CombinedOutput()
			output = append(output, out...)
			if err != nil {
				return output, err
			}
		}
	}
	return output, nil
}