You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.4 KiB

12 years ago
package conf
import (
"bytes"
"io"
"os"
12 years ago
)
// WriteConfigFile 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 *ConfigFile) WriteConfigFile(fname string, perm uint32, header string) (err error) {
12 years ago
var file *os.File
12 years ago
if file, err = os.Create(fname); err != nil {
12 years ago
return err
}
if err = c.Write(file, header); err != nil {
return err
}
12 years ago
return file.Close()
12 years ago
}
12 years ago
// WriteConfigBytes returns the configuration file.
12 years ago
func (c *ConfigFile) WriteConfigBytes(header string) (config []byte) {
buf := bytes.NewBuffer(nil)
12 years ago
12 years ago
c.Write(buf, header)
12 years ago
12 years ago
return buf.Bytes()
}
12 years ago
// Writes the configuration file to the io.Writer.
func (c *ConfigFile) Write(writer io.Writer, header string) (err error) {
12 years ago
buf := bytes.NewBuffer(nil)
12 years ago
12 years ago
if header != "" {
if _, err = buf.WriteString("# " + header + "\n"); err != nil {
return err
}
}
for section, sectionmap := range c.data {
if section == DefaultSection && len(sectionmap) == 0 {
12 years ago
continue // skip default section if empty
12 years ago
}
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
}
}
12 years ago
12 years ago
buf.WriteTo(writer)
12 years ago
return nil
12 years ago
}