forked from zieckey/goini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinherited_ini.go
81 lines (71 loc) · 1.86 KB
/
inherited_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
package goini
import (
"path/filepath"
"errors"
"log"
)
// Suppress error if they are not otherwise used.
var _ = log.Printf
const (
InheritedFrom = "inherited_from" // The key of the INI path which will be inherited from
)
// LoadInheritedINI loads an INI file which inherits from another INI
// e.g:
// The common.ini has contents:
// project=common
// ip=192.168.0.1
//
// And the project.ini has contents:
// project=ppp
// combo=ppp
// inherited_from=common.ini
//
// The project.ini has the same configure as below :
// project=ppp
// combo=ppp
// ip=192.168.0.1
//
func LoadInheritedINI(filename string) (*INI, error) {
ini := New()
err := ini.ParseFile(filename)
if err != nil {
return nil, err
}
inherited, ok := ini.Get(InheritedFrom)
if !ok {
return ini, nil
}
inherited = GetPathByRelativePath(filename, inherited)
inheritedINI, err := LoadInheritedINI(inherited)
if err != nil {
return nil, errors.New(err.Error() + " " + inherited)
}
ini.Merge(inheritedINI, false)
return ini, nil
}
// Merge merges the data in another INI (from) to this INI (ini), and
// from INI will not be changed
func (ini *INI) Merge(from *INI, override bool) {
for section, kv := range from.sections {
for key, value := range kv {
_, found := ini.SectionGet(section, key)
if override || !found {
ini.SectionSet(section, key, value)
}
}
}
}
// GetPathByRelativePath gets the real path according to the relative file path
// e.g. :
// relativeFilePath = /home/goini/conf/common.conf
// inheritedPath = app.conf
//
// and then the GetPathByRelativePath(relativeFilePath, inheritedPath) will
// return /home/goini/conf/app.conf
func GetPathByRelativePath(relativeFilePath, inheritedPath string) string {
if filepath.IsAbs(inheritedPath) {
return inheritedPath
}
dir, _ := filepath.Split(relativeFilePath)
return filepath.Join(dir, inheritedPath)
}