-
Notifications
You must be signed in to change notification settings - Fork 106
/
utils.go
87 lines (78 loc) · 1.63 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package sda
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"gopkg.in/dedis/cothority.v0/lib/dbg"
)
/*
* Writes 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 {
dbg.Fatal(err)
}
err := ioutil.WriteFile(getFullName(filename, dirOpt...), buf.Bytes(), 0660)
if err != nil {
dbg.Fatal(err)
}
}
/*
* Reads 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()
dbg.Lvl1("Didn't find", filename, "in", pwd)
return err
}
_, err = toml.Decode(string(buf), conf)
if err != nil {
dbg.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)
}
type collectedErrors struct {
s string
e error
}
func collectErrors(format string, m []collectedErrors) error {
var errStr string
for _, e := range m {
errStr += fmt.Sprintf(format, e.s, e.e)
}
if errStr == "" {
return nil
}
return errors.New(errStr)
}