-
Notifications
You must be signed in to change notification settings - Fork 7
/
ini.go
116 lines (105 loc) · 2.48 KB
/
ini.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
package main
import (
"fmt"
"os"
"github.com/go-ini/ini"
)
func init() {
// Maintain the original file format
ini.PrettyFormat = false
}
func loadOptions() ini.LoadOptions {
return ini.LoadOptions{
// Support mysql-style "boolean" values - a key wth no value.
AllowBooleanKeys: true,
// Support preserving arrays in original document
AllowShadows: true,
IgnoreInlineComment: globalOpts.IgnoreInlineComments,
}
}
// iniLoad attempts to load the ini file.
func iniLoad(filename string) (*ini.File, error) {
return ini.LoadSources(
loadOptions(),
filename,
)
}
// iniLoadOrEmpty attempts to load the ini file. If it does not exists,
// it will return an empty one
func iniLoadOrEmpty(filename string) (*ini.File, error) {
f, err := iniLoad(filename)
if err == nil {
return f, nil
}
if os.IsNotExist(err) {
return ini.Empty(loadOptions()), nil
}
return nil, err
}
// iniSave writes the ini file to the named file.
func iniSave(filename string, iniFile *ini.File) error {
// The third argument, perm, is ignored when the file doesn't exist
// So we can safely set it to '0644', it won't modify the existing permissions
// if the file exists.
f, err := os.OpenFile(filename, os.O_SYNC|os.O_RDWR|os.O_CREATE, os.FileMode(0644))
if err != nil {
return err
}
// Clear file content
err = f.Truncate(0)
if err != nil {
return err
}
_, err = iniFile.WriteTo(f)
if err != nil {
return err
}
return f.Close()
}
func iniFileGet(file string, s string, key string) (string, error) {
iniFile, err := iniLoad(file)
if err != nil {
return "", err
}
section := iniFile.Section(s)
if !section.HasKey(key) {
return "", nil
}
k, err := section.GetKey(key)
if err != nil {
return "", err
}
return k.String(), nil
}
func iniFileSet(file string, s string, key string, value interface{}) error {
iniFile, err := iniLoadOrEmpty(file)
if err != nil {
return err
}
section := iniFile.Section(s)
switch v := value.(type) {
case string:
if section.HasKey(key) && len(section.Key(key).ValueWithShadows()) == 1 {
section.Key(key).SetValue(v)
} else {
section.NewKey(key, v)
}
case bool:
section.NewBooleanKey(key)
default:
return fmt.Errorf("invalid key type %T", v)
}
return iniSave(file, iniFile)
}
func iniFileDel(file string, s string, key string) error {
iniFile, err := iniLoad(file)
if err != nil {
return err
}
section := iniFile.Section(s)
if !section.HasKey(key) {
return nil
}
section.DeleteKey(key)
return iniSave(file, iniFile)
}