config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2013, Cong Ding. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // author: Cong Ding <dinggnu@gmail.com>
  16. //
  17. package config
  18. import (
  19. "bufio"
  20. "errors"
  21. "os"
  22. "strings"
  23. )
  24. var commentPrefix = []string{"//", "#", ";"}
  25. func Read(filename string) (map[string]string, error) {
  26. var res = map[string]string{}
  27. in, err := os.Open(filename)
  28. if err != nil {
  29. return res, err
  30. }
  31. defer in.Close()
  32. scanner := bufio.NewScanner(in)
  33. line := ""
  34. section := ""
  35. for scanner.Scan() {
  36. if scanner.Text() == "" {
  37. continue
  38. }
  39. if line == "" {
  40. sec := checkSection(scanner.Text())
  41. if sec != "" {
  42. section = sec + "."
  43. continue
  44. }
  45. }
  46. if checkComment(scanner.Text()) {
  47. continue
  48. }
  49. line += scanner.Text()
  50. if strings.HasSuffix(line, "\\") {
  51. line = line[:len(line)-1]
  52. continue
  53. }
  54. key, value, err := checkLine(line)
  55. if err != nil {
  56. return res, errors.New("WRONG: " + line)
  57. }
  58. res[section+key] = value
  59. line = ""
  60. }
  61. return res, nil
  62. }
  63. func checkSection(line string) string {
  64. line = strings.TrimSpace(line)
  65. lineLen := len(line)
  66. if lineLen < 2 {
  67. return ""
  68. }
  69. if line[0] == '[' && line[lineLen-1] == ']' {
  70. return line[1 : lineLen-1]
  71. }
  72. return ""
  73. }
  74. func checkLine(line string) (string, string, error) {
  75. key := ""
  76. value := ""
  77. sp := strings.SplitN(line, "=", 2)
  78. if len(sp) != 2 {
  79. return key, value, errors.New("WRONG: " + line)
  80. }
  81. key = strings.TrimSpace(sp[0])
  82. value = strings.TrimSpace(sp[1])
  83. return key, value, nil
  84. }
  85. func checkComment(line string) bool {
  86. line = strings.TrimSpace(line)
  87. for p := range commentPrefix {
  88. if strings.HasPrefix(line, commentPrefix[p]) {
  89. return true
  90. }
  91. }
  92. return false
  93. }