github.com/drone/runner-go@v1.12.0/shell/bash/bash.go (about) 1 // Copyright 2019 Drone.IO Inc. All rights reserved. 2 // Use of this source code is governed by the Polyform License 3 // that can be found in the LICENSE file. 4 5 // Package shell provides functions for converting shell commands 6 // to shell scripts. 7 package bash 8 9 import ( 10 "bytes" 11 "fmt" 12 "strings" 13 ) 14 15 // Suffix provides the shell script suffix. For posix systems 16 // this value is an empty string. 17 const Suffix = "" 18 19 // Command returns the shell command and arguments. 20 func Command() (string, []string) { 21 return "/bin/sh", []string{"-e"} 22 } 23 24 func Script(commands []string) string { 25 return script(commands, true) 26 } 27 28 func SilentScript(commands []string) string { 29 return script(commands, false) 30 } 31 32 // Script converts a slice of individual shell commands to a posix-compliant shell script. 33 func script(commands []string, trace bool) string { 34 buf := new(bytes.Buffer) 35 fmt.Fprintln(buf) 36 fmt.Fprintf(buf, optionScript) 37 fmt.Fprintln(buf) 38 for _, command := range commands { 39 escaped := fmt.Sprintf("%q", command) 40 escaped = strings.Replace(escaped, "$", `\$`, -1) 41 var stringToWrite string 42 if trace { 43 stringToWrite = fmt.Sprintf( 44 traceScript, 45 escaped, 46 command, 47 ) 48 } else { 49 stringToWrite = "\n" + command + "\n" 50 } 51 buf.WriteString(stringToWrite) 52 } 53 return buf.String() 54 } 55 56 // optionScript is a helper script this is added to the build 57 // to set shell options, in this case, to exit on error. 58 const optionScript = "set -e" 59 60 // traceScript is a helper script that is added to 61 // the build script to trace a command. 62 const traceScript = ` 63 echo + %s 64 %s 65 `