From 017622fef402fb198ff9b62e050a9dd0bdae15d6 Mon Sep 17 00:00:00 2001 From: Gubarz <1037896+Gubarz@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:38:37 -0700 Subject: [PATCH] fix(executor): preserve literal ampersands in conditions --- .../headless/condition_ampersands_test.go | 66 +++++++++++++++++++ internal/resolver/resolver.go | 4 +- pkg/executor/condition_test.go | 6 ++ pkg/executor/resolve.go | 52 ++++++++++----- pkg/parser/dsl.go | 19 +++--- pkg/parser/types.go | 21 ++++++ 6 files changed, 140 insertions(+), 28 deletions(-) create mode 100644 internal/headless/condition_ampersands_test.go diff --git a/internal/headless/condition_ampersands_test.go b/internal/headless/condition_ampersands_test.go new file mode 100644 index 0000000..3e08213 --- /dev/null +++ b/internal/headless/condition_ampersands_test.go @@ -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" + + "\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) + } + }) + } +} diff --git a/internal/resolver/resolver.go b/internal/resolver/resolver.go index 6fd8ced..70ba8b1 100644 --- a/internal/resolver/resolver.go +++ b/internal/resolver/resolver.go @@ -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 } } diff --git a/pkg/executor/condition_test.go b/pkg/executor/condition_test.go index 63eac6b..757110e 100644 --- a/pkg/executor/condition_test.go +++ b/pkg/executor/condition_test.go @@ -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}, @@ -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}, diff --git a/pkg/executor/resolve.go b/pkg/executor/resolve.go index 7cbc402..4437e04 100644 --- a/pkg/executor/resolve.go +++ b/pkg/executor/resolve.go @@ -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. diff --git a/pkg/parser/dsl.go b/pkg/parser/dsl.go index 54ae07b..131969d 100644 --- a/pkg/parser/dsl.go +++ b/pkg/parser/dsl.go @@ -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": @@ -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)}) diff --git a/pkg/parser/types.go b/pkg/parser/types.go index 736d20a..40de0c7 100644 --- a/pkg/parser/types.go +++ b/pkg/parser/types.go @@ -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) {