-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathdocker_client.go
97 lines (75 loc) · 2.05 KB
/
docker_client.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 client
import "os/exec"
import "strings"
import "errors"
import "bufio"
import "fmt"
//DockerClient : Run docker commands
type DockerClient struct{}
//Status : Check if docker daemon is there
func (dc *DockerClient) Status() error {
cmdName := "docker"
args := []string{"info"}
return dc.runCommand(cmdName, args)
}
//Pull : Pull image
func (dc *DockerClient) Pull(image string) error {
if len(strings.TrimSpace(image)) == 0 {
return errors.New("Empty image")
}
cmdName := "docker"
args := []string{"pull", image}
return dc.runCommandWithOutput(cmdName, args)
}
//Tag :Tag image
func (dc *DockerClient) Tag(source, target string) error {
if len(strings.TrimSpace(source)) == 0 ||
len(strings.TrimSpace(target)) == 0 {
return errors.New("Empty images")
}
cmdName := "docker"
args := []string{"tag", source, target}
return dc.runCommandWithOutput(cmdName, args)
}
//Push : push image
func (dc *DockerClient) Push(image string) error {
if len(strings.TrimSpace(image)) == 0 {
return errors.New("Empty image")
}
cmdName := "docker"
args := []string{"push", image}
return dc.runCommandWithOutput(cmdName, args)
}
//Login : Login docker
func (dc *DockerClient) Login(userName, password string, uri string) error {
if len(strings.TrimSpace(userName)) == 0 ||
len(strings.TrimSpace(password)) == 0 {
return errors.New("Invlaid credential")
}
cmdName := "docker"
args := []string{"login", "-u", userName, "-p", password, uri}
return dc.runCommandWithOutput(cmdName, args)
}
func (dc *DockerClient) runCommand(cmdName string, args []string) error {
return exec.Command(cmdName, args...).Run()
}
func (dc *DockerClient) runCommandWithOutput(cmdName string, args []string) error {
cmd := exec.Command(cmdName, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
return err
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("%s out | %s\n", cmdName, scanner.Text())
}
}()
if err = cmd.Start(); err != nil {
return err
}
if err = cmd.Wait(); err != nil {
return err
}
return nil
}