Skip to content

Commit 3e29089

Browse files
committed
eval: return error hash instead of panicking on compile errors
Changes to make eval output byte-for-byte compatible with rugo run.
1 parent 6033dd8 commit 3e29089

2 files changed

Lines changed: 27 additions & 15 deletions

File tree

modules/eval/runtime.go

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func (*Eval) Run(source string) interface{} {
4040
c := &compiler.Compiler{BaseDir: tmpDir}
4141
result, err := c.RunCapture(srcFile)
4242
if err != nil {
43-
panic(fmt.Sprintf("eval.run: %v", err))
43+
return errorToHash(err)
4444
}
4545

4646
return capturedToHash(result)
@@ -57,15 +57,10 @@ func (*Eval) File(path string, extra ...interface{}) interface{} {
5757
args[i] = fmt.Sprintf("%v", v)
5858
}
5959

60-
absPath, err := filepath.Abs(path)
60+
c := &compiler.Compiler{}
61+
result, err := c.RunCapture(path, args...)
6162
if err != nil {
62-
panic(fmt.Sprintf("eval.file: resolving path: %v", err))
63-
}
64-
65-
c := &compiler.Compiler{BaseDir: filepath.Dir(absPath)}
66-
result, err := c.RunCapture(absPath, args...)
67-
if err != nil {
68-
panic(fmt.Sprintf("eval.file: %v", err))
63+
return errorToHash(err)
6964
}
7065

7166
return capturedToHash(result)
@@ -87,3 +82,18 @@ func capturedToHash(result *compiler.CapturedOutput) map[interface{}]interface{}
8782
"lines": lines,
8883
}
8984
}
85+
86+
// errorToHash converts a compile/build error to the standard result hash,
87+
// matching what "rugo run" outputs on failure (exit 1 + "error: " prefix).
88+
func errorToHash(err error) map[interface{}]interface{} {
89+
msg := strings.TrimRight("error: "+err.Error(), "\n")
90+
var lines []interface{}
91+
for _, line := range strings.Split(msg, "\n") {
92+
lines = append(lines, interface{}(line))
93+
}
94+
return map[interface{}]interface{}{
95+
"status": 1,
96+
"output": msg,
97+
"lines": lines,
98+
}
99+
}

rats/stdlib/94_eval_module_test.rugo

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,16 @@ RUGO
5757
test.assert_eq(result["output"], "hello world")
5858
end
5959

60-
rats "try/or catches eval compile errors"
61-
result = try eval.run("def") or nil
62-
test.assert_nil(result)
60+
rats "eval.run returns hash on compile errors"
61+
result = eval.run("def")
62+
test.assert_eq(result["status"], 1)
63+
test.assert_contains(result["output"], "error:")
6364
end
6465

65-
rats "try/or catches eval.file errors"
66-
result = try eval.file("nonexistent.rugo") or nil
67-
test.assert_nil(result)
66+
rats "eval.file returns hash on missing file"
67+
result = eval.file("nonexistent.rugo")
68+
test.assert_eq(result["status"], 1)
69+
test.assert_contains(result["output"], "error:")
6870
end
6971

7072
rats "try/or passes through successful eval"

0 commit comments

Comments
 (0)