Skip to content

Commit ad4393e

Browse files
authored
fix: arg parsing (#108)
1 parent ba42449 commit ad4393e

2 files changed

Lines changed: 11 additions & 28 deletions

File tree

cmd/tsk/tsk.go

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ func main() {
7474
os.Exit(1)
7575
}
7676

77-
opts.tasks, opts.cliArgs = parseArgs(flag.Args())
77+
opts.tasks, opts.cliArgs = parseArgs(flag.Args(), flag.CommandLine.ArgsLenAtDash())
7878

7979
// cfg is the parsed task file
8080
cfg, err := task.NewTaskConfig(opts.taskFile, opts.cliArgs, opts.listTasks)
@@ -114,31 +114,11 @@ func main() {
114114
exec.RunTasks(exec.Config, &opts.tasks)
115115
}
116116

117-
// splits args like [task1, task2 --, arg1, arg2] into
118-
// - tasks = []string{"task1", "task2"}
119-
// - cliArgs = "arg1 arg2"
120-
func parseArgs(args []string) (tasks []string, cliArgs string) {
121-
cliArgsIndex := func() int {
122-
for index, arg := range args {
123-
if arg == "--" {
124-
return index
125-
}
126-
}
127-
return -1
128-
}()
129-
130-
hasCliArgs := func() bool {
131-
if cliArgsIndex >= 0 {
132-
return true
133-
}
134-
return false
135-
}()
136-
137-
if hasCliArgs {
138-
tasks = args[:cliArgsIndex]
139-
cliArgs = strings.Join(args[cliArgsIndex+1:], " ")
140-
return
117+
func parseArgs(args []string, dashIndex int) (tasks []string, cliArgs string) {
118+
if dashIndex >= 0 {
119+
tasks = args[:dashIndex]
120+
cliArgs = strings.Join(args[dashIndex:], " ")
121+
return tasks, cliArgs
141122
}
142-
143123
return args, ""
144124
}

cmd/tsk/tsk_test.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,27 @@ func TestParseArgs(t *testing.T) {
1010
input []string
1111
expectedTasks []string
1212
expectedCliArgs string
13+
dashIndex int
1314
}{
1415
{
1516
name: "tasks and args",
16-
input: []string{"task1", "task2", "--", "arg1", "arg2"},
17+
input: []string{"task1", "task2", "arg1", "arg2"},
1718
expectedTasks: []string{"task1", "task2"},
1819
expectedCliArgs: "arg1 arg2",
20+
dashIndex: 2,
1921
},
2022
{
2123
name: "just tasks",
2224
input: []string{"task1", "task2"},
2325
expectedTasks: []string{"task1", "task2"},
2426
expectedCliArgs: "",
27+
dashIndex: -1,
2528
},
2629
}
2730

2831
for _, test := range tests {
2932
t.Run(test.name, func(t *testing.T) {
30-
tasks, cliArgs := parseArgs(test.input)
33+
tasks, cliArgs := parseArgs(test.input, test.dashIndex)
3134
if !equalSlices(tasks, test.expectedTasks) {
3235
t.Errorf("Expected tasks: %v, got: %v", test.expectedTasks, tasks)
3336
}

0 commit comments

Comments
 (0)