Skip to content

Commit 0e9c40e

Browse files
committed
pkg: mflag: flag: make mflag strip quotes in -flag="var" forms
This patch improves the mflag package to ensure that things arguments to mflag such as `-flag="var"` or `-flag='var'` have the quotes stripped from the value (to mirror the getopt functionality for similar flags). Docker-DCO-1.1-Signed-off-by: Aleksa Sarai <[email protected]> (github: cyphar)
1 parent 4edcbfd commit 0e9c40e

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

pkg/mflag/flag.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
Command line flag syntax:
5252
-flag
5353
-flag=x
54+
-flag="x"
55+
-flag='x'
5456
-flag x // non-boolean flags only
5557
One or two minus signs may be used; they are equivalent.
5658
The last form is not permitted for boolean flags because the
@@ -775,6 +777,37 @@ func (f *FlagSet) usage() {
775777
}
776778
}
777779

780+
func trimQuotes(str string) string {
781+
type quote struct {
782+
start, end byte
783+
}
784+
785+
// All valid quote types.
786+
quotes := []quote{
787+
// Double quotes
788+
{
789+
start: '"',
790+
end: '"',
791+
},
792+
793+
// Single quotes
794+
{
795+
start: '\'',
796+
end: '\'',
797+
},
798+
}
799+
800+
for _, quote := range quotes {
801+
// Only strip if outermost match.
802+
if str[0] == quote.start && str[len(str)-1] == quote.end {
803+
str = str[1 : len(str)-1]
804+
break
805+
}
806+
}
807+
808+
return str
809+
}
810+
778811
// parseOne parses one flag. It reports whether a flag was seen.
779812
func (f *FlagSet) parseOne() (bool, string, error) {
780813
if len(f.args) == 0 {
@@ -799,7 +832,7 @@ func (f *FlagSet) parseOne() (bool, string, error) {
799832
value := ""
800833
for i := 1; i < len(name); i++ { // equals cannot be first
801834
if name[i] == '=' {
802-
value = name[i+1:]
835+
value = trimQuotes(name[i+1:])
803836
has_value = true
804837
name = name[0:i]
805838
break

0 commit comments

Comments
 (0)