read.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // Copyright 2013 Unknwon
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // 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, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package goconfig
  15. import (
  16. "bufio"
  17. "bytes"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "os"
  22. "path"
  23. "strings"
  24. "time"
  25. )
  26. // Read reads an io.Reader and returns a configuration representation.
  27. // This representation can be queried with GetValue.
  28. func (c *ConfigFile) read(reader io.Reader) (err error) {
  29. buf := bufio.NewReader(reader)
  30. // Handle BOM-UTF8.
  31. // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
  32. mask, err := buf.Peek(3)
  33. if err == nil && len(mask) >= 3 &&
  34. mask[0] == 239 && mask[1] == 187 && mask[2] == 191 {
  35. buf.Read(mask)
  36. }
  37. count := 1 // Counter for auto increment.
  38. // Current section name.
  39. section := DEFAULT_SECTION
  40. var comments string
  41. // Parse line-by-line
  42. for {
  43. line, err := buf.ReadString('\n')
  44. line = strings.TrimSpace(line)
  45. lineLengh := len(line) //[SWH|+]
  46. if err != nil {
  47. if err != io.EOF {
  48. return err
  49. }
  50. // Reached end of file, if nothing to read then break,
  51. // otherwise handle the last line.
  52. if lineLengh == 0 {
  53. break
  54. }
  55. }
  56. // switch written for readability (not performance)
  57. switch {
  58. case lineLengh == 0: // Empty line
  59. continue
  60. case line[0] == '#' || line[0] == ';': // Comment
  61. // Append comments
  62. if len(comments) == 0 {
  63. comments = line
  64. } else {
  65. comments += LineBreak + line
  66. }
  67. continue
  68. case line[0] == '[' && line[lineLengh-1] == ']': // New sction.
  69. // Get section name.
  70. section = strings.TrimSpace(line[1 : lineLengh-1])
  71. // Set section comments and empty if it has comments.
  72. if len(comments) > 0 {
  73. c.SetSectionComments(section, comments)
  74. comments = ""
  75. }
  76. // Make section exist even though it does not have any key.
  77. c.SetValue(section, " ", " ")
  78. // Reset counter.
  79. count = 1
  80. continue
  81. case section == "": // No section defined so far
  82. return readError{ERR_BLANK_SECTION_NAME, line}
  83. default: // Other alternatives
  84. var (
  85. i int
  86. keyQuote string
  87. key string
  88. valQuote string
  89. value string
  90. )
  91. //[SWH|+]:支持引号包围起来的字串
  92. if line[0] == '"' {
  93. if lineLengh >= 6 && line[0:3] == `"""` {
  94. keyQuote = `"""`
  95. } else {
  96. keyQuote = `"`
  97. }
  98. } else if line[0] == '`' {
  99. keyQuote = "`"
  100. }
  101. if keyQuote != "" {
  102. qLen := len(keyQuote)
  103. pos := strings.Index(line[qLen:], keyQuote)
  104. if pos == -1 {
  105. return readError{ERR_COULD_NOT_PARSE, line}
  106. }
  107. pos = pos + qLen
  108. i = strings.IndexAny(line[pos:], "=:")
  109. if i <= 0 {
  110. return readError{ERR_COULD_NOT_PARSE, line}
  111. }
  112. i = i + pos
  113. key = line[qLen:pos] //保留引号内的两端的空格
  114. } else {
  115. i = strings.IndexAny(line, "=:")
  116. if i <= 0 {
  117. return readError{ERR_COULD_NOT_PARSE, line}
  118. }
  119. key = strings.TrimSpace(line[0:i])
  120. }
  121. //[SWH|+];
  122. // Check if it needs auto increment.
  123. if key == "-" {
  124. key = "#" + fmt.Sprint(count)
  125. count++
  126. }
  127. //[SWH|+]:支持引号包围起来的字串
  128. lineRight := strings.TrimSpace(line[i+1:])
  129. lineRightLength := len(lineRight)
  130. firstChar := ""
  131. if lineRightLength >= 2 {
  132. firstChar = lineRight[0:1]
  133. }
  134. if firstChar == "`" {
  135. valQuote = "`"
  136. } else if lineRightLength >= 6 && lineRight[0:3] == `"""` {
  137. valQuote = `"""`
  138. }
  139. if valQuote != "" {
  140. qLen := len(valQuote)
  141. pos := strings.LastIndex(lineRight[qLen:], valQuote)
  142. if pos == -1 {
  143. return readError{ERR_COULD_NOT_PARSE, line}
  144. }
  145. pos = pos + qLen
  146. value = lineRight[qLen:pos]
  147. } else {
  148. value = strings.TrimSpace(lineRight[0:])
  149. }
  150. //[SWH|+];
  151. c.SetValue(section, key, value)
  152. // Set key comments and empty if it has comments.
  153. if len(comments) > 0 {
  154. c.SetKeyComments(section, key, comments)
  155. comments = ""
  156. }
  157. }
  158. // Reached end of file.
  159. if err == io.EOF {
  160. break
  161. }
  162. }
  163. return nil
  164. }
  165. // LoadFromData accepts raw data directly from memory
  166. // and returns a new configuration representation.
  167. // Note that the configuration is written to the system
  168. // temporary folder, so your file should not contain
  169. // sensitive information.
  170. func LoadFromData(data []byte) (c *ConfigFile, err error) {
  171. // Save memory data to temporary file to support further operations.
  172. tmpName := path.Join(os.TempDir(), "goconfig", fmt.Sprintf("%d", time.Now().Nanosecond()))
  173. if err = os.MkdirAll(path.Dir(tmpName), os.ModePerm); err != nil {
  174. return nil, err
  175. }
  176. if err = ioutil.WriteFile(tmpName, data, 0655); err != nil {
  177. return nil, err
  178. }
  179. c = newConfigFile([]string{tmpName})
  180. err = c.read(bytes.NewBuffer(data))
  181. return c, err
  182. }
  183. // LoadFromReader accepts raw data directly from a reader
  184. // and returns a new configuration representation.
  185. // You must use ReloadData to reload.
  186. // You cannot append files a configfile read this way.
  187. func LoadFromReader(in io.Reader) (c *ConfigFile, err error) {
  188. c = newConfigFile([]string{""})
  189. err = c.read(in)
  190. return c, err
  191. }
  192. func (c *ConfigFile) loadFile(fileName string) (err error) {
  193. f, err := os.Open(fileName)
  194. if err != nil {
  195. return err
  196. }
  197. defer f.Close()
  198. return c.read(f)
  199. }
  200. // LoadConfigFile reads a file and returns a new configuration representation.
  201. // This representation can be queried with GetValue.
  202. func LoadConfigFile(fileName string, moreFiles ...string) (c *ConfigFile, err error) {
  203. // Append files' name together.
  204. fileNames := make([]string, 1, len(moreFiles)+1)
  205. fileNames[0] = fileName
  206. if len(moreFiles) > 0 {
  207. fileNames = append(fileNames, moreFiles...)
  208. }
  209. c = newConfigFile(fileNames)
  210. for _, name := range fileNames {
  211. if err = c.loadFile(name); err != nil {
  212. return nil, err
  213. }
  214. }
  215. return c, nil
  216. }
  217. // Reload reloads configuration file in case it has changes.
  218. func (c *ConfigFile) Reload() (err error) {
  219. var cfg *ConfigFile
  220. if len(c.fileNames) == 1 {
  221. if c.fileNames[0] == "" {
  222. return fmt.Errorf("file opened from in-memory data, use ReloadData to reload")
  223. }
  224. cfg, err = LoadConfigFile(c.fileNames[0])
  225. } else {
  226. cfg, err = LoadConfigFile(c.fileNames[0], c.fileNames[1:]...)
  227. }
  228. if err == nil {
  229. *c = *cfg
  230. }
  231. return err
  232. }
  233. // ReloadData reloads configuration file from memory
  234. func (c *ConfigFile) ReloadData(in io.Reader) (err error) {
  235. var cfg *ConfigFile
  236. if len(c.fileNames) != 1 {
  237. return fmt.Errorf("Multiple files loaded, unable to mix in-memory and file data")
  238. }
  239. cfg, err = LoadFromReader(in)
  240. if err == nil {
  241. *c = *cfg
  242. }
  243. return err
  244. }
  245. // AppendFiles appends more files to ConfigFile and reload automatically.
  246. func (c *ConfigFile) AppendFiles(files ...string) error {
  247. if len(c.fileNames) == 1 && c.fileNames[0] == "" {
  248. return fmt.Errorf("Cannot append file data to in-memory data")
  249. }
  250. c.fileNames = append(c.fileNames, files...)
  251. return c.Reload()
  252. }
  253. // readError occurs when read configuration file with wrong format.
  254. type readError struct {
  255. Reason ParseError
  256. Content string // Line content
  257. }
  258. // Error implement Error interface.
  259. func (err readError) Error() string {
  260. switch err.Reason {
  261. case ERR_BLANK_SECTION_NAME:
  262. return "empty section name not allowed"
  263. case ERR_COULD_NOT_PARSE:
  264. return fmt.Sprintf("could not parse line: %s", string(err.Content))
  265. }
  266. return "invalid read error"
  267. }