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
34 changes: 21 additions & 13 deletions cmd/cheatmd/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -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("<!-- cheat\n")
Expand All @@ -127,6 +115,26 @@ func buildComposeMarkdown(name, desc, command string) string {
return sb.String()
}

func writeComposeCommand(out *strings.Builder, command, syntax string) {
toAngle := syntax == "angle"
toDollar := syntax == "dollar" || syntax == ""
if !toAngle && !toDollar {
out.WriteString(command)
return
}
last := 0
parser.WalkVars(command, toAngle, toDollar, func(start, end int, name string) {
out.WriteString(command[last:start])
if toAngle {
out.WriteString("<" + name + ">")
} else {
out.WriteString("$" + name)
}
last = end
})
out.WriteString(command[last:])
}

func determineComposeTargetFile(file string) (string, error) {
if file != "" {
return config.ExpandHomePath(file)
Expand Down
32 changes: 32 additions & 0 deletions cmd/cheatmd/compose_escaping_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import (
"strings"
"testing"

"github.com/cheatmd-dev/cheatmd/pkg/config"
)

func TestComposeOnlyRewritesVariableReferences(t *testing.T) {
previous := config.Get().VarSyntax
t.Cleanup(func() { config.Get().VarSyntax = previous })

for _, tc := range []struct {
syntax, command, want string
}{
{"angle", `echo \$host \\$shell_only $host $hostname`, `echo \$host \\$shell_only <host> <hostname>`},
{"dollar", `echo \$host <host> <hostname>`, `echo \$host $host $hostname`},
{"both", `echo \$host $host <hostname>`, `echo \$host $host <hostname>`},
} {
t.Run(tc.syntax, func(t *testing.T) {
config.Get().VarSyntax = tc.syntax
markdown := buildComposeMarkdown("Greeting", "", tc.command)
if !strings.Contains(markdown, "\n"+tc.want+"\n") {
t.Errorf("snippet did not preserve the command %q:\n%s", tc.want, markdown)
}
if !strings.HasSuffix(markdown, "<!-- cheat\nvar host\nvar hostname\n-->\n") {
t.Errorf("wrong variable declarations:\n%s", markdown)
}
})
}
}
4 changes: 2 additions & 2 deletions pkg/executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions pkg/executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ func TestSubstituteVars_Dollar(t *testing.T) {
scope: map[string]string{"host": "10.0.0.1"},
expected: "echo <host>",
},
{
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",
Expand Down
86 changes: 18 additions & 68 deletions pkg/executor/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
37 changes: 37 additions & 0 deletions pkg/executor/var_discovery_test.go
Original file line number Diff line number Diff line change
@@ -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 <second> $first", "both", []string{"first", "second"}},
{"escaped and active references", `echo \$value \\$literal $value`, "dollar", []string{"value"}},
{"angle only", "echo $first <second>", "angle", []string{"second"}},
{"malformed angle", "echo <broken $value", "both", []string{"value"}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := FindAllVars(tc.command, tc.syntax); !reflect.DeepEqual(got, tc.want) {
t.Fatalf("FindAllVars() = %v, want %v", got, tc.want)
}
})
}
}

func TestReplaceVarPreservesEscapedReference(t *testing.T) {
input := `echo \$name \\$name $name <name> $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)
}
}
49 changes: 33 additions & 16 deletions pkg/parser/compose.go
Original file line number Diff line number Diff line change
@@ -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 (<var>) syntaxes. It returns a
Expand All @@ -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
}
4 changes: 2 additions & 2 deletions pkg/parser/compose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
}

Expand Down
Loading