-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathcommon.go
More file actions
103 lines (85 loc) · 1.89 KB
/
common.go
File metadata and controls
103 lines (85 loc) · 1.89 KB
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
/*
* Xenon
*
* Copyright 2018 The Xenon Authors.
* Code is licensed under the GPLv3.
*
*/
package cmd
import (
"bytes"
"config"
"fmt"
"io/ioutil"
"model"
"os"
"path/filepath"
"runtime"
"strings"
"xbase/xlog"
"github.com/spf13/cobra"
)
var (
configPathFile = "config.path"
log = xlog.NewStdLog(xlog.Level(xlog.INFO))
)
func ErrorOK(err error) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
log.Panic("%v", err)
}
}
func RspOK(ret string) {
if ret != model.OK {
log.Panic("rsp[%v] != [OK]", ret)
}
}
func GetConfig() (*config.Config, error) {
fullPath := configPathFile
// try to search in current dir
// and try to in Abs dir if failed
if _, err := os.Stat(fullPath); err != nil {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return nil, err
}
fullPath = fmt.Sprintf("%s/%s", dir, configPathFile)
}
data, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, err
}
conf, err := config.LoadConfig(strings.TrimSpace(string(data)))
if err != nil {
return nil, err
}
return conf, nil
}
func SaveConfig(conf *config.Config) error {
fullPath := configPathFile
// try to search in current dir
// and try to in Abs dir if failed
if _, err := os.Stat(fullPath); err != nil {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
fullPath = fmt.Sprintf("%s/%s", dir, configPathFile)
}
data, err := ioutil.ReadFile(fullPath)
if err != nil {
return err
}
if err := config.WriteConfig(strings.TrimSpace(string(data)), conf); err != nil {
return err
}
return nil
}
func executeCommand(root *cobra.Command, args ...string) (output string, err error) {
buf := new(bytes.Buffer)
root.SetOutput(buf)
root.SetArgs(args)
_, err = root.ExecuteC()
return buf.String(), err
}