This repository has been archived by the owner on May 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
scan.go
122 lines (108 loc) · 2.5 KB
/
scan.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
package scan
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"sync"
"github.com/rogpeppe/rog-go/parallel"
"sourcegraph.com/sourcegraph/srclib/config"
"sourcegraph.com/sourcegraph/srclib/flagutil"
"sourcegraph.com/sourcegraph/srclib/unit"
)
type Options struct {
config.Options
// Quiet silences all output.
Quiet bool
}
// ScanMulti runs multiple scanner tools in parallel. It passes command-line
// options from opt to each one, and it sends the JSON representation of cfg
// (the repo/tree's Config) to each tool's stdin.
func ScanMulti(scanners [][]string, opt Options, treeConfig map[string]interface{}) ([]*unit.SourceUnit, error) {
if treeConfig == nil {
treeConfig = map[string]interface{}{}
}
var (
units []*unit.SourceUnit
mu sync.Mutex
)
run := parallel.NewRun(runtime.GOMAXPROCS(0))
for _, scanner_ := range scanners {
scanner := scanner_
run.Do(func() error {
units2, err := Scan(scanner, opt, treeConfig)
if err != nil {
return fmt.Errorf("scanner %v: %s", scanner, err)
}
mu.Lock()
defer mu.Unlock()
units = append(units, units2...)
return nil
})
}
err := run.Wait()
// Return error only if none of the commands succeeded.
if len(units) == 0 {
return nil, err
}
return units, nil
}
func Scan(scanner []string, opt Options, treeConfig map[string]interface{}) ([]*unit.SourceUnit, error) {
args, err := flagutil.MarshalArgs(&opt)
if err != nil {
return nil, err
}
var errw bytes.Buffer
cmd := exec.Command(scanner[0], scanner[1])
cmd.Args = append(cmd.Args, args...)
if opt.Quiet {
cmd.Stderr = &errw
} else {
cmd.Stderr = io.MultiWriter(&errw, os.Stderr)
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
defer func() {
if cmd.Process != nil {
cmd.Process.Kill()
}
}()
// Write the treeConfig into stdin.
w := bufio.NewWriter(stdin)
if err := json.NewEncoder(w).Encode(treeConfig); err != nil {
w.Flush()
return nil, err
}
if err := w.Flush(); err != nil {
return nil, err
}
if err := stdin.Close(); err != nil {
return nil, err
}
// Read on stdout into the list of source units.
var units []*unit.SourceUnit
if err := json.NewDecoder(stdout).Decode(&units); err != nil {
return nil, err
}
if err := cmd.Wait(); err != nil {
return nil, err
}
// Fill in repo.
for _, u := range units {
u.Repo = opt.Repo
}
return units, nil
}