First import
This commit is contained in:
commit
c49f1b4ed9
6 changed files with 590 additions and 0 deletions
62
write.go
Normal file
62
write.go
Normal file
|
@ -0,0 +1,62 @@
|
|||
package conf
|
||||
|
||||
import (
|
||||
"os"
|
||||
"io"
|
||||
"bytes"
|
||||
)
|
||||
|
||||
// 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 int, header string) (err os.Error) {
|
||||
var file *os.File;
|
||||
|
||||
if file, err = os.Open(fname, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = c.Write(file, header); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return file.Close();
|
||||
}
|
||||
|
||||
func (c *ConfigFile) WriteConfigBytes(header string) (config []byte) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
|
||||
c.Write(buf, header)
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func (c *ConfigFile) Write(writer io.Writer, header string) (err os.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;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue