Skip to content

Instantly share code, notes, and snippets.

@heyLu
Last active September 10, 2015 09:45
Show Gist options
  • Save heyLu/ed44463c17017153a54f to your computer and use it in GitHub Desktop.
Save heyLu/ed44463c17017153a54f to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
)
func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: %s <cmd> [<args>]*\n", os.Args[0])
os.Exit(1)
}
cmdName := os.Args[1]
var cmdArgs []string
if len(os.Args) > 2 {
cmdArgs = os.Args[2:]
}
cmd := exec.Command(cmdName, cmdArgs...)
cmd.Stdout = newIndentWriter(">>> ", os.Stdout)
cmd.Stderr = newIndentWriter(">>> ", os.Stderr)
err := cmd.Run()
fmt.Println()
if err != nil {
fmt.Println("Error:", err)
}
}
type indentWriter struct {
prefix []byte
writer io.Writer
needsPrefix bool // true when next write needs to write the prefix first
}
func newIndentWriter(prefix string, writer io.Writer) *indentWriter {
return &indentWriter{
prefix: []byte(prefix),
writer: writer,
needsPrefix: true,
}
}
func (iw *indentWriter) Write(data []byte) (int, error) {
if iw.needsPrefix {
_, err := iw.writer.Write(iw.prefix)
if err != nil {
return 0, err // no bytes from data written yet
}
iw.needsPrefix = false
}
newLine := bytes.IndexByte(data, '\n')
if newLine == -1 {
return iw.writer.Write(data)
}
n, err := iw.writer.Write(data[0 : newLine+1])
if err != nil {
return n, err
}
iw.needsPrefix = true
nn, err := iw.Write(data[newLine+1:])
return n + nn, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment