Repository navigation
Expand file tree
/
Copy pathfile.go
More file actions
112 lines (99 loc) · 1.88 KB
/
Copy pathfile.go
File metadata and controls
112 lines (99 loc) · 1.88 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
B176
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
package env
import (
"bytes"
"go.etcd.io/etcd/client/pkg/v3/fileutil"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/eolinker/eosc"
"github.com/eolinker/eosc/log"
)
type Config struct {
path string
args eosc.IUntyped
}
func NewConfig(path string) *Config {
return &Config{path: path, args: eosc.NewUntyped()}
}
func (c *Config) ReadFile(paths ...string) {
for _, path := range paths {
// 参数配置文件格式:分行获取
fileutil.CreateDirAll(filepath.Dir(path))
data, err := ioutil.ReadFile(path)
if err != nil {
continue
}
buf := bytes.NewBuffer(data)
for {
line, err := buf.ReadString('\n')
if err != nil && err != io.EOF {
break
}
line = strings.TrimSpace(line)
if len(line) > 0 {
index := strings.Index(line, "=")
if index == -1 {
continue
}
c.Set(line[:index], line[index+1:])
}
if err != nil {
return
}
}
}
}
func (c *Config) Set(name string, value string) {
if name != "" {
c.args.Set(name, value)
}
}
func (c *Config) Get(name string) (string, bool) {
vl, has := c.args.Get(name)
if !has {
return "", false
}
v, ok := vl.(string)
if !ok {
return "", false
}
return v, true
}
func (c *Config) GetDefault(name string, value string) string {
vl, has := c.args.Get(name)
if !has {
return value
}
v, ok := vl.(string)
if !ok {
return value
}
return v
}
func (c *Config) Save() error {
builder := strings.Builder{}
for key, value := range c.args.All() {
v, ok := value.(string)
if !ok {
continue
}
builder.WriteString(key)
builder.WriteString("=")
builder.WriteString(v)
builder.WriteString("\n")
}
f, err := os.OpenFile(c.path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f.Close()
// offset
_, err = f.Write([]byte(builder.String()))
if err != nil {
return err
}
log.Info("write args file succeed!")
return nil
}