~nvkv/amitm

ref: 431aac47482224d5e2e147c9a360ccf69e464273 amitm/internal/amitm/v1/executor.go -rw-r--r-- 1.3 KiB
431aac47Semyon Novikov Switch license to LGPLv3 with static linking exception 2 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
65
66
67
68
package amitm

import (
	"fmt"
	"os/exec"
	"path/filepath"
	"strings"

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

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

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

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

	var output []byte

	w, err := acme.Open(event.ID, nil)
	if err != nil {
		return output, err
	}

	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", event.Name, -1)
			}

			cmd := exec.Command(prog, args...)
			out, err := cmd.CombinedOutput()

			output = append(output, out...)
			if err != nil {
				return output, err
			}
		}
	}

	_ = w.Ctl("get")
	return output, nil
}