From 25de59df88a72f506da527f24363f92bf9decea1 Mon Sep 17 00:00:00 2001 From: Robert Lin Date: Fri, 27 May 2022 10:29:14 -0700 Subject: [PATCH] arg: introduce Arg alias, add note about quoting --- arg.go | 8 ++++++++ command.go | 8 ++++++-- exit_code_test.go | 6 +++--- 3 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 arg.go diff --git a/arg.go b/arg.go new file mode 100644 index 0000000..f462d27 --- /dev/null +++ b/arg.go @@ -0,0 +1,8 @@ +package run + +import "bitbucket.org/creachadair/shell" + +// Arg quotes a value such that it gets treated as an argument by a command. +// +// It is currently an alias for shell.Quote +func Arg(v string) string { return shell.Quote(v) } diff --git a/command.go b/command.go index f20b56c..4ac6521 100644 --- a/command.go +++ b/command.go @@ -26,10 +26,12 @@ type Command struct { } // Cmd joins all the parts and builds a command from it. +// +// Arguments are not implicitly quoted - to quote arguemnts, you can use Arg. func Cmd(ctx context.Context, parts ...string) *Command { args, ok := shell.Split(strings.Join(parts, " ")) if !ok { - return &Command{buildError: errors.New("provided args are invalid")} + return &Command{buildError: errors.New("provided parts has unclosed quotes")} } return &Command{ @@ -39,8 +41,10 @@ func Cmd(ctx context.Context, parts ...string) *Command { } // Bash joins all the parts and builds a command from it to be run by 'bash -c'. +// +// Arguments are not implicitly quoted - to quote arguemnts, you can use Arg. func Bash(ctx context.Context, parts ...string) *Command { - return Cmd(ctx, "bash -c", shell.Quote(strings.Join(parts, " "))) + return Cmd(ctx, "bash -c", Arg(strings.Join(parts, " "))) } // Run starts command execution and returns Output, which defaults to combined output. diff --git a/exit_code_test.go b/exit_code_test.go index 290ed63..c9f15b1 100644 --- a/exit_code_test.go +++ b/exit_code_test.go @@ -4,21 +4,21 @@ import ( "context" "fmt" - "bitbucket.org/creachadair/shell" "github.com/sourcegraph/run" ) func ExampleExitCode() { ctx := context.Background() - err := run.Cmd(ctx, "bash -c", shell.Quote("exit 123")).Run().Wait() + err := run.Bash(ctx, "exit 123").Run().Wait() fmt.Println(run.ExitCode(err)) - err = run.Cmd(ctx, "echo 'hello world!'").Run().Wait() + err = run.Cmd(ctx, "echo", run.Arg("hello world!")).Run().Wait() fmt.Println(run.ExitCode(err)) err = run.Cmd(ctx, "non-existing-binary").Run().Wait() fmt.Println(run.ExitCode(err)) + // Output: // 123 // 0