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

112 lines
2.4 KiB
Go

13 years ago
package conf
import (
"io"
"os"
"bytes"
"bufio"
"strings"
)
// ReadConfigFile reads a file and returns a new configuration representation.
// This representation can be queried with GetString, etc.
func ReadConfigFile(fname string) (c *ConfigFile, err os.Error) {
13 years ago
var file *os.File
13 years ago
if file, err = os.Open(fname, os.O_RDONLY, 0); err != nil {
return nil, err
}
13 years ago
c = NewConfigFile()
13 years ago
if err = c.Read(file); err != nil {
return nil, err
}
if err = file.Close(); err != nil {
return nil, err
}
return c, nil
}
func ReadConfigBytes(conf []byte) (c *ConfigFile, err os.Error) {
buf := bytes.NewBuffer(conf)
13 years ago
c = NewConfigFile()
13 years ago
if err = c.Read(buf); err != nil {
return nil, err
}
13 years ago
13 years ago
return c, err
}
// Read reads an io.Reader and returns a configuration representation. This
// representation can be queried with GetString, etc.
func (c *ConfigFile) Read(reader io.Reader) (err os.Error) {
buf := bufio.NewReader(reader)
13 years ago
var section, option string
13 years ago
section = "default"
for {
13 years ago
l, buferr := buf.ReadString('\n') // parse line-by-line
13 years ago
l = strings.TrimSpace(l)
if buferr != nil {
if buferr != os.EOF {
return err
}
if len(l) == 0 {
break
}
13 years ago
}
13 years ago
13 years ago
// switch written for readability (not performance)
switch {
13 years ago
case len(l) == 0: // empty line
13 years ago
continue
13 years ago
case l[0] == '#': // comment
13 years ago
continue
13 years ago
case l[0] == ';': // comment
13 years ago
continue
13 years ago
case len(l) >= 3 && strings.ToLower(l[0:3]) == "rem": // comment (for windows users)
13 years ago
continue
13 years ago
case l[0] == '[' && l[len(l)-1] == ']': // new section
option = "" // reset multi-line value
section = strings.TrimSpace(l[1 : len(l)-1])
c.AddSection(section)
13 years ago
13 years ago
case section == "": // not new section and no section defined so far
13 years ago
return ReadError{BlankSection, l}
13 years ago
default: // other alternatives
i := firstIndex(l, []byte{'=', ':'})
13 years ago
switch {
13 years ago
case i > 0: // option and value
i := firstIndex(l, []byte{'=', ':'})
option = strings.TrimSpace(l[0:i])
value := strings.TrimSpace(stripComments(l[i+1:]))
c.AddOption(section, option, value)
13 years ago
13 years ago
case section != "" && option != "": // continuation of multi-line value
prev, _ := c.GetRawString(section, option)
value := strings.TrimSpace(stripComments(l))
c.AddOption(section, option, prev+"\n"+value)
13 years ago
default:
return ReadError{CouldNotParse, l}
}
}
13 years ago
13 years ago
// Reached end of file
if buferr == os.EOF {
break
}
13 years ago
}
13 years ago
return nil
13 years ago
}