-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.go
97 lines (79 loc) · 1.67 KB
/
runner.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"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sync"
"syscall"
"github.com/adrg/xdg"
"golang.org/x/term"
)
var cfgFilePath = func(fileName string) string {
return filepath.Join(xdg.ConfigHome, irirDir, fileName)
}
func run() error {
o := parseArgs()
rule, err := loadRule(cfgFilePath, o.rule)
if err != nil {
return err
}
if o.wrapCmdName != "" {
return wrapCommand(o, rule)
}
if term.IsTerminal(int(syscall.Stdin)) {
os.Exit(exitOK)
}
routine(os.Stdin, rule)
return nil
}
func wrapCommand(o *options, rule []*Rule) error {
cmd := exec.Command(o.wrapCmdName, o.wrapCmdArgs...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("stdout pipe error %#v, %w", cmd.String(), err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return fmt.Errorf("stderr pipe error %#v, %w", cmd.String(), err)
}
if err := cmd.Start(); err != nil {
return fmt.Errorf("could not start %#v, %w", cmd.String(), err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
routine(stdout, rule)
}()
wg.Add(1)
go func() {
defer wg.Done()
routine(stderr, rule)
}()
wg.Wait()
if err := cmd.Wait(); err != nil {
return fmt.Errorf("something went wrong %#v, %w", cmd.String(), err)
}
return nil
}
func routine(r io.Reader, rule []*Rule) error {
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Bytes()
result, err := process(line, rule)
if err != nil {
putErr(err.Error())
result = line
}
if _, err := os.Stdout.Write(result); err != nil {
return err
}
if _, err := os.Stdout.WriteString("\n"); err != nil {
return fmt.Errorf("fail to write string %w", err)
}
}
return nil
}