forked from getantibody/antibody
/
antibody.go
73 lines (67 loc) · 1.37 KB
/
antibody.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
package antibodylib
import (
"bufio"
"io"
"os"
"strings"
"sync"
"github.com/caarlos0/gohome"
"github.com/getantibody/antibody/bundle"
"golang.org/x/sync/errgroup"
)
// Antibody the main thing
type Antibody struct {
r io.Reader
parallelism int
Home string
}
// New creates a new Antibody instance with the given parameters
func New(home string, r io.Reader, p int) *Antibody {
return &Antibody{
r: r,
parallelism: p,
Home: home,
}
}
// Bundle processes all given lines and returns the shell content to execute
func (a *Antibody) Bundle() (result string, err error) {
var g errgroup.Group
var lock sync.Mutex
var shs indexedLines
var idx int
sem := make(chan bool, a.parallelism)
scanner := bufio.NewScanner(a.r)
for scanner.Scan() {
l := scanner.Text()
index := idx
idx++
sem <- true
g.Go(func() error {
defer func() {
<-sem
}()
l = strings.TrimSpace(l)
if l != "" && l[0] != '#' {
s, berr := bundle.New(a.Home, l).Get()
lock.Lock()
shs = append(shs, indexedLine{index, s})
lock.Unlock()
return berr
}
return nil
})
}
if err = scanner.Err(); err != nil {
return
}
err = g.Wait()
return shs.String(), err
}
// Home finds the right home folder to use
func Home() string {
home := os.Getenv("ANTIBODY_HOME")
if home == "" {
home = gohome.Cache("antibody")
}
return home
}