forked from go-kratos/kratos
/
tool.go
284 lines (262 loc) · 5.78 KB
/
tool.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"fmt"
"go/build"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"github.com/fatih/color"
"github.com/urfave/cli/v2"
)
const (
toolDoc = "https://go-kratos.github.io/kratos/#/kratos-tool"
)
// Tool is kratos tool.
type Tool struct {
Name string `json:"name"`
Alias string `json:"alias"`
BuildTime time.Time `json:"build_time"`
Install string `json:"install"`
Requirements []string `json:"requirements"`
Dir string `json:"dir"`
Summary string `json:"summary"`
Platform []string `json:"platform"`
Author string `json:"author"`
URL string `json:"url"`
Hidden bool `json:"hidden"`
requires []*Tool
}
func toolAction(c *cli.Context) (err error) {
if c.NArg() == 0 {
sort.Slice(toolIndexs, func(i, j int) bool { return toolIndexs[i].BuildTime.After(toolIndexs[j].BuildTime) })
for _, t := range toolIndexs {
if t.Hidden {
continue
}
updateTime := t.BuildTime.Format("2006/01/02")
fmt.Printf("%s%s: %s Author(%s) [%s]\n", color.HiMagentaString(t.Name), getNotice(t), color.HiCyanString(t.Summary), t.Author, updateTime)
}
fmt.Println("\n安装工具: kratos tool install demo")
fmt.Println("执行工具: kratos tool demo")
fmt.Println("安装全部工具: kratos tool install all")
fmt.Println("全部升级: kratos tool upgrade all")
fmt.Println("\n详细文档:", toolDoc)
return
}
commond := c.Args().First()
switch commond {
case "upgrade":
upgradeAll()
return
case "install":
name := c.Args().Get(1)
if name == "all" {
installAll()
} else {
install(name)
}
return
case "check_install":
if e := checkInstall(c.Args().Get(1)); e != nil {
fmt.Fprintf(os.Stderr, fmt.Sprintf("%v\n", e))
}
return
}
if e := installAndRun(commond, c.Args().Slice()[1:]); e != nil {
fmt.Fprintf(os.Stderr, fmt.Sprintf("%v\n", e))
}
return
}
func installAndRun(name string, args []string) (err error) {
for _, t := range toolList() {
if name == t.Name {
if !t.installed() || t.needUpdated() {
t.install()
}
pwd, _ := os.Getwd()
err = runTool(t.Name, pwd, t.toolPath(), args)
return
}
}
return fmt.Errorf("找不到%s", name)
}
func checkInstall(name string) (err error) {
for _, t := range toolList() {
if name == t.Name {
if !t.installed() || t.needUpdated() {
t.install()
}
return
}
}
return fmt.Errorf("找不到%s", name)
}
func upgradeAction(c *cli.Context) error {
install("kratos")
return nil
}
func install(name string) {
if name == "" {
fmt.Fprintf(os.Stderr, color.HiRedString("请填写要安装的工具名称\n"))
return
}
for _, t := range toolList() {
if name == t.Name {
t.install()
return
}
}
fmt.Fprintf(os.Stderr, color.HiRedString("安装失败 找不到 %s\n", name))
return
}
func installAll() {
for _, t := range toolList() {
if t.Install != "" {
t.install()
}
}
}
func upgradeAll() {
for _, t := range toolList() {
if t.needUpdated() {
t.install()
}
}
}
func toolList() (tools []*Tool) {
return toolIndexs
}
func getNotice(t *Tool) (notice string) {
if !t.supportOS() || t.Install == "" {
return
}
notice = color.HiGreenString("(未安装)")
if t.installed() {
notice = color.HiBlueString("(已安装)")
if t.needUpdated() {
notice = color.RedString("(有更新)")
}
}
return
}
func (t Tool) needUpdated() bool {
for _, r := range t.requires {
if r.needUpdated() {
return true
}
}
if !t.supportOS() || t.Install == "" {
return false
}
if f, err := os.Stat(t.toolPath()); err == nil {
if t.BuildTime.After(f.ModTime()) {
return true
}
}
return false
}
func (t Tool) toolPath() string {
name := t.Alias
if name == "" {
name = t.Name
}
gobin := Getenv("GOBIN")
if runtime.GOOS == "windows" {
name += ".exe"
}
if gobin != "" {
return filepath.Join(gobin, name)
}
return filepath.Join(gopath(), "bin", name)
}
func (t Tool) installed() bool {
_, err := os.Stat(t.toolPath())
return err == nil
}
func (t Tool) supportOS() bool {
for _, p := range t.Platform {
if strings.ToLower(p) == runtime.GOOS {
return true
}
}
return false
}
func (t Tool) install() {
if t.Install == "" {
fmt.Fprintf(os.Stderr, color.RedString("%s: 自动安装失败详情请查看文档:%s\n", t.Name, toolDoc))
return
}
fmt.Println(t.Install)
cmds := strings.Split(t.Install, " ")
if len(cmds) > 0 {
if err := runTool(t.Name, path.Dir(t.toolPath()), cmds[0], cmds[1:]); err == nil {
color.Green("%s: 安装成功!", t.Name)
}
}
}
func (t Tool) updated() bool {
if !t.supportOS() || t.Install == "" {
return false
}
if f, err := os.Stat(t.toolPath()); err == nil {
if t.BuildTime.After(f.ModTime()) {
return true
}
}
return false
}
func gopath() (gp string) {
gopaths := strings.Split(Getenv("GOPATH"), string(filepath.ListSeparator))
if len(gopaths) == 1 && gopaths[0] != "" {
return gopaths[0]
}
pwd, err := os.Getwd()
if err != nil {
return
}
abspwd, err := filepath.Abs(pwd)
if err != nil {
return
}
for _, gopath := range gopaths {
if gopath == "" {
continue
}
absgp, err := filepath.Abs(gopath)
if err != nil {
return
}
if strings.HasPrefix(abspwd, absgp) {
return absgp
}
}
return build.Default.GOPATH
}
func runTool(name, dir, cmd string, args []string) (err error) {
toolCmd := &exec.Cmd{
Path: cmd,
Args: append([]string{cmd}, args...),
Dir: dir,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Env: os.Environ(),
}
if filepath.Base(cmd) == cmd {
var lp string
if lp, err = exec.LookPath(cmd); err == nil {
toolCmd.Path = lp
}
}
if err = toolCmd.Run(); err != nil {
if e, ok := err.(*exec.ExitError); !ok || !e.Exited() {
fmt.Fprintf(os.Stderr, "运行 %s 出错: %v\n", name, err)
}
}
return
}