From effb2755b7052c74cf8d62d8089c40f59b35f3fb Mon Sep 17 00:00:00 2001 From: Falk Harrison Date: Tue, 29 Sep 2026 10:46:31 +0200 Subject: [PATCH 1/2] fix(parser): share escaped variable discovery rules --- pkg/executor/resolve.go | 59 +----------------------------- pkg/executor/var_discovery_test.go | 28 ++++++++++++++ pkg/parser/compose.go | 56 ++++++++++++++++++++-------- pkg/parser/compose_test.go | 4 +- 4 files changed, 72 insertions(+), 75 deletions(-) create mode 100644 pkg/executor/var_discovery_test.go diff --git a/pkg/executor/resolve.go b/pkg/executor/resolve.go index 4437e04..13e0d4e 100644 --- a/pkg/executor/resolve.go +++ b/pkg/executor/resolve.go @@ -189,62 +189,7 @@ func ReplaceVar(cmd, varName, replacement string, syntax string) string { return re.ReplaceAllLiteralString(cmd, replacement) } -// FindAllVars finds ALL variable references in a command, ignoring quoting. +// FindAllVars finds variable references using the parser's syntax and escaping rules. func FindAllVars(cmd string, syntax string) []string { - allowDollar := syntax == "dollar" || syntax == "both" - allowAngle := syntax == "angle" || syntax == "both" - - var vars []string - seen := make(map[string]bool) - add := func(name string) { - if seen[name] { - return - } - seen[name] = true - vars = append(vars, name) - } - - for i := 0; i < len(cmd); i++ { - switch cmd[i] { - case '$': - i = scanDollarVar(cmd, i, allowDollar, add) - case '<': - i = scanAngleVar(cmd, i, allowAngle, add) - } - } - - return vars -} - -func scanDollarVar(cmd string, i int, allowDollar bool, add func(string)) int { - if !allowDollar || i+1 >= len(cmd) || (i > 0 && cmd[i-1] == '\\') { - return i - } - j := i + 1 - for j < len(cmd) && parser.IsVarChar(cmd[j], j == i+1) { - j++ - } - if j > i+1 { - add(cmd[i+1 : j]) - } - return j - 1 -} - -func scanAngleVar(cmd string, i int, allowAngle bool, add func(string)) int { - if !allowAngle { - return i - } - j := i + 1 - if j >= len(cmd) || !parser.IsVarChar(cmd[j], true) { - return i - } - j++ - for j < len(cmd) && parser.IsVarChar(cmd[j], false) { - j++ - } - if j >= len(cmd) || cmd[j] != '>' { - return i - } - add(cmd[i+1 : j]) - return j + return parser.ExtractVars(cmd, syntax == "" || syntax == "dollar" || syntax == "both", syntax == "angle" || syntax == "both") } diff --git a/pkg/executor/var_discovery_test.go b/pkg/executor/var_discovery_test.go new file mode 100644 index 0000000..aa82f5f --- /dev/null +++ b/pkg/executor/var_discovery_test.go @@ -0,0 +1,28 @@ +package executor + +import ( + "reflect" + "testing" +) + +func TestFindAllVarsEscapesAndDefaultSyntax(t *testing.T) { + for _, tc := range []struct { + name, command, syntax string + want []string + }{ + {"default", "echo $value", "", []string{"value"}}, + {"odd backslash", `echo \$literal $value`, "dollar", []string{"value"}}, + {"even backslashes", `echo \\$value`, "dollar", []string{"value"}}, + {"three backslashes", `echo \\\$literal $value`, "dollar", []string{"value"}}, + {"shell braces", "echo ${HOME} $value", "dollar", []string{"value"}}, + {"ordered unique names", "echo $first $first", "both", []string{"first", "second"}}, + {"angle only", "echo $first ", "angle", []string{"second"}}, + {"malformed angle", "echo `) +// WalkVars visits complete variable references in source order. Offsets are byte +// offsets into command. Dollar references escaped by an odd number of preceding +// backslashes and shell ${...} forms are left to the shell. +func WalkVars(command string, allowDollar, allowAngle bool, visit func(start, end int, name string)) { + backslashes := 0 + for i := 0; i < len(command); i++ { + if command[i] == '\\' { + backslashes++ + continue + } + escaped := backslashes%2 != 0 + backslashes = 0 + dollar := command[i] == '$' && allowDollar && !escaped + angle := command[i] == '<' && allowAngle + if !dollar && !angle { + continue + } + start := i + j := i + 1 + if j >= len(command) || !IsVarChar(command[j], true) { + continue + } + j++ + for j < len(command) && IsVarChar(command[j], false) { + j++ + } + name := command[i+1 : j] + if angle { + if j >= len(command) || command[j] != '>' { + continue + } + j++ + } + visit(start, j, name) + i = j - 1 + } +} // ExtractVars finds all variables in a command string. It respects the provided // flags for dollar ($var) and angle bracket () syntaxes. It returns a @@ -14,20 +46,12 @@ func ExtractVars(command string, allowDollar, allowAngle bool) []string { varMap := make(map[string]bool) var vars []string - matches := combinedRegex.FindAllStringSubmatch(command, -1) - for _, match := range matches { - var name string - if match[1] != "" && allowDollar { - name = match[1] - } else if match[2] != "" && allowAngle { - name = match[2] - } - - if name != "" && !varMap[name] { + WalkVars(command, allowDollar, allowAngle, func(_, _ int, name string) { + if !varMap[name] { varMap[name] = true vars = append(vars, name) } - } + }) return vars } diff --git a/pkg/parser/compose_test.go b/pkg/parser/compose_test.go index acd2be6..7aa425b 100644 --- a/pkg/parser/compose_test.go +++ b/pkg/parser/compose_test.go @@ -37,9 +37,9 @@ func TestExtractVars(t *testing.T) { want: nil, }, { - name: "escaped variables", // the parser currently extracts it anyway, which is fine for compose + name: "escaped variables", command: "echo \\$var", - want: []string{"var"}, + want: nil, }, } From 4e6f59b723a786cd3eb1ebde3c97675e95eb21f3 Mon Sep 17 00:00:00 2001 From: Gubarz <1037896+Gubarz@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:49:26 -0700 Subject: [PATCH 2/2] fix(vars): preserve escaped dollars during discovery and rendering --- cmd/cheatmd/compose.go | 34 +++++++++++++++++----------- cmd/cheatmd/compose_escaping_test.go | 32 ++++++++++++++++++++++++++ pkg/executor/executor.go | 4 ++-- pkg/executor/executor_test.go | 6 +++++ pkg/executor/resolve.go | 31 ++++++++++++++----------- pkg/executor/var_discovery_test.go | 11 ++++++++- pkg/parser/compose.go | 15 ++++-------- 7 files changed, 93 insertions(+), 40 deletions(-) create mode 100644 cmd/cheatmd/compose_escaping_test.go diff --git a/cmd/cheatmd/compose.go b/cmd/cheatmd/compose.go index 9d5e9c4..f21742c 100644 --- a/cmd/cheatmd/compose.go +++ b/cmd/cheatmd/compose.go @@ -97,25 +97,13 @@ func buildComposeMarkdown(name, desc, command string) string { // Always extract both syntaxes to catch whatever the user pasted vars := parser.ExtractVars(command, true, true) - // Rewrite the command to respect the user's configured var_syntax - switch config.Get().VarSyntax { - case "dollar", "": - for _, v := range vars { - command = strings.ReplaceAll(command, "<"+v+">", "$"+v) - } - case "angle": - for _, v := range vars { - command = strings.ReplaceAll(command, "$"+v, "<"+v+">") - } - } - var sb strings.Builder sb.WriteString("\n# ") sb.WriteString(name) sb.WriteString("\n\n") sb.WriteString(fmt.Sprintf("```sh title:\"%s\"\n", desc)) - sb.WriteString(command) + writeComposeCommand(&sb, command, config.Get().VarSyntax) sb.WriteString("\n```\n") sb.WriteString("\n") { + t.Errorf("wrong variable declarations:\n%s", markdown) + } + }) + } +} diff --git a/pkg/executor/executor.go b/pkg/executor/executor.go index c8cad22..930ddb4 100644 --- a/pkg/executor/executor.go +++ b/pkg/executor/executor.go @@ -184,10 +184,10 @@ func SubstituteVars(s string, scope map[string]string, syntax string) string { case "angle": s = strings.ReplaceAll(s, "<"+name+">", val) case "both": - s = strings.ReplaceAll(s, "$"+name, val) + s = replaceTemplateVar(s, name, val, true, false) s = strings.ReplaceAll(s, "<"+name+">", val) default: // "dollar" - s = strings.ReplaceAll(s, "$"+name, val) + s = replaceTemplateVar(s, name, val, true, false) } } return s diff --git a/pkg/executor/executor_test.go b/pkg/executor/executor_test.go index a41659c..d3cf1f7 100644 --- a/pkg/executor/executor_test.go +++ b/pkg/executor/executor_test.go @@ -74,6 +74,12 @@ func TestSubstituteVars_Dollar(t *testing.T) { scope: map[string]string{"host": "10.0.0.1"}, expected: "echo ", }, + { + name: "escaped and unknown references are preserved", + input: `echo \$user \\$user $user $username`, + scope: map[string]string{"user": "bob"}, + expected: `echo \$user \\$user bob $username`, + }, { name: "braced shell vars ignored in dollar mode", input: "echo ${host} $host", diff --git a/pkg/executor/resolve.go b/pkg/executor/resolve.go index 13e0d4e..438db50 100644 --- a/pkg/executor/resolve.go +++ b/pkg/executor/resolve.go @@ -173,20 +173,25 @@ func evaluatePredicate(predicate string, scope map[string]string) bool { // ReplaceVar replaces variable references in cmd with replacement. func ReplaceVar(cmd, varName, replacement string, syntax string) string { - q := regexp.QuoteMeta(varName) - var parts []string - if syntax == "dollar" || syntax == "both" { - parts = append(parts, `\$`+q+`\b`) - } - if syntax == "angle" || syntax == "both" { - parts = append(parts, `<`+q+`>`) - } - if len(parts) == 0 { - return cmd + return replaceTemplateVar(cmd, varName, replacement, + syntax == "" || syntax == "dollar" || syntax == "both", syntax == "angle" || syntax == "both") +} + +func replaceTemplateVar(command, varName, replacement string, allowDollar, allowAngle bool) string { + var out strings.Builder + last := 0 + parser.WalkVars(command, allowDollar, allowAngle, func(start, end int, name string) { + if name == varName { + out.WriteString(command[last:start]) + out.WriteString(replacement) + last = end + } + }) + if last == 0 { + return command } - pattern := strings.Join(parts, "|") - re := regexp.MustCompile(pattern) - return re.ReplaceAllLiteralString(cmd, replacement) + out.WriteString(command[last:]) + return out.String() } // FindAllVars finds variable references using the parser's syntax and escaping rules. diff --git a/pkg/executor/var_discovery_test.go b/pkg/executor/var_discovery_test.go index aa82f5f..0a6216d 100644 --- a/pkg/executor/var_discovery_test.go +++ b/pkg/executor/var_discovery_test.go @@ -12,10 +12,11 @@ func TestFindAllVarsEscapesAndDefaultSyntax(t *testing.T) { }{ {"default", "echo $value", "", []string{"value"}}, {"odd backslash", `echo \$literal $value`, "dollar", []string{"value"}}, - {"even backslashes", `echo \\$value`, "dollar", []string{"value"}}, + {"even backslashes", `echo \\$value`, "dollar", nil}, {"three backslashes", `echo \\\$literal $value`, "dollar", []string{"value"}}, {"shell braces", "echo ${HOME} $value", "dollar", []string{"value"}}, {"ordered unique names", "echo $first $first", "both", []string{"first", "second"}}, + {"escaped and active references", `echo \$value \\$literal $value`, "dollar", []string{"value"}}, {"angle only", "echo $first ", "angle", []string{"second"}}, {"malformed angle", "echo $names` + want := `echo \$name \\$name value value $names` + if got := ReplaceVar(input, "name", "value", "both"); got != want { + t.Fatalf("ReplaceVar = %q, want %q", got, want) + } +} diff --git a/pkg/parser/compose.go b/pkg/parser/compose.go index 06cd703..4e153a7 100644 --- a/pkg/parser/compose.go +++ b/pkg/parser/compose.go @@ -1,18 +1,11 @@ package parser -// WalkVars visits complete variable references in source order. Offsets are byte -// offsets into command. Dollar references escaped by an odd number of preceding -// backslashes and shell ${...} forms are left to the shell. +// WalkVars visits complete variable references in source order using byte offsets. +// A backslash immediately before a dollar shields it from CheatMD. Command +// rendering removes that one backslash, leaving any earlier ones for the shell. func WalkVars(command string, allowDollar, allowAngle bool, visit func(start, end int, name string)) { - backslashes := 0 for i := 0; i < len(command); i++ { - if command[i] == '\\' { - backslashes++ - continue - } - escaped := backslashes%2 != 0 - backslashes = 0 - dollar := command[i] == '$' && allowDollar && !escaped + dollar := command[i] == '$' && allowDollar && (i == 0 || command[i-1] != '\\') angle := command[i] == '<' && allowAngle if !dollar && !angle { continue