generated from LinuxSuRen/github-go
/
install.go
207 lines (184 loc) · 4.89 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
package cmd
import (
"archive/tar"
"compress/gzip"
"fmt"
"github.com/spf13/cobra"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
)
// NewInstallCmd returns the install command
func NewInstallCmd() (cmd *cobra.Command) {
opt := &installOption{}
cmd = &cobra.Command{
Use: "install",
PreRunE: opt.preRunE,
RunE: opt.runE,
}
flags := cmd.Flags()
//flags.StringVarP(&opt.Mode, "mode", "m", "package",
// "If you want to install it via platform package manager")
flags.BoolVarP(&opt.ShowProgress, "show-progress", "", true, "If show the progress of download")
flags.IntVarP(&opt.Thread, "thread", "t", 4,
`Download file with multi-threads. It only works when its value is bigger than 1`)
flags.BoolVarP(&opt.KeepPart, "keep-part", "", false,
"If you want to keep the part files instead of deleting them")
flags.StringVarP(&opt.Provider, "provider", "", ProviderGitHub, "The file provider")
flags.StringVarP(&opt.OS, "os", "", runtime.GOOS, "The OS of target binary file")
flags.StringVarP(&opt.Arch, "arch", "", runtime.GOARCH, "The arch of target binary file")
return
}
type installOption struct {
downloadOption
Mode string
}
func (o *installOption) preRunE(cmd *cobra.Command, args []string) (err error) {
if err = o.fetchHomeConfig(); err != nil {
// this is not a fatal, don't block the process
cmd.Printf("Failed with fetching home config: %v\n", err)
}
err = o.downloadOption.preRunE(cmd, args)
return
}
func (o *installOption) runE(cmd *cobra.Command, args []string) (err error) {
if err = o.downloadOption.runE(cmd, args); err != nil {
return
}
var source string
var target string
if o.Tar {
if err = o.extractFiles(o.Output, o.name); err == nil {
source = fmt.Sprintf("%s/%s", filepath.Dir(o.Output), o.name)
target = fmt.Sprintf("/usr/local/bin/%s", o.name)
} else {
err = fmt.Errorf("cannot extract %s from tar file, error: %v", o.Output, err)
}
} else {
source = o.downloadOption.Output
target = fmt.Sprintf("/usr/local/bin/%s", o.name)
}
if err == nil {
fmt.Println("install", source, "to", target)
err = o.overWriteBinary(source, target)
}
return
}
func (o *installOption) overWriteBinary(sourceFile, targetPath string) (err error) {
switch runtime.GOOS {
case "linux", "darwin":
if err = execCommand("chmod", "u+x", sourceFile); err != nil {
return
}
if err = execCommand("rm", "-rf", targetPath); err != nil {
return
}
var cp string
if cp, err = exec.LookPath("cp"); err == nil {
err = syscall.Exec(cp, []string{"cp", sourceFile, targetPath}, os.Environ())
}
default:
sourceF, _ := os.Open(sourceFile)
targetF, _ := os.OpenFile(targetPath, os.O_CREATE|os.O_RDWR, 0600)
if _, err = io.Copy(targetF, sourceF); err != nil {
err = fmt.Errorf("cannot copy %s from %s to %v, error: %v", o.name, sourceFile, targetPath, err)
}
}
return
}
func (o *installOption) extractFiles(tarFile, targetName string) (err error) {
var f *os.File
var gzf *gzip.Reader
if f, err = os.Open(tarFile); err != nil {
return
}
defer func() {
_ = f.Close()
}()
if gzf, err = gzip.NewReader(f); err != nil {
return
}
tarReader := tar.NewReader(gzf)
var header *tar.Header
var found bool
for {
if header, err = tarReader.Next(); err == io.EOF {
err = nil
break
} else if err != nil {
break
}
name := header.Name
switch header.Typeflag {
case tar.TypeReg:
if name != targetName && !strings.HasSuffix(name, "/"+targetName) {
continue
}
var targetFile *os.File
if targetFile, err = os.OpenFile(fmt.Sprintf("%s/%s", filepath.Dir(tarFile), targetName),
os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)); err != nil {
break
}
if _, err = io.Copy(targetFile, tarReader); err != nil {
break
}
found = true
_ = targetFile.Close()
}
}
if err == nil && !found {
err = fmt.Errorf("cannot found item '%s' from '%s'", targetName, tarFile)
}
return
}
func execCommand(name string, arg ...string) (err error) {
command := exec.Command(name, arg...)
//var stdout []byte
//var errStdout error
stdoutIn, _ := command.StdoutPipe()
stderrIn, _ := command.StderrPipe()
err = command.Start()
if err != nil {
return err
}
// cmd.Wait() should be called only after we finish reading
// from stdoutIn and stderrIn.
// wg ensures that we finish
var wg sync.WaitGroup
wg.Add(1)
go func() {
_, _ = copyAndCapture(os.Stdout, stdoutIn)
wg.Done()
}()
_, _ = copyAndCapture(os.Stderr, stderrIn)
wg.Wait()
err = command.Wait()
return
}
func copyAndCapture(w io.Writer, r io.Reader) ([]byte, error) {
var out []byte
buf := make([]byte, 1024, 1024)
for {
n, err := r.Read(buf[:])
if n > 0 {
d := buf[:n]
out = append(out, d...)
_, err := w.Write(d)
if err != nil {
return out, err
}
}
if err != nil {
// Read returns io.EOF at the end of file, which is not an error for us
if err == io.EOF {
err = nil
}
return out, err
}
}
}