-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·97 lines (86 loc) · 1.5 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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"strings"
"sync"
)
var (
nworker = flag.Int("c", 50, "concurrent")
)
type lineWriter struct {
buf bytes.Buffer
}
func (w *lineWriter) Write(b []byte) (int, error) {
for _, c := range b {
if c == '\n' {
w.Flush()
} else {
w.buf.WriteByte(c)
}
}
return len(b), nil
}
func (w *lineWriter) Flush() {
if w.buf.Len() != 0 {
fmt.Println(w.buf.String())
w.buf.Reset()
}
}
type item struct {
data string
idx int
}
func render(cmd string, x item) string {
fs := strings.Fields(x.data)
for i := 1; i < 10; i++ {
old := fmt.Sprintf("{{%d}}", i)
new := ""
if i <= len(fs) {
new = fs[i-1]
}
cmd = strings.Replace(cmd, old, new, -1)
}
cmd = strings.Replace(cmd, "{{i}}", fmt.Sprint(x.idx), -1)
return cmd
}
func worker(cmd string, ch chan item, wg *sync.WaitGroup) {
defer wg.Done()
stdout := new(lineWriter)
stderr := new(lineWriter)
for item := range ch {
cmdstr := render(cmd, item)
c := exec.Command("bash", "-c", cmdstr)
c.Stdout = stdout
c.Stderr = stderr
c.Run()
stdout.Flush()
stderr.Flush()
}
}
func main() {
flag.Parse()
if flag.NArg() != 1 {
fmt.Fprintf(os.Stderr, "usage: %s $cmd", os.Args[0])
return
}
wg := new(sync.WaitGroup)
ch := make(chan item, *nworker)
for i := 0; i < *nworker; i++ {
wg.Add(1)
go worker(flag.Arg(0), ch, wg)
}
idx := 0
r := bufio.NewScanner(os.Stdin)
for r.Scan() {
idx++
line := r.Text()
ch <- item{line, idx}
}
close(ch)
wg.Wait()
}