generated from LinuxSuRen/github-go
/
install.go
356 lines (317 loc) · 10 KB
/
install.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package cmd
import (
"context"
"fmt"
"log"
sysos "os"
"path"
"strings"
"github.com/AlecAivazis/survey/v2"
fakeruntime "github.com/linuxsuren/go-fake-runtime"
"github.com/linuxsuren/http-downloader/pkg/common"
"github.com/linuxsuren/http-downloader/pkg/installer"
"github.com/linuxsuren/http-downloader/pkg/os"
"github.com/linuxsuren/http-downloader/pkg/version"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// newInstallCmd returns the install command
func newInstallCmd(ctx context.Context) (cmd *cobra.Command) {
opt := &installOption{
downloadOption: newDownloadOption(ctx),
execer: &fakeruntime.DefaultExecer{},
}
cmd = &cobra.Command{
Use: "install",
Aliases: []string{"i", "add"},
Short: "Install a package from https://github.com/LinuxSuRen/hd-home",
Long: `Install a package from https://github.com/LinuxSuRen/hd-home
Cannot find your desired package? Please run command: hd fetch --reset, then try it again`,
Example: "hd install goget",
PreRunE: opt.preRunE,
RunE: opt.runE,
GroupID: coreGroup.ID,
}
flags := cmd.Flags()
opt.addFlags(flags)
opt.addPlatformFlags(flags)
opt.addDownloadFlags(flags)
flags.StringVarP(&opt.Category, "category", "c", "",
"The category of the potentials packages")
flags.BoolVarP(&opt.AcceptPreRelease, "accept-preRelease", "", false,
"If you accept preRelease as the binary asset from GitHub")
flags.BoolVarP(&opt.AcceptPreRelease, "pre", "", false,
"Same with option --accept-preRelease")
flags.BoolVarP(&opt.fromSource, "from-source", "", false,
"Indicate if install it via go install github.com/xxx/xxx")
flags.StringVarP(&opt.fromBranch, "from-branch", "", "master",
"Only works if the flag --from-source is true")
flags.StringVarP(&opt.target, "target", "", opt.getDefaultInstallDir(), "The target installation directory")
flags.BoolVarP(&opt.goget, "goget", "", viper.GetBool("fetch"),
"Use command goget to download the binary, only works if the flag --from-source is true")
flags.BoolVarP(&opt.Download, "download", "", true,
"If download the package")
flags.BoolVarP(&opt.force, "force", "f", false,
"Indicate if force to download the package even it is exist")
flags.BoolVarP(&opt.CleanPackage, "clean-package", "", true,
"Clean the package if the installation is success")
flags.BoolVarP(&opt.KeepPart, "keep-part", "", false,
"If you want to keep the part files instead of deleting them")
return
}
func (o *installOption) getDefaultInstallDir() string {
switch o.execer.OS() {
case "linux", "darwin":
return "/usr/local/bin"
case "windows":
return `C:\Program Files (x86)\Common Files`
}
return ""
}
type installOption struct {
*downloadOption
Download bool
CleanPackage bool
fromSource bool
fromBranch string
target string
goget bool
force bool
// inner fields
nativePackage bool
tool string
execer fakeruntime.Execer
}
func (o *installOption) shouldInstall() (should, exist bool) {
var greater bool
if name, lookErr := o.execer.LookPath(o.tool); lookErr == nil {
exist = true
var versionCmd string
if o.downloadOption != nil && o.downloadOption.Package != nil && o.downloadOption.Package.VersionCmd != "" {
versionCmd = o.downloadOption.Package.VersionCmd
}
if versionCmd != "" {
log.Println("check target version via", name, versionCmd)
if data, err := o.execer.Command(name, versionCmd); err == nil &&
(o.downloadOption.Package != nil && o.downloadOption.Package.Version != "") {
greater = version.GreatThan(o.downloadOption.Package.Version, string(data))
}
}
}
should = o.force || !exist || greater
return
}
func (o *installOption) preRunE(cmd *cobra.Command, args []string) (err error) {
if len(args) > 0 {
o.tool = args[0]
}
if o.tool == "" && o.Category == "" {
err = fmt.Errorf("tool or category name is requried")
return
}
// try to find if it's a native package
o.nativePackage = os.HasPackage(o.tool)
if !o.nativePackage {
if o.Category == "" {
err = o.downloadOption.preRunE(cmd, args)
if o.downloadOption.Package != nil {
// try to find the real tool name
if o.downloadOption.Package.TargetBinary != "" {
o.tool = o.downloadOption.Package.TargetBinary
} else if o.downloadOption.Package.Binary != "" {
o.tool = o.downloadOption.Package.Binary
} else {
o.tool = o.downloadOption.Package.Repo
}
}
} else {
err = o.downloadOption.fetch()
}
}
return
}
func (o *installOption) install(cmd *cobra.Command, args []string) (err error) {
if o.nativePackage {
// install a package
if should, exist := o.shouldInstall(); !should {
if exist {
cmd.Printf("%s is already exist, please use the flag --force if you install it again\n", o.tool)
}
return
}
var proxy map[string]string
if o.ProxyGitHub != "" {
proxy = map[string]string{
"https://raw.githubusercontent.com": fmt.Sprintf("https://%s/https://raw.githubusercontent.com", o.ProxyGitHub),
"https://github.com": fmt.Sprintf("https://%s/https://github.com", o.ProxyGitHub),
}
}
err = os.InstallWithProxy(args[0], proxy)
return
}
// aka go get github.com/xxx/xxx
if o.fromSource {
err = o.installFromSource()
return
}
// install a package from hd-home
if o.Download {
log.Println("check if it should be installed")
if should, exist := o.shouldInstall(); !should {
if exist {
cmd.Printf("%s is already exist, please use the flag --force if you install it again\n", o.tool)
return
}
}
if err = o.downloadOption.runE(cmd, args); err != nil {
return
}
}
if o.Package == nil {
o.Package = &installer.HDConfig{}
}
if o.target != "" && o.Package.TargetDirectory == "" {
o.Package.TargetDirectory = o.target
}
if o.Package.TargetDirectory == "" {
o.Package.TargetDirectory = "/usr/local/bin"
}
if err = sysos.MkdirAll(o.Package.TargetDirectory, 0750); err != nil {
return
}
log.Println("target directory", o.Package.TargetDirectory)
process := &installer.Installer{
Source: o.downloadOption.Output,
Name: o.name,
Package: o.Package,
Tar: o.Tar,
Output: o.Output,
CleanPackage: o.CleanPackage,
AdditionBinaries: o.Package.AdditionBinaries,
TargetDirectory: o.Package.TargetDirectory,
Execer: o.execer,
}
// install requirements tools in the post phase
if len(o.Package.Requirements) > 0 {
if len(o.Package.PostInstalls) == 0 {
o.Package.PostInstalls = make([]installer.CmdWithArgs, 0)
}
for i := range o.Package.Requirements {
tool := o.Package.Requirements[i]
o.Package.PostInstalls = append(o.Package.PostInstalls, installer.CmdWithArgs{
Cmd: "hd",
Args: []string{"install", tool},
})
}
}
err = process.Install()
return
}
func (o *installOption) runE(cmd *cobra.Command, args []string) (err error) {
if o.Category != "" {
packages := installer.FindPackagesByCategory(o.Category)
orgAndRepos := make([]string, len(packages))
for i := range packages {
orgAndRepos[i] = fmt.Sprintf("%s/%s", packages[i].Org, packages[i].Repo)
}
if len(orgAndRepos) == 0 {
err = fmt.Errorf("cannot find any tools by category: %s", o.Category)
return
}
selector := &survey.MultiSelect{
Message: "Select packages",
Options: orgAndRepos,
}
var choose []string
if err = survey.AskOne(selector, &choose); err != nil {
return
}
for _, item := range choose {
if err = o.downloadOption.preRunE(cmd, []string{item}); err != nil {
return
}
// try to find the real tool name
if o.downloadOption.Package.TargetBinary != "" {
o.tool = o.downloadOption.Package.TargetBinary
} else if o.downloadOption.Package.Binary != "" {
o.tool = o.downloadOption.Package.Binary
} else {
o.tool = o.downloadOption.Package.Repo
}
if err = o.install(cmd, []string{item}); err != nil {
return
}
o.Output = "" // TODO this field must be set to be empty for the next round, need a better solution here
}
} else {
err = o.install(cmd, args)
}
return
}
func (o *installOption) installFromSource() (err error) {
if !o.Package.FromSource {
err = fmt.Errorf("not support install it from source")
return
}
if o.Provider != "github" {
err = fmt.Errorf("only support github.com")
return
}
if o.org == "" || o.repo == "" {
err = fmt.Errorf("org: '%s' or repo: '%s' is empty", o.org, o.repo)
return
}
var binaryPath string
if o.goget {
binaryPath, err = o.runGogetCommand(fmt.Sprintf("github.com/%s/%s", o.org, o.repo), o.repo)
} else {
binaryPath, err = o.buildGoSource()
}
if err == nil && binaryPath != "" {
is := &installer.Installer{}
targetName := o.name
if o.Package != nil && o.Package.TargetBinary != "" {
targetName = o.Package.TargetBinary
}
err = is.OverWriteBinary(binaryPath, path.Join(o.Package.TargetDirectory, targetName))
}
return
}
func (o *installOption) buildGoSource() (binaryPath string, err error) {
gopath := sysos.Getenv("GOPATH")
if gopath == "" {
err = fmt.Errorf("GOPATH is required")
return
}
if err = o.execer.RunCommandInDir("go", sysos.TempDir(), strings.Split(o.buildGoInstallCmd(), " ")[1:]...); err != nil {
err = fmt.Errorf("faield to run go install command, error: %v", err)
return
}
binaryPath = path.Join(gopath, fmt.Sprintf("bin/%s", o.name))
if !common.Exist(binaryPath) {
err = fmt.Errorf("no found %s from GOPATH", o.name)
}
return
}
func (o *installOption) buildGoInstallCmd() string {
return fmt.Sprintf("go install github.com/%s/%s@%s", o.org, o.repo, o.fromBranch)
}
func (o *installOption) runGogetCommand(repo, name string) (binaryPath string, err error) {
// make sure goget command exists
is := installer.Installer{
Provider: "github",
}
if err = is.CheckDepAndInstall(map[string]string{
"goget": "linuxsuren/goget",
}); err != nil {
err = fmt.Errorf("cannot download goget, error: %v", err)
return
}
// run goget command
tmpPath := sysos.TempDir()
binaryPath = path.Join(tmpPath, name)
if err = o.execer.RunCommandInDir("goget", tmpPath, repo); err != nil {
err = fmt.Errorf("faield to run go install command, error: %v", err)
}
return
}