Search code examples
powershellgogo-cobra

How to pass space to Cobra CLI string slice flag?


I am using a StringSliceP from the Pflag libraray accept a list of strings as CLI arguments.

I am calling the Go application from the Windows Command Prompt.

I would like some of the strings of the list to contain a (") double quote character, but I have not been able to do this.

Escaping the quotes does not work:

goapp.exe --string-slice-list "a\"b",c,d,e

Expected result: []string{"a\"b", "c", "d", "e"}

Actual result: Error: invalid argument "a\"\\b,c,d,e" for "--string-slice-list" flag: parse error on line 1, column 1: bare " in non-quoted-field

Doubling up the quotes does not work:

goapp.exe --string-slice-list "a""b",c,d,e

Expected result: []string{"a\"b", "c", "d", "e"}

Actual result: Error: invalid argument "a\"b,c,d,e" for "--string-slice-list" flag: parse error on line 1, column 1: bare " in non-quoted-field


Solution

  • Here is how to do it from a Windows command prompt:

    goapp.exe --string-slice-list \"a\"\"b\",c,d,e
    

    yields [a"b c d e] and

    goapp.exe --string-slice-list \"a\\\"\"b\",c,d,e
    

    does [a\"b c d e] (I’m not sure which one you actually want).

    The reason for this is, as has been pointed out, that the Pflag library makes use of the Go standard library encoding/csv supporting the format described in RFC 4180. If we refer to section 2 from paragraphs 5, 6 and 7:

    If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.

    Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.

    If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote.