/
lookup.go
102 lines (90 loc) · 2.68 KB
/
lookup.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
package lookup
import (
"context"
"os"
"strings"
"github.com/XotoX1337/dogo/constants"
"github.com/XotoX1337/dogo/log"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
type Service struct {
Service string
Container string
Image string
}
type ConfigDetails struct {
Ready bool
Services []string
Containers []string
Images []string
ImageContainerMap []map[string]string
Config string
}
var ServicesMap = map[string]ConfigDetails{}
func Containers(toComplete string, all bool) []string {
options := types.ContainerListOptions{All: all}
containerList := ContainerList(options)
var containers []string
for _, container := range containerList {
containers = append(containers, container.Names[0][1:])
}
return containers
}
func Search(slice []string, query string) []string {
if query == "*" {
log.Warn("need at least one character for wildcard search")
os.Exit(1)
}
var found []string
for _, element := range slice {
if strings.HasSuffix(query, "*") {
if strings.HasPrefix(element, strings.TrimSuffix(query, "*")) {
found = append(found, element)
}
}
if element == query {
found = append(found, element)
}
}
return found
}
func Services(toComplete string, all bool) []string {
options := types.ContainerListOptions{All: all}
//flag all
containerList := ContainerList(options)
var services []string
for _, container := range containerList {
services = append(services, container.Image)
}
return services
}
func Client() *client.Client {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
log.Fatal("could not establish a connection with docker. Is docker installed?")
}
return cli
}
func ContainerList(options types.ContainerListOptions) []types.Container {
cli := Client()
containerList, err := cli.ContainerList(context.Background(), options)
if err != nil {
log.Fatal("could not establish a connection with docker. Is docker installed?")
}
return containerList
}
func GenerateServiceMap() {
containerList := ContainerList(types.ContainerListOptions{All: true})
for _, container := range containerList {
index := container.Labels[constants.COMPOSE_CONFIG_FILE_LABEL]
ServicesMap[index] = ConfigDetails{
Ready: true,
Services: append(ServicesMap[index].Services, container.Labels[constants.COMPOSE_SERVICE_LABEL]),
Images: append(ServicesMap[index].Images, container.Image),
Containers: append(ServicesMap[index].Containers, container.Names[0][1:]),
ImageContainerMap: append(ServicesMap[index].ImageContainerMap, map[string]string{container.Image: container.Names[0][1:]}),
Config: index,
}
}
}