forked from monzo/orchestra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
114 lines (103 loc) · 2.6 KB
/
utils.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
package commands
import (
"math"
"os"
"path/filepath"
"strings"
log "github.com/cihub/seelog"
"github.com/urfave/cli/v2"
"github.com/tifo/orchestra/config"
"github.com/tifo/orchestra/services"
)
// niceness used for subprocesses
// https://en.wikipedia.org/wiki/Nice_(Unix)
const niceness = "1"
// This is temporary, very very alpha and may change soon
func FilterServices(c *cli.Context) map[string]*services.Service {
excludeMode := 0
args := c.Args().Slice()
included := make(map[string]bool)
for _, s := range args {
name := s
if strings.HasPrefix(s, "~") {
name = strings.Replace(s, "~", "", 1)
}
// Remove trailing slash to help with file autocomplete
name = strings.TrimRight(name, "/")
// Alias `.` to the current service if it exists
if name == "." {
cwd, _ := os.Getwd()
name, _ = filepath.Rel(services.ProjectPath, cwd)
}
// Check if arg match a service or a stack
if _, ok := services.Registry[name]; ok {
if strings.HasPrefix(s, "~") {
excludeMode += 1
delete(services.Registry, name)
} else {
excludeMode -= 1
included[name] = true
}
} else if stack, ok := services.StackRegistry[name]; ok {
if strings.HasPrefix(s, "~") {
excludeMode += 1
for _, svc := range stack {
delete(services.Registry, svc.Name)
}
delete(services.StackRegistry, name)
} else {
excludeMode -= 1
for _, svc := range stack {
included[svc.Name] = true
}
}
} else {
_ = log.Errorf("Service or stack %s not found", name)
return nil
}
}
if math.Abs(float64(excludeMode)) != float64(len(args)) {
_ = log.Critical("You can't exclude and include services at the same time")
os.Exit(1)
}
if excludeMode < 0 {
for name := range services.Registry {
if !included[name] {
delete(services.Registry, name)
}
}
}
return services.Registry
}
func BeforeAfterWrapper(f func(c *cli.Context) error) func(c *cli.Context) error {
return func(c *cli.Context) error {
err := config.GetBeforeFunc()(c)
if err != nil {
appendError(err)
}
_ = f(c)
err = config.GetAfterFunc()(c)
if err != nil {
appendError(err)
}
return nil
}
}
// GetEnvForService returns all the environment variables for a given service
// including the ones specified in the global config
func GetEnvForService(c *cli.Context, service *services.Service) []string {
return append(service.Env, config.GetEnvForCommand(c)...)
}
type workerPool chan struct{}
func (p workerPool) Drain() {
for i := 0; i < cap(p); i++ {
p <- struct{}{}
}
}
func (p workerPool) Do(impl func()) {
p <- struct{}{}
go func() {
defer func() { <-p }()
impl()
}()
}