added bash package
parent
8449fe8013
commit
969b4e42cd
@ -0,0 +1,52 @@
|
||||
// Copyright 2019 Drone.IO Inc. All rights reserved.
|
||||
// Use of this source code is governed by the Parity Public License
|
||||
// that can be found in the LICENSE file.
|
||||
|
||||
// Package shell provides functions for converting shell commands
|
||||
// to shell scripts.
|
||||
package bash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Suffix provides the shell script suffix. For posix systems
|
||||
// this value is an empty string.
|
||||
const Suffix = ""
|
||||
|
||||
// Command returns the shell command and arguments.
|
||||
func Command() (string, []string) {
|
||||
return "/bin/sh", []string{"-e"}
|
||||
}
|
||||
|
||||
// Script converts a slice of individual shell commands to
|
||||
// a posix-compliant shell script.
|
||||
func Script(commands []string) string {
|
||||
buf := new(bytes.Buffer)
|
||||
fmt.Fprintln(buf)
|
||||
fmt.Fprintf(buf, optionScript)
|
||||
fmt.Fprintln(buf)
|
||||
for _, command := range commands {
|
||||
escaped := fmt.Sprintf("%q", command)
|
||||
escaped = strings.Replace(escaped, "$", `\$`, -1)
|
||||
buf.WriteString(fmt.Sprintf(
|
||||
traceScript,
|
||||
escaped,
|
||||
command,
|
||||
))
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// optionScript is a helper script this is added to the build
|
||||
// to set shell options, in this case, to exit on error.
|
||||
const optionScript = "set -e"
|
||||
|
||||
// traceScript is a helper script that is added to
|
||||
// the build script to trace a command.
|
||||
const traceScript = `
|
||||
echo + %s
|
||||
%s
|
||||
`
|
@ -0,0 +1,43 @@
|
||||
// Copyright 2019 Drone.IO Inc. All rights reserved.
|
||||
// Use of this source code is governed by the Parity Public License
|
||||
// that can be found in the LICENSE file.
|
||||
|
||||
package bash
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCommands(t *testing.T) {
|
||||
cmd, args := Command()
|
||||
{
|
||||
got, want := cmd, "/bin/sh"
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Want command %v, got %v", want, got)
|
||||
}
|
||||
}
|
||||
{
|
||||
got, want := args, []string{"-e"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Want command %v, got %v", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScript(t *testing.T) {
|
||||
got, want := Script([]string{"go build", "go test"}), exampleScript
|
||||
if got != want {
|
||||
t.Errorf("Want %q, got %q", want, got)
|
||||
}
|
||||
}
|
||||
|
||||
var exampleScript = `
|
||||
set -e
|
||||
|
||||
echo + "go build"
|
||||
go build
|
||||
|
||||
echo + "go test"
|
||||
go test
|
||||
`
|
Loading…
Reference in New Issue