Skip to content

Commit 91be5a5

Browse files
authored
Merge pull request #1 from thecodesmith/copilot/implement-escaping-special-characters
fix(cobra): escape newlines, tabs, and carriage returns in kdlQuoteAlways
2 parents 7562574 + 3ccc32c commit 91be5a5

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

integrations/cobra/cobra_usage_test.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,75 @@ func TestStringDefaultZero(t *testing.T) {
313313
assertContains(t, got, `default="0"`)
314314
}
315315

316+
func TestSpecialCharacterEscaping(t *testing.T) {
317+
tests := []struct {
318+
name string
319+
input string
320+
expected string
321+
}{
322+
{
323+
name: "newline in help",
324+
input: "Line one\nLine two",
325+
expected: `"Line one\nLine two"`,
326+
},
327+
{
328+
name: "tab in help",
329+
input: "col1\tcol2",
330+
expected: `"col1\tcol2"`,
331+
},
332+
{
333+
name: "carriage return in help",
334+
input: "text\rmore",
335+
expected: `"text\rmore"`,
336+
},
337+
{
338+
name: "backslash in help",
339+
input: `path\to\file`,
340+
expected: `"path\\to\\file"`,
341+
},
342+
{
343+
name: "double quote in help",
344+
input: `say "hello"`,
345+
expected: `"say \"hello\""`,
346+
},
347+
{
348+
name: "mixed special characters",
349+
input: "line1\nline2\ttab\r\nwindows",
350+
expected: `"line1\nline2\ttab\r\nwindows"`,
351+
},
352+
}
353+
354+
for _, tt := range tests {
355+
t.Run(tt.name, func(t *testing.T) {
356+
got := kdlQuoteAlways(tt.input)
357+
if got != tt.expected {
358+
t.Errorf("kdlQuoteAlways(%q) = %q, want %q", tt.input, got, tt.expected)
359+
}
360+
})
361+
}
362+
}
363+
364+
func TestNewlineInCommandHelp(t *testing.T) {
365+
root := &cobra.Command{
366+
Use: "app",
367+
Short: "Short help",
368+
Long: "First line.\nSecond line.\n\nThird paragraph.",
369+
}
370+
371+
got := Generate(root)
372+
373+
assertContains(t, got, `long_about "First line.\nSecond line.\n\nThird paragraph."`)
374+
}
375+
376+
func TestSpecialCharsInFlagHelp(t *testing.T) {
377+
cmd := &cobra.Command{Use: "app"}
378+
cmd.Flags().String("format", "", "Output format:\n json\n yaml")
379+
380+
got := Generate(cmd)
381+
382+
assertContains(t, got, `help="Output format:\n json\n yaml"`)
383+
}
384+
316385
// --- helpers ---
317386

318387
func assertContains(t *testing.T, got, want string) {

integrations/cobra/kdl.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ func kdlQuote(s string) string {
303303
func kdlQuoteAlways(s string) string {
304304
s = strings.ReplaceAll(s, `\`, `\\`)
305305
s = strings.ReplaceAll(s, `"`, `\"`)
306+
s = strings.ReplaceAll(s, "\n", `\n`)
307+
s = strings.ReplaceAll(s, "\t", `\t`)
308+
s = strings.ReplaceAll(s, "\r", `\r`)
306309
return `"` + s + `"`
307310
}
308311

0 commit comments

Comments
 (0)