-
Notifications
You must be signed in to change notification settings - Fork 3
/
dependencies.go
134 lines (110 loc) · 2.38 KB
/
dependencies.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
123
124
125
126
127
128
129
130
131
132
133
134
package goclitools
import (
"errors"
"fmt"
"regexp"
"time"
"github.com/urfave/cli"
)
type DependencyScript interface {
Run() error
}
type DependencyScriptFn struct {
Fn func() error
}
func (script DependencyScriptFn) Run() error {
return script.Fn()
}
type DependencyScriptString struct {
Fn string
}
func (script DependencyScriptString) Run() error {
return RunInteractive(script.Fn)
}
type Dependency struct {
Name string
CheckCmd string
CheckCmdValidation string
Dependencies []Dependency
InstallScripts []DependencyScript
UninstallScripts []DependencyScript
}
func (d *Dependency) Check() (bool, error) {
output, err := Run(d.CheckCmd)
if err != nil {
if ee, ok := err.(*cli.ExitError); ok {
if ee.ExitCode() != 1 {
return false, ee
}
} else {
return false, err
}
}
if d.CheckCmdValidation != "" {
if matched, err := regexp.Match(d.CheckCmdValidation, output); err != nil || !matched {
return false, nil
}
}
return string(output) != "", nil
}
func (d *Dependency) Install() error {
res, _ := d.Check()
if res == true {
Logf("%s is already installed\n", d.Name)
return nil
}
for _, dep := range d.Dependencies {
Log("Validating subdependency", dep.Name)
if err := dep.Install(); err != nil {
return err
}
}
count := len(d.InstallScripts)
if count == 0 {
return fmt.Errorf("%s cannot be installed (no install scripts)", d.Name)
}
for key, script := range d.InstallScripts {
Logf("Running installation script %d/%d\n", key+1, count)
if err := script.Run(); err != nil {
return err
}
}
Logf("Waiting for installation check to pass: ")
attempts := 0
for true {
installed, err := d.Check()
if err != nil {
PrintNotOK()
return err
}
if installed {
break
}
if attempts > 60 {
PrintNotOK()
return errors.New("Installation check pass failed: timeout")
}
attempts++
time.Sleep(time.Second)
}
PrintOK()
return nil
}
func (d *Dependency) Uninstall() error {
res, _ := d.Check()
if res == false {
Logf("%s is not installed\n", d.Name)
return nil
}
count := len(d.UninstallScripts)
if count == 0 {
return fmt.Errorf("%s cannot be uninstalled (no uninstall scripts)", d.Name)
}
for key, script := range d.UninstallScripts {
Logf("Running uninstallation script %d/%d\n", key+1, count)
if err := script.Run(); err != nil {
return err
}
}
return nil
}