8000 arg: introduce Arg alias, add note about quoting by bobheadxi · Pull Request #36 · sourcegraph/run · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions arg.go
Original file line number Diff line number Diff line change
@@ -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) }
8 changes: 6 additions & 2 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions exit_code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
0