diff --git a/pkg/parser/dsl.go b/pkg/parser/dsl.go index 5769737..38ed01b 100644 --- a/pkg/parser/dsl.go +++ b/pkg/parser/dsl.go @@ -14,7 +14,7 @@ import ( func parseCheatDSL(cheat *Cheat, content string, path string, startLine int) []ParseError { lines := joinContinuationLines(strings.Split(content, "\n")) - var currentCondition string + var conditionStack []string var errs []ParseError ifDepth := 0 ifLines := []int{} @@ -26,6 +26,15 @@ 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": @@ -37,13 +46,14 @@ func parseCheatDSL(cheat *Cheat, content string, path string, startLine int) []P } else { ifDepth-- ifLines = ifLines[:len(ifLines)-1] + conditionStack = conditionStack[:len(conditionStack)-1] } - currentCondition = "" case "if": if rest == "" { errs = append(errs, ParseError{File: path, Line: lineNo, Message: "`if` requires a condition"}) + conditionStack = append(conditionStack, "") } else { - currentCondition = rest + conditionStack = append(conditionStack, rest) } ifDepth++ ifLines = append(ifLines, lineNo) diff --git a/pkg/parser/dsl_test.go b/pkg/parser/dsl_test.go new file mode 100644 index 0000000..264fb0d --- /dev/null +++ b/pkg/parser/dsl_test.go @@ -0,0 +1,34 @@ +package parser + +import ( + "testing" +) + +func TestDSLIfNesting(t *testing.T) { + cheat := &Cheat{} + dslBlock := ` +if A + if B + var X = echo x + fi + var Y = echo y +fi +` + errs := parseCheatDSL(cheat, dslBlock, "test.md", 1) + if len(errs) > 0 { + t.Fatalf("unexpected errors: %v", errs) + } + + if len(cheat.Vars) != 2 { + t.Fatalf("expected 2 vars, got %d", len(cheat.Vars)) + } + + for _, v := range cheat.Vars { + if v.Name == "X" && v.Condition != "A && B" { + t.Errorf("expected var X condition to be A && B, got %s", v.Condition) + } + if v.Name == "Y" && v.Condition != "A" { + t.Errorf("expected var Y condition to be A, got %s", v.Condition) + } + } +}