-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
cmdutil: move MultiValue to internal/cmdutil for reuse
- Loading branch information
1 parent
1b38f3f
commit 5ca8b62
Showing
2 changed files
with
51 additions
and
41 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package cmdutil | ||
|
||
import ( | ||
"strings" | ||
|
||
"github.com/gobwas/glob" | ||
) | ||
|
||
// MultiValue can be used as a flag.Var type to support comma-separated lists | ||
// of values on the command line. The [MultiValue.ResolveArgValues] method can | ||
// be used to validate the values and resolve globs. | ||
type MultiValue []string | ||
|
||
func (mv *MultiValue) String() string { | ||
return strings.Join(*mv, ", ") | ||
} | ||
|
||
func (mv *MultiValue) Set(v string) error { | ||
split := strings.Split(v, ",") | ||
*mv = split | ||
return nil | ||
} | ||
|
||
// ResolveArgValues returns a list of valid values from the MultiValue. Invalid | ||
// values are returned separately. Globs are expanded. If the args are empty, | ||
// the valueList is returned in full. | ||
func (args MultiValue) ResolveArgValues(valueList []string) ([]string, []string) { | ||
if len(args) == 0 { | ||
return valueList, nil | ||
} | ||
selection := make([]string, 0, len(args)) | ||
invalid := make([]string, 0, len(args)) | ||
for _, arg := range args { | ||
g := glob.MustCompile(arg) | ||
match := false | ||
for _, v := range valueList { | ||
if g.Match(v) { | ||
selection = append(selection, v) | ||
match = true | ||
} | ||
} | ||
if !match { | ||
invalid = append(invalid, arg) | ||
} | ||
} | ||
return selection, invalid | ||
} |