-
Notifications
You must be signed in to change notification settings - Fork 1
/
write.go
67 lines (54 loc) · 1.5 KB
/
write.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
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package conf
import (
"bytes"
"io"
"os"
)
// WriteFile saves the configuration representation to a file.
// The desired file permissions must be passed as in os.Open.
// The header is a string that is saved as a comment in the first line of the file.
func (c *Config) WriteFile(fname string, perm uint32, header string) (err error) {
var file *os.File
if file, err = os.Create(fname); err != nil {
return err
}
if err = c.Write(file, header); err != nil {
return err
}
return file.Close()
}
// WriteBytes returns the configuration file.
func (c *Config) WriteBytes(header string) (config []byte) {
buf := bytes.NewBuffer(nil)
c.Write(buf, header)
return buf.Bytes()
}
// Writes the configuration file to the io.Writer.
func (c *Config) Write(writer io.Writer, header string) (err error) {
buf := bytes.NewBuffer(nil)
if header != "" {
if _, err = buf.WriteString("# " + header + "\n"); err != nil {
return err
}
}
for section, sectionmap := range c.data {
if section == DefaultSection && len(sectionmap) == 0 {
continue // skip default section if empty
}
if _, err = buf.WriteString("[" + section + "]\n"); err != nil {
return err
}
for option, value := range sectionmap {
if _, err = buf.WriteString(option + "=" + value + "\n"); err != nil {
return err
}
}
if _, err = buf.WriteString("\n"); err != nil {
return err
}
}
buf.WriteTo(writer)
return nil
}