forked from akatrevorjay/prefixout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (181 loc) · 4.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"strings"
"syscall"
docopt "github.com/docopt/docopt-go"
"github.com/logrusorgru/aurora"
)
var version = "0.0.1"
var self = path.Base(os.Args[0])
var logger = log.New(os.Stderr, fmt.Sprintf("%s: ", self), 0)
func orPanic(err error) {
if err == nil {
return
}
logger.Panic(err)
}
func main() {
var err error
usage := `Usage: prefixout [-dtc] [-p PREFIX | --prefix PREFIX] -- COMMAND [ARGS ...]
Prefixes stdout/stderr of a command. Nuff said.
Arguments:
PREFIX Prefix (defaults to "COMMAND: ")
COMMAND Command to exec
ARGS Command arguments
-d Differentiate stdout/stderr
-t Timestamp output
-c Color output`
arguments, err := docopt.Parse(usage, nil, true, fmt.Sprintf("prefixout %s", version), true)
orPanic(err)
au := aurora.NewAurora(arguments["-c"].(bool))
exec_args := make([]string, 0)
if arguments["ARGS"] != nil {
exec_args = append(exec_args, arguments["ARGS"].([]string)...)
}
if arguments["COMMAND"] == nil {
err := errors.New("No command specified")
orPanic(err)
}
exec_cmd := arguments["COMMAND"].(string)
exec_all := make([]string, 0)
exec_all = append(exec_all, exec_cmd)
exec_all = append(exec_all, exec_args...)
var prefix string
if arguments["PREFIX"] != nil {
prefix = arguments["PREFIX"].(string)
} else {
prefix = fmt.Sprintf("%s: ", exec_cmd)
}
prefix_flags := 0
if arguments["-t"].(bool) {
prefix_flags |= log.Ldate | log.Ltime
}
out_prefix := prefix
err_prefix := prefix
if arguments["-d"].(bool) {
err_prefix += "[stderr] "
}
logout := log.New(os.Stdout, "", prefix_flags)
slurperOut := NewSlurper(logout, out_prefix, func(prefix string, str string) string {
return au.Bold(prefix).String() + str
})
defer slurperOut.Close()
logerr := log.New(os.Stderr, "", prefix_flags)
slurperErr := NewSlurper(logerr, err_prefix, func(prefix string, str string) string {
return au.Bold(prefix).Red().String() + str
})
defer slurperErr.Close()
cmd := exec.Command(exec_cmd, exec_args...)
// Attach fds (stdin is handled by wait)
cmd.Stdout = slurperOut
cmd.Stderr = slurperErr
err = cmd.Start()
if err != nil {
logger.Fatalf("ERROR! Could not spawn command. %v\n", err.Error())
}
err = cmd.Wait()
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// The program has exited with an exit code != 0
// This works on both Unix and Windows. Although package
// syscall is generally platform dependent, WaitStatus is
// defined for both Unix and Windows and in both cases has
// an ExitStatus() method with the same signature.
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
code := status.ExitStatus()
os.Exit(code)
}
} else {
orPanic(err)
}
}
}
type Slurper struct {
Logger *log.Logger
buf *bytes.Buffer
prefix string
formatter func(string, string) string
}
func NewSlurper(logger *log.Logger, prefix string, formatter func(string, string) string) *Slurper {
l := &Slurper{
Logger: logger,
buf: bytes.NewBuffer([]byte("")),
prefix: prefix,
formatter: formatter,
}
return l
}
func termHasColors() bool {
// TODO Just check if tty and/or interactive.
term := os.Getenv("TERM")
if strings.HasSuffix(term, "color") || strings.HasPrefix(term, "xterm") {
return true
}
return false
}
func (l *Slurper) Write(p []byte) (n int, err error) {
if n, err = l.buf.Write(p); err != nil {
return
}
err = l.OutputLines()
return
}
func (l *Slurper) Close() error {
if err := l.Flush(); err != nil {
return err
}
l.buf = bytes.NewBuffer([]byte(""))
return nil
}
func (l *Slurper) Flush() error {
var p []byte
count, err := l.buf.Read(p)
if err != nil {
return err
}
if count > 0 {
l.out(string(p))
}
return nil
}
func (l *Slurper) OutputLines() error {
for {
line, err := l.buf.ReadString('\n')
if len(line) > 0 {
if strings.HasSuffix(line, "\n") {
l.out(line)
} else {
// put back into buffer, it's not a complete line yet
// Close() or Flush() have to be used to flush out
// the last remaining line if it does not end with a newline
if _, err := l.buf.WriteString(line); err != nil {
return err
}
}
}
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
func (l *Slurper) out(str string) {
if len(str) < 1 {
return
}
if l.formatter != nil {
str = l.formatter(l.prefix, str)
}
l.Logger.Print(str)
}