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 4437e04..438db50 100644 --- a/pkg/executor/resolve.go +++ b/pkg/executor/resolve.go @@ -173,78 +173,28 @@ 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 - } - pattern := strings.Join(parts, "|") - re := regexp.MustCompile(pattern) - return re.ReplaceAllLiteralString(cmd, replacement) + return replaceTemplateVar(cmd, varName, replacement, + syntax == "" || syntax == "dollar" || syntax == "both", syntax == "angle" || syntax == "both") } -// FindAllVars finds ALL variable references in a command, ignoring quoting. -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 +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 } - 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]) + }) + if last == 0 { + return command } - return j - 1 + out.WriteString(command[last:]) + return out.String() } -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 +// FindAllVars finds variable references using the parser's syntax and escaping rules. +func FindAllVars(cmd string, syntax string) []string { + 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..0a6216d --- /dev/null +++ b/pkg/executor/var_discovery_test.go @@ -0,0 +1,37 @@ +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", 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 b47d1e4..4e153a7 100644 --- a/pkg/parser/compose.go +++ b/pkg/parser/compose.go @@ -1,10 +1,35 @@ package parser -import ( - "regexp" -) - -var combinedRegex = regexp.MustCompile(`\$([a-zA-Z_][a-zA-Z0-9_]*)|<([a-zA-Z_][a-zA-Z0-9_]*)>`) +// 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)) { + for i := 0; i < len(command); i++ { + dollar := command[i] == '$' && allowDollar && (i == 0 || command[i-1] != '\\') + 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 +39,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, }, }