Skip to content

Commit

Permalink
Merge pull request #49 from grafana/48-fix-subcommand-flags-handling
Browse files Browse the repository at this point in the history
fix subcommand flags handling
  • Loading branch information
szkiba authored Oct 15, 2024
2 parents 1c55cce + e7f5be7 commit cb2d359
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 7 deletions.
46 changes: 46 additions & 0 deletions cmd/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package cmd

import (
"context"

"github.com/spf13/cobra"
)

type argsKey struct{}

// SetArgs set arguments for cmd command and store the args in the context.
func SetArgs(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}

cmd.SetContext(context.WithValue(ctx, argsKey{}, args))

cmd.SetArgs(args)
}

func getArgs(cmd *cobra.Command) []string {
ctx := cmd.Context()
if ctx == nil {
return nil
}

value := ctx.Value(argsKey{})
if value == nil {
return nil
}

args, ok := value.([]string)
if !ok {
return nil
}

for idx := range args {
if args[idx] == cmd.Name() {
return args[idx+1:]
}
}

return nil
}
10 changes: 4 additions & 6 deletions cmd/k6exec/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package main
import (
"log/slog"
"os"
"strings"

"github.com/grafana/k6exec/cmd"
sloglogrus "github.com/samber/slog-logrus/v2"
Expand Down Expand Up @@ -36,17 +35,16 @@ func main() {
}

func newCmd(args []string, levelVar *slog.LevelVar) *cobra.Command {
cmd := cmd.New(levelVar)
cmd.Use = strings.ReplaceAll(cmd.Use, "exec", appname)
cmd.Version = version
root := cmd.New(levelVar)
root.Version = version

if len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
args[0] = "help"
}

cmd.SetArgs(args)
cmd.SetArgs(root, args)

return cmd
return root
}

func runCmd(cmd *cobra.Command) {
Expand Down
6 changes: 5 additions & 1 deletion cmd/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,11 @@ func (s *state) preRunE(sub *cobra.Command, args []string) error {
cmdargs = append(cmdargs, "--no-color")
}

cmdargs = append(cmdargs, args...)
if subargs := getArgs(sub); subargs != nil {
cmdargs = append(cmdargs, subargs...)
} else {
cmdargs = append(cmdargs, args...)
}

cmd, err := k6exec.Command(context.Background(), cmdargs, deps, &s.Options)
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions releases/v0.1.8.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
k6exec `v0.1.8` is here 🎉!

This is an internal bugfix release.

**Fix subcommand flags handling**

Passing subcommand specific flags was not possible, k6exec swallowed these flags.
This has been fixed.

0 comments on commit cb2d359

Please sign in to comment.