forked from gpmgo/gopm
/
gpm.go
440 lines (372 loc) · 10 KB
/
gpm.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// Copyright (c) 2013 GPMGo Members. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// gpm(Go Package Manager) is a Go package manage tool for search, install, update and share packages in Go.
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"text/template"
"unicode"
"unicode/utf8"
"github.com/BurntSushi/toml"
"github.com/GPMGo/gpm/doc"
"github.com/GPMGo/gpm/utils"
)
var (
config tomlConfig
appPath string // Application path.
)
var (
localNodes []*doc.Node
localBundles []*doc.Bundle
)
// Use for i18n, key is prompt code, value is corresponding message.
var promptMsg map[string]string
type tomlConfig struct {
Title, Version string
Lang string `toml:"user_language"`
AutoBackup bool `toml:"auto_backup"`
Account account
AutoEnable flagEnable `toml:"auto_enable"`
}
type flagEnable struct {
Build, Install, Search, Check []string
}
type account struct {
Username, Password string
Github_Access_Token string `toml:"github_access_token"`
}
// A Command is an implementation of a go command
// like go build or go fix.
type Command struct {
// Run runs the command.
// The args are the arguments after the command name.
Run func(cmd *Command, args []string)
// UsageLine is the one-line usage message.
// The first word in the line is taken to be the command name.
UsageLine string
// Short is the short description shown in the 'go help' output.
Short string
// Long is the long message shown in the 'go help <this-command>' output.
Long string
// Flag is a set of flags specific to this command.
Flags map[string]bool
}
// Name returns the command's name: the first word in the usage line.
func (c *Command) Name() string {
name := c.UsageLine
i := strings.Index(name, " ")
if i >= 0 {
name = name[:i]
}
return name
}
func (c *Command) Usage() {
fmt.Fprintf(os.Stderr, "usage: %s\n\n", c.UsageLine)
fmt.Fprintf(os.Stderr, "%s\n", strings.TrimSpace(c.Long))
os.Exit(2)
}
// Runnable reports whether the command can be run; otherwise
// it is a documentation pseudo-command such as importpath.
func (c *Command) Runnable() bool {
return c.Run != nil
}
// Commands lists the available commands and help topics.
// The order here is the order in which they are printed by 'gpm help'.
var commands = []*Command{
cmdBuild,
cmdSearch,
cmdInstall,
cmdRemove,
cmdCheck,
}
// getAppPath returns application execute path for current process.
func getAppPath() bool {
// Look up executable in PATH variable.
appPath, _ = exec.LookPath("gpm")
if len(appPath) == 0 {
fmt.Printf("ERROR: getAppPath -> Unable to indicate current execute path.\n")
return false
}
if runtime.GOOS == "windows" {
// Replace all '\' to '/'.
appPath = strings.Replace(filepath.Dir(appPath), "\\", "/", -1) + "/"
}
doc.SetAppConfig(appPath, config.AutoBackup)
return true
}
// loadPromptMsg loads prompt messages according to user language.
func loadPromptMsg(lang string) bool {
promptMsg = make(map[string]string)
// Load prompt messages.
f, err := os.Open(appPath + "i18n/" + lang + "/prompt.txt")
if err != nil {
fmt.Printf("ERROR: loadUsage -> Fail to load prompt messages[ %s ]\n", err)
return false
}
defer f.Close()
// Read prompt messages.
fi, _ := f.Stat()
promptBytes := make([]byte, fi.Size())
f.Read(promptBytes)
promptStrs := strings.Split(string(promptBytes), "\n")
for _, p := range promptStrs {
i := strings.Index(p, "=")
if i > -1 {
promptMsg[p[:i]] = p[i+1:]
}
}
return true
}
// loadUsage loads usage according to user language.
func loadUsage(lang string) bool {
if !loadPromptMsg(lang) {
return false
}
// Load main usage.
f, err := os.Open(appPath + "i18n/" + lang + "/usage.tpl")
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadUsage -> %s\n", promptMsg["LoadCommandUsage"]), "main", err)
return false
}
defer f.Close()
// Read main usages.
fi, _ := f.Stat()
usageBytes := make([]byte, fi.Size())
f.Read(usageBytes)
usageTemplate = string(usageBytes)
// Load command usage.
for _, cmd := range commands {
f, err := os.Open(appPath + "i18n/" + lang + "/usage_" + cmd.Name() + ".txt")
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadUsage -> %s\n", promptMsg["LoadCommandUsage"]), cmd.Name(), err)
return false
}
defer f.Close()
// Read usage.
fi, _ := f.Stat()
usageBytes := make([]byte, fi.Size())
f.Read(usageBytes)
usages := strings.Split(string(usageBytes), "|||")
if len(usages) < 2 {
fmt.Printf(
fmt.Sprintf("ERROR: loadUsage -> %s\n", promptMsg["ReadCoammndUsage"]), cmd.Name())
return false
}
cmd.Short = usages[0]
cmd.Long = usages[1]
}
return true
}
// loadLocalNodes loads nodes information from local file system.
func loadLocalNodes() bool {
if !utils.IsExist(appPath + "data/nodes.json") {
os.MkdirAll(appPath+"data/", os.ModePerm)
} else {
fr, err := os.Open(appPath + "data/nodes.json")
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalNodes -> %s\n", promptMsg["LoadLocalData"]), err)
return false
}
defer fr.Close()
err = json.NewDecoder(fr).Decode(&localNodes)
if err != nil && err != io.EOF {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalNodes -> %s\n", promptMsg["ParseJSON"]), err)
return false
}
}
return true
}
// loadLocalBundles loads bundles from local file system.
func loadLocalBundles() bool {
// Find all bundles.
dir, err := os.Open(appPath + "repo/bundles/")
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalBundles -> %s\n", promptMsg["OpenFile"]), err)
return false
}
defer dir.Close()
fis, err := dir.Readdir(0)
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalBundles -> %s\n", promptMsg["OpenFile"]), err)
return false
}
for _, fi := range fis {
// In case this folder contains unexpected directories.
if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".json") {
fr, err := os.Open(appPath + "repo/bundles/" + fi.Name())
if err != nil {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalBundles -> %s\n", promptMsg["OpenFile"]), err)
return false
}
bundle := new(doc.Bundle)
err = json.NewDecoder(fr).Decode(bundle)
fr.Close()
if err != nil && err != io.EOF {
fmt.Printf(fmt.Sprintf("ERROR: loadLocalBundles -> %s\n", promptMsg["ParseJSON"]), err)
return false
}
// Make sure bundle name is not empty.
if len(bundle.Name) == 0 {
bundle.Name = fi.Name()[:strings.Index(fi.Name(), ".")]
}
localBundles = append(localBundles, bundle)
}
}
return true
}
// We don't use init() to initialize
// bacause we need to get execute path in runtime.
func initialize() bool {
// Try to have highest performance.
runtime.GOMAXPROCS(runtime.NumCPU())
// Get application execute path.
if !getAppPath() {
return false
}
// Load configuration.
if _, err := toml.DecodeFile(appPath+"conf/gpm.toml", &config); err != nil {
fmt.Printf("initialize -> Fail to load configuration[ %s ]\n", err)
return false
}
// Set github.com access token.
doc.SetGithubCredentials(config.Account.Github_Access_Token)
// Load usages by language.
if !loadUsage(config.Lang) {
return false
}
// Create bundle and snapshot directories.
os.MkdirAll(appPath+"repo/bundles/", os.ModePerm)
os.MkdirAll(appPath+"repo/snapshots/", os.ModePerm)
// Create local tarball directories.
os.MkdirAll(appPath+"repo/tarballs/", os.ModePerm)
// Initialize local data.
if !loadLocalNodes() || !loadLocalBundles() {
return false
}
return true
}
func main() {
// Initialization.
if !initialize() {
return
}
// Check length of arguments.
args := os.Args[1:]
if len(args) < 1 {
usage()
return
}
// Show help documentation.
if args[0] == "help" {
help(args[1:])
return
}
// Check commands and run.
for _, cmd := range commands {
if cmd.Name() == args[0] && cmd.Run != nil {
cmd.Run(cmd, args[1:])
exit()
return
}
}
// Uknown commands.
fmt.Fprintf(os.Stderr, fmt.Sprintf("%s\n", promptMsg["UnknownCommand"]), args[0])
setExitStatus(2)
exit()
}
var exitStatus = 0
var exitMu sync.Mutex
func setExitStatus(n int) {
exitMu.Lock()
if exitStatus < n {
exitStatus = n
}
exitMu.Unlock()
}
var usageTemplate string
var helpTemplate = `{{if .Runnable}}usage: gpm {{.UsageLine}}
{{end}}{{.Long | trim}}
`
// tmpl executes the given template text on data, writing the result to w.
func tmpl(w io.Writer, text string, data interface{}) {
t := template.New("top")
t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
template.Must(t.Parse(text))
if err := t.Execute(w, data); err != nil {
panic(err)
}
}
func capitalize(s string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToTitle(r)) + s[n:]
}
func printUsage(w io.Writer) {
tmpl(w, usageTemplate, commands)
}
func usage() {
printUsage(os.Stderr)
os.Exit(2)
}
// help implements the 'help' command.
func help(args []string) {
if len(args) == 0 {
printUsage(os.Stdout)
// not exit 2: succeeded at 'gpm help'.
return
}
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "usage: gpm help command\n\nToo many arguments given.\n")
os.Exit(2) // failed at 'gpm help'
}
arg := args[0]
for _, cmd := range commands {
if cmd.Name() == arg {
tmpl(os.Stdout, helpTemplate, cmd)
// not exit 2: succeeded at 'go help cmd'.
return
}
}
fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'gpm help'.\n", arg)
os.Exit(2) // failed at 'go help cmd'
}
var atexitFuncs []func()
func atexit(f func()) {
atexitFuncs = append(atexitFuncs, f)
}
func exit() {
for _, f := range atexitFuncs {
f()
}
os.Exit(exitStatus)
}
// executeCommand executes commands in command line.
func executeCommand(cmd string, args []string) {
cmdExec := exec.Command(cmd, args...)
stdout, err := cmdExec.StdoutPipe()
if err != nil {
fmt.Println(err)
}
stderr, err := cmdExec.StderrPipe()
if err != nil {
fmt.Println(err)
}
err = cmdExec.Start()
if err != nil {
fmt.Println(err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
cmdExec.Wait()
}