Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions internal/headless/condition_ampersands_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package headless

import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"

"github.com/cheatmd-dev/cheatmd/pkg/executor"
"github.com/cheatmd-dev/cheatmd/pkg/parser"
)

func TestHeadlessConditionWithLiteralAmpersands(t *testing.T) {
path := filepath.Join(t.TempDir(), "condition.md")
const cheat = "# Flavor\n\n" +
"```sh\nprintf '%s' $result\n```\n" +
"<!-- cheat\n" +
"var flavor\n" +
"var result := fallback\n" +
"if $flavor == Rock && Roll\n" +
" if enabled\n" +
" var result := matched\n" +
" fi\n" +
"fi\n" +
"-->\n"
if err := os.WriteFile(path, []byte(cheat), 0o600); err != nil {
t.Fatal(err)
}

for _, tc := range []struct{ flavor, want string }{
{"Rock && Roll", "matched"},
{"Rock", "fallback"},
} {
t.Run(tc.flavor, func(t *testing.T) {
index, err := parser.NewParser().ParseSingleFile(path)
if err != nil {
t.Fatal(err)
}
input, err := json.Marshal(map[string]any{
"jsonrpc": "2.0",
"result": map[string]any{"values": map[string]string{"flavor": tc.flavor}},
"id": 1,
})
if err != nil {
t.Fatal(err)
}
var output bytes.Buffer
session := &RunnerSession{
Cheat: index.Cheats[0], Index: index, Exec: executor.NewExecutor(index),
Decoder: json.NewDecoder(bytes.NewReader(input)), Out: &output,
}
session.initializeVariables()
if err := session.resolveInteractively(); err != nil {
t.Fatal(err)
}
if got := session.Exec.BuildFinalCommand(session.Cheat); got != "printf '%s' "+tc.want {
t.Fatalf("command = %q, want result %q", got, tc.want)
}
if !strings.Contains(output.String(), `"name":"flavor"`) {
t.Fatalf("missing flavor prompt: %s", &output)
}
})
}
}
4 changes: 3 additions & 1 deletion internal/resolver/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ func SelectVariant(variants []parser.VarDef, scope map[string]string) *parser.Va
}
continue
}
if executor.EvaluateCondition(v.Condition, scope) {
if v.MatchesConditions(func(condition string) bool {
return executor.EvaluateCondition(condition, scope)
}) {
return v
}
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/executor/condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ func TestEvaluateConditionConjunction(t *testing.T) {
{"second false", "$env == prod && $region == eu", map[string]string{"env": "prod", "region": "us"}, false},
{"both false", "$env == prod && $region == eu", map[string]string{"env": "dev", "region": "us"}, false},
{"mixed operators", "$env != dev && $region == eu", map[string]string{"env": "prod", "region": "eu"}, true},
{"literal within conjunction", "$value == Rock && Roll && $enabled", map[string]string{"value": "Rock && Roll", "enabled": "yes"}, true},
{"false predicate after literal", "$value == Rock && Roll && $enabled", map[string]string{"value": "Rock && Roll", "enabled": ""}, false},
{"three predicates", "$env == prod && $region != us && $ready", map[string]string{"env": "prod", "region": "eu", "ready": "yes"}, true},
{"empty middle predicate", "yes && && yes", nil, false},
{"empty last predicate", "yes &&", nil, false},
Expand All @@ -30,6 +32,10 @@ func TestEvaluateConditionLiteralOperands(t *testing.T) {
name, condition, value, expected string
want bool
}{
{"literal conjunction text", "$value == Rock && Roll", "Rock && Roll", "", true},
{"literal does not match just its prefix", "$value == Rock && Roll", "Rock", "", false},
{"inequality against literal conjunction text", "$value != Rock && Roll", "Rock && Roll", "", false},
{"ampersands without spaces", "$value == Rock&&Roll", "Rock&&Roll", "", true},
{"equality containing operators", "$value == $expected", "a == b != c && d", "a == b != c && d", true},
{"unequal values containing operators", "$value == $expected", "a == b", "a != b", false},
{"inequality containing equality", "$value != other", "a == b", "", true},
Expand Down
52 changes: 34 additions & 18 deletions pkg/executor/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,32 +127,48 @@ func visitDependencies(defs []parser.VarDef, addWithDeps func(string)) {
}
}

// A comparison can contain literal && in its operand. A following variable
// predicate gives && its conjunction meaning on the same DSL line.
var variableConjunction = regexp.MustCompile(`&&\s*\$[a-zA-Z_][a-zA-Z0-9_]*\s*(?:==|!=|&&|$)`)

// EvaluateCondition evaluates a condition expression against the scope.
func EvaluateCondition(condition string, scope map[string]string) bool {
for _, predicate := range strings.Split(condition, "&&") {
predicate = strings.TrimSpace(predicate)
op := ""
at := -1
for i := 0; i+1 < len(predicate); i++ {
if predicate[i:i+2] == "==" || predicate[i:i+2] == "!=" {
at, op = i, predicate[i:i+2]
break
for {
predicate, rest, joined := strings.Cut(condition, "&&")
if joined && (strings.Contains(predicate, "==") || strings.Contains(predicate, "!=")) {
if match := variableConjunction.FindStringIndex(condition[len(predicate):]); match != nil {
boundary := len(predicate) + match[0]
predicate, rest = condition[:boundary], condition[boundary+2:]
} else {
predicate, joined = condition, false
}
}
if at < 0 {
if SubstituteVars(predicate, scope, "dollar") == "" {
return false
}

if !evaluatePredicate(predicate, scope) {
return false
}
if !joined {
return true
}
condition = rest
}
}

func evaluatePredicate(predicate string, scope map[string]string) bool {
predicate = strings.TrimSpace(predicate)
for i := 0; i+1 < len(predicate); i++ {
op := predicate[i : i+2]
if op != "==" && op != "!=" {
continue
}
left := strings.TrimSpace(SubstituteVars(strings.TrimSpace(predicate[:at]), scope, "dollar"))
right := strings.TrimSpace(SubstituteVars(strings.TrimSpace(predicate[at+2:]), scope, "dollar"))
equal := left == right
if (op == "==" && !equal) || (op == "!=" && equal) {
return false
left := strings.TrimSpace(SubstituteVars(strings.TrimSpace(predicate[:i]), scope, "dollar"))
right := strings.TrimSpace(SubstituteVars(strings.TrimSpace(predicate[i+2:]), scope, "dollar"))
if op == "==" {
return left == right
}
return left != right
}
return true
return SubstituteVars(predicate, scope, "dollar") != ""
}

// ReplaceVar replaces variable references in cmd with replacement.
Expand Down
19 changes: 10 additions & 9 deletions pkg/parser/dsl.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,6 @@ func parseCheatDSL(cheat *Cheat, content string, path string, startLine int) []P
continue
}

// Calculate currentCondition from the stack
var conds []string
for _, c := range conditionStack {
if c != "" {
conds = append(conds, c)
}
}
currentCondition := strings.Join(conds, " && ")

keyword, rest := splitFirstWord(line)
switch keyword {
case "fi":
Expand Down Expand Up @@ -78,8 +69,18 @@ func parseCheatDSL(cheat *Cheat, content string, path string, startLine int) []P
errs = append(errs, ParseError{File: path, Line: lineNo, Message: err})
}
case "var":
// Keep the individual if expressions for evaluation.
var conds []string
for _, c := range conditionStack {
if c != "" {
conds = append(conds, c)
}
}
currentCondition := strings.Join(conds, " && ")
if err := parseVarLine(cheat, rest, currentCondition); err != "" {
errs = append(errs, ParseError{File: path, Line: lineNo, Message: err})
} else if len(conds) > 1 {
cheat.Vars[len(cheat.Vars)-1].nested = &nestedCondition{joined: currentCondition, parts: conds}
}
default:
errs = append(errs, ParseError{File: path, Line: lineNo, Message: fmt.Sprintf("unknown DSL keyword %q (expected one of: var, if, fi, export, import, chain)", keyword)})
Expand Down
21 changes: 21 additions & 0 deletions pkg/parser/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,27 @@ type VarDef struct {
Literal string // Literal value with var substitution (for := syntax)
Args string // Selector arguments after ---
Condition string // Conditional expression: "$var == value" or "$var != value"

nested *nestedCondition
}

type nestedCondition struct {
joined string
parts []string
}

// MatchesConditions evaluates each enclosing if expression. Condition retains
// the joined text for callers that display or construct variable definitions.
func (v VarDef) MatchesConditions(match func(string) bool) bool {
if v.nested == nil || v.Condition != v.nested.joined {
return v.Condition == "" || match(v.Condition)
}
for _, part := range v.nested.parts {
if !match(part) {
return false
}
}
return true
}

func parseVarDefBase(value string) (string, string) {
Expand Down
Loading