parser.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package ini
  2. import (
  3. "bufio"
  4. "io"
  5. "strings"
  6. "git.ali33.ru/fcg-xvii/go-tools/text/config"
  7. )
  8. func init() {
  9. config.RegisterParseMethod("ini", parser)
  10. }
  11. func parser(r io.Reader) (res config.Config, err error) {
  12. res = newConfig()
  13. buf := bufio.NewReader(r)
  14. var line []byte
  15. section, _ := res.Section("main")
  16. for {
  17. line, _, err = buf.ReadLine()
  18. if s := string(line); len(s) > 0 {
  19. s = strings.TrimSpace(s)
  20. switch s[0] {
  21. case '#':
  22. // comment
  23. case '[':
  24. // section
  25. if s[len(s)-1] == ']' {
  26. sectionName := s[1 : len(s)-1]
  27. if sectionName == "main" {
  28. section, _ = res.Section("main")
  29. } else {
  30. section = res.AppendSection(sectionName)
  31. }
  32. }
  33. default:
  34. // value, check comment
  35. if pos := strings.Index(s, "#"); pos > 0 {
  36. s = s[:pos]
  37. }
  38. // check plitter position
  39. if pos := strings.Index(s, "="); pos > 0 {
  40. key, val := strings.TrimSpace(s[:pos]), strings.TrimSpace(s[pos+1:])
  41. section.SetValue(key, val)
  42. }
  43. }
  44. }
  45. if err != nil {
  46. if err == io.EOF {
  47. err = nil
  48. }
  49. return
  50. }
  51. }
  52. }