conf/write.go

65 lines
1.4 KiB
Go
Raw Permalink Normal View History

2010-03-28 22:44:26 +00:00
package conf
import (
"bytes"
"io"
"os"
2010-03-28 22:44:26 +00:00
)
// 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) {
2010-04-08 17:39:05 +00:00
var file *os.File
2010-03-28 22:44:26 +00:00
if file, err = os.Create(fname); err != nil {
2010-03-28 22:44:26 +00:00
return err
}
if err = c.Write(file, header); err != nil {
return err
}
2010-04-08 17:39:05 +00:00
return file.Close()
2010-03-28 22:44:26 +00:00
}
2010-03-29 05:44:35 +00:00
// WriteConfigBytes returns the configuration file.
2010-03-28 22:44:26 +00:00
func (c *ConfigFile) WriteConfigBytes(header string) (config []byte) {
buf := bytes.NewBuffer(nil)
2010-04-08 17:39:05 +00:00
2010-03-28 22:44:26 +00:00
c.Write(buf, header)
2010-04-08 17:39:05 +00:00
2010-03-28 22:44:26 +00:00
return buf.Bytes()
}
2010-03-29 05:44:35 +00:00
// Writes the configuration file to the io.Writer.
func (c *ConfigFile) Write(writer io.Writer, header string) (err error) {
2010-03-28 22:44:26 +00:00
buf := bytes.NewBuffer(nil)
2010-04-08 17:39:05 +00:00
2010-03-28 22:44:26 +00:00
if header != "" {
if _, err = buf.WriteString("# " + header + "\n"); err != nil {
return err
}
}
for section, sectionmap := range c.data {
if section == DefaultSection && len(sectionmap) == 0 {
2010-04-08 17:39:05 +00:00
continue // skip default section if empty
2010-03-28 22:44:26 +00:00
}
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
}
}
2010-04-08 17:39:05 +00:00
2010-03-28 22:44:26 +00:00
buf.WriteTo(writer)
2010-04-08 17:39:05 +00:00
return nil
2010-03-28 22:44:26 +00:00
}