Skip to content

Commit 417caab

Browse files
authored
Support absolute paths when calling malcontent externally (#944)
Signed-off-by: egibs <20933572+egibs@users.noreply.github.com>
1 parent 200a7be commit 417caab

1 file changed

Lines changed: 22 additions & 16 deletions

File tree

pkg/compile/compile.go

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"os"
1212
"path/filepath"
1313
"regexp"
14+
"runtime"
1415
"strings"
1516

1617
"github.com/chainguard-dev/clog"
@@ -166,22 +167,34 @@ func removeRules(data []byte, rulesToRemove []string) []byte {
166167
return newlinePattern.ReplaceAll(modified, []byte("\n\n"))
167168
}
168169

169-
// findRoot locates the repository root on the fly.
170-
func findRoot(start string) string {
171-
current := start
170+
// findRoot locates the packages's root directory on the fly.
171+
func findRoot() (string, error) {
172+
_, here, _, ok := runtime.Caller(0)
173+
if !ok {
174+
return "", fmt.Errorf("failed to get current file path")
175+
}
176+
177+
dir := filepath.Dir(here)
178+
current := dir
172179
for {
173-
next := filepath.Join(current, "rules")
174-
if _, err := os.Stat(next); err == nil {
175-
return current
180+
rulesPath := filepath.Join(current, "rules")
181+
if fi, err := os.Stat(rulesPath); err == nil && fi.IsDir() {
182+
return current, nil
176183
}
177184

178185
parent := filepath.Dir(current)
179186
if parent == current {
180-
return ""
187+
break
181188
}
182-
183189
current = parent
184190
}
191+
192+
rulesPath := filepath.Join(filepath.Dir(dir), "rules")
193+
if fi, err := os.Stat(rulesPath); err == nil && fi.IsDir() {
194+
return filepath.Dir(dir), nil
195+
}
196+
197+
return "", fmt.Errorf("could not find rules directory from %s", dir)
185198
}
186199

187200
// replaceGlobal updates the include string to reference the absolute path of rules/global/global.yara
@@ -205,17 +218,10 @@ func Recursive(ctx context.Context, fss []fs.FS) (*yarax.Rules, error) {
205218
return nil, fmt.Errorf("yarax compiler: %w", err)
206219
}
207220

208-
// use the current working directory to determine the root path
209-
// this only needs to be done once
210-
cwd, err := os.Getwd()
211-
if err != nil {
212-
return nil, err
213-
}
214-
abs, err := filepath.Abs(cwd)
221+
rootPath, err := findRoot()
215222
if err != nil {
216223
return nil, err
217224
}
218-
rootPath := findRoot(abs)
219225

220226
rulesToRemove := getRulesToRemove()
221227

0 commit comments

Comments
 (0)