forked from dedis/onet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
63 lines (56 loc) · 1.35 KB
/
utils.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
package onet
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/dedis/onet/log"
)
// WriteTomlConfig write any structure to a toml-file
// Takes a filename and an optional directory-name.
func WriteTomlConfig(conf interface{}, filename string, dirOpt ...string) {
buf := new(bytes.Buffer)
if err := toml.NewEncoder(buf).Encode(conf); err != nil {
log.Fatal(err)
}
err := ioutil.WriteFile(getFullName(filename, dirOpt...), buf.Bytes(), 0660)
if err != nil {
log.Fatal(err)
}
}
// ReadTomlConfig read any structure from a toml-file
// Takes a filename and an optional directory-name
func ReadTomlConfig(conf interface{}, filename string, dirOpt ...string) error {
buf, err := ioutil.ReadFile(getFullName(filename, dirOpt...))
if err != nil {
pwd, _ := os.Getwd()
log.Lvl1("Didn't find", filename, "in", pwd)
return err
}
_, err = toml.Decode(string(buf), conf)
if err != nil {
log.Fatal(err)
}
return nil
}
/*
* Gets filename and dirname
*
* special cases:
* - filename only
* - filename in relative path
* - filename in absolute path
* - filename and additional path
*/
func getFullName(filename string, dirOpt ...string) string {
dir := filepath.Dir(filename)
if len(dirOpt) > 0 {
dir = dirOpt[0]
} else {
if dir == "" {
dir = "."
}
}
return dir + "/" + filepath.Base(filename)
}