Skip to content

Commit

Permalink
Merge pull request #137 from rsteube/run-flags
Browse files Browse the repository at this point in the history
run: add flags to env
  • Loading branch information
rsteube authored Feb 18, 2023
2 parents 69024d9 + 042bd89 commit c1bb62f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
12 changes: 12 additions & 0 deletions example/runnable.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,15 @@ commands:
positional:
- - "$(git branch --format '%(refname:short)\t%(subject)\tblue')"
- "$(git tag --format '%(refname:short)\t\tyellow')"

- name: sub3
description: shell with flags
run: "$(git log --author \"${C_FLAG_AUTHOR}\" $1)"
flags:
-a, --author=: limit to author
completion:
flag:
author: ["$(git shortlog --summary --email HEAD | sed -e 's/^.*\t//' -e 's/ </\t</')"]
positional:
- - "$(git branch --format '%(refname:short)\t%(subject)\tblue')"
- "$(git tag --format '%(refname:short)\t\tyellow')"
3 changes: 2 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ func TestRunnable(t *testing.T) {
s.Run("runnable.yaml", "export", "runnable", "").
Expect(carapace.ActionValuesDescribed(
"sub1", "alias",
"sub2", "shell").
"sub2", "shell",
"sub3", "shell with flags").
Tag("commands"))
})
}
15 changes: 15 additions & 0 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import (
"runtime"
"strings"

"github.com/rsteube/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -57,10 +59,23 @@ func (r run) parse() func(cmd *cobra.Command, args []string) error {
return fmt.Errorf("malformed macro: %#v", r)
}

context := carapace.NewContext(args...)
cmd.Flags().Visit(func(f *pflag.Flag) {
context.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
})
var err error
for index, mArg := range mArgs {
mArgs[index], err = context.Envsubst(mArg)
if err != nil {
return err
}
}

execCmd := exec.Command(mCmd, append(mArgs, args...)...)
execCmd.Stdin = cmd.InOrStdin()
execCmd.Stdout = cmd.OutOrStdout()
execCmd.Stderr = cmd.ErrOrStderr()
execCmd.Env = context.Env
if err := execCmd.Run(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ProcessState.ExitCode())
Expand Down

0 comments on commit c1bb62f

Please sign in to comment.