Debian Codegraph @

caplets/caplet.go

raw symbols SCIP
1 package caplets
2
3 import (
4 "fmt"
5 "path/filepath"
6 "strings"
7
8 "github.com/evilsocket/islazy/fs"
9 )
10
11 type Script struct {
12 Path string `json:"path"`
13 Size int64 `json:"size"`
14 Code []string `json:"code"`
15 }
16
17 func newScript(path string, size int64) Script {
18 return Script{
19 Path: path,
20 Size: size,
21 Code: make([]string, 0),
22 }
23 }
24
25 type Caplet struct {
26 Script
27 Name string `json:"name"`
28 Scripts []Script `json:"scripts"`
29 }
30
31 func NewCaplet(name string, path string, size int64) Caplet {
32 return Caplet{
33 Script: newScript(path, size),
34 Name: name,
35 Scripts: make([]Script, 0),
36 }
37 }
38
39 func (cap *Caplet) Eval(argv []string, lineCb func(line string) error) error {
40 if argv == nil {
41 argv = []string{}
42 }
43 // the caplet might include other files (include directive, proxy modules, etc),
44 // temporarily change the working directory
45 return fs.Chdir(filepath.Dir(cap.Path), func() error {
46 for _, line := range cap.Code {
47 // skip empty lines and comments
48 if line == "" || line[0] == '#' {
49 continue
50 }
51 // replace $0 with argv[0], $1 with argv[1] and so on
52 for i, arg := range argv {
53 what := fmt.Sprintf("$%d", i)
54 line = strings.Replace(line, what, arg, -1)
55 }
56
57 if err := lineCb(line); err != nil {
58 return err
59 }
60 }
61 return nil
62 })
63 }