parser.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2015 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 ini
  15. import (
  16. "bufio"
  17. "bytes"
  18. "fmt"
  19. "io"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "unicode"
  24. )
  25. const minReaderBufferSize = 4096
  26. var pythonMultiline = regexp.MustCompile(`^([\t\f ]+)(.*)`)
  27. type parserOptions struct {
  28. IgnoreContinuation bool
  29. IgnoreInlineComment bool
  30. AllowPythonMultilineValues bool
  31. SpaceBeforeInlineComment bool
  32. UnescapeValueDoubleQuotes bool
  33. UnescapeValueCommentSymbols bool
  34. PreserveSurroundedQuote bool
  35. DebugFunc DebugFunc
  36. ReaderBufferSize int
  37. }
  38. type parser struct {
  39. buf *bufio.Reader
  40. options parserOptions
  41. isEOF bool
  42. count int
  43. comment *bytes.Buffer
  44. }
  45. func (p *parser) debug(format string, args ...interface{}) {
  46. if p.options.DebugFunc != nil {
  47. p.options.DebugFunc(fmt.Sprintf(format, args...))
  48. }
  49. }
  50. func newParser(r io.Reader, opts parserOptions) *parser {
  51. size := opts.ReaderBufferSize
  52. if size < minReaderBufferSize {
  53. size = minReaderBufferSize
  54. }
  55. return &parser{
  56. buf: bufio.NewReaderSize(r, size),
  57. options: opts,
  58. count: 1,
  59. comment: &bytes.Buffer{},
  60. }
  61. }
  62. // BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format.
  63. // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
  64. func (p *parser) BOM() error {
  65. mask, err := p.buf.Peek(2)
  66. if err != nil && err != io.EOF {
  67. return err
  68. } else if len(mask) < 2 {
  69. return nil
  70. }
  71. switch {
  72. case mask[0] == 254 && mask[1] == 255:
  73. fallthrough
  74. case mask[0] == 255 && mask[1] == 254:
  75. p.buf.Read(mask)
  76. case mask[0] == 239 && mask[1] == 187:
  77. mask, err := p.buf.Peek(3)
  78. if err != nil && err != io.EOF {
  79. return err
  80. } else if len(mask) < 3 {
  81. return nil
  82. }
  83. if mask[2] == 191 {
  84. p.buf.Read(mask)
  85. }
  86. }
  87. return nil
  88. }
  89. func (p *parser) readUntil(delim byte) ([]byte, error) {
  90. data, err := p.buf.ReadBytes(delim)
  91. if err != nil {
  92. if err == io.EOF {
  93. p.isEOF = true
  94. } else {
  95. return nil, err
  96. }
  97. }
  98. return data, nil
  99. }
  100. func cleanComment(in []byte) ([]byte, bool) {
  101. i := bytes.IndexAny(in, "#;")
  102. if i == -1 {
  103. return nil, false
  104. }
  105. return in[i:], true
  106. }
  107. func readKeyName(delimiters string, in []byte) (string, int, error) {
  108. line := string(in)
  109. // Check if key name surrounded by quotes.
  110. var keyQuote string
  111. if line[0] == '"' {
  112. if len(line) > 6 && string(line[0:3]) == `"""` {
  113. keyQuote = `"""`
  114. } else {
  115. keyQuote = `"`
  116. }
  117. } else if line[0] == '`' {
  118. keyQuote = "`"
  119. }
  120. // Get out key name
  121. endIdx := -1
  122. if len(keyQuote) > 0 {
  123. startIdx := len(keyQuote)
  124. // FIXME: fail case -> """"""name"""=value
  125. pos := strings.Index(line[startIdx:], keyQuote)
  126. if pos == -1 {
  127. return "", -1, fmt.Errorf("missing closing key quote: %s", line)
  128. }
  129. pos += startIdx
  130. // Find key-value delimiter
  131. i := strings.IndexAny(line[pos+startIdx:], delimiters)
  132. if i < 0 {
  133. return "", -1, ErrDelimiterNotFound{line}
  134. }
  135. endIdx = pos + i
  136. return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil
  137. }
  138. endIdx = strings.IndexAny(line, delimiters)
  139. if endIdx < 0 {
  140. return "", -1, ErrDelimiterNotFound{line}
  141. }
  142. return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
  143. }
  144. func (p *parser) readMultilines(line, val, valQuote string) (string, error) {
  145. for {
  146. data, err := p.readUntil('\n')
  147. if err != nil {
  148. return "", err
  149. }
  150. next := string(data)
  151. pos := strings.LastIndex(next, valQuote)
  152. if pos > -1 {
  153. val += next[:pos]
  154. comment, has := cleanComment([]byte(next[pos:]))
  155. if has {
  156. p.comment.Write(bytes.TrimSpace(comment))
  157. }
  158. break
  159. }
  160. val += next
  161. if p.isEOF {
  162. return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next)
  163. }
  164. }
  165. return val, nil
  166. }
  167. func (p *parser) readContinuationLines(val string) (string, error) {
  168. for {
  169. data, err := p.readUntil('\n')
  170. if err != nil {
  171. return "", err
  172. }
  173. next := strings.TrimSpace(string(data))
  174. if len(next) == 0 {
  175. break
  176. }
  177. val += next
  178. if val[len(val)-1] != '\\' {
  179. break
  180. }
  181. val = val[:len(val)-1]
  182. }
  183. return val, nil
  184. }
  185. // hasSurroundedQuote check if and only if the first and last characters
  186. // are quotes \" or \'.
  187. // It returns false if any other parts also contain same kind of quotes.
  188. func hasSurroundedQuote(in string, quote byte) bool {
  189. return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote &&
  190. strings.IndexByte(in[1:], quote) == len(in)-2
  191. }
  192. func (p *parser) readValue(in []byte, bufferSize int) (string, error) {
  193. line := strings.TrimLeftFunc(string(in), unicode.IsSpace)
  194. if len(line) == 0 {
  195. if p.options.AllowPythonMultilineValues && len(in) > 0 && in[len(in)-1] == '\n' {
  196. return p.readPythonMultilines(line, bufferSize)
  197. }
  198. return "", nil
  199. }
  200. var valQuote string
  201. if len(line) > 3 && string(line[0:3]) == `"""` {
  202. valQuote = `"""`
  203. } else if line[0] == '`' {
  204. valQuote = "`"
  205. } else if p.options.UnescapeValueDoubleQuotes && line[0] == '"' {
  206. valQuote = `"`
  207. }
  208. if len(valQuote) > 0 {
  209. startIdx := len(valQuote)
  210. pos := strings.LastIndex(line[startIdx:], valQuote)
  211. // Check for multi-line value
  212. if pos == -1 {
  213. return p.readMultilines(line, line[startIdx:], valQuote)
  214. }
  215. if p.options.UnescapeValueDoubleQuotes && valQuote == `"` {
  216. return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil
  217. }
  218. return line[startIdx : pos+startIdx], nil
  219. }
  220. lastChar := line[len(line)-1]
  221. // Won't be able to reach here if value only contains whitespace
  222. line = strings.TrimSpace(line)
  223. trimmedLastChar := line[len(line)-1]
  224. // Check continuation lines when desired
  225. if !p.options.IgnoreContinuation && trimmedLastChar == '\\' {
  226. return p.readContinuationLines(line[:len(line)-1])
  227. }
  228. // Check if ignore inline comment
  229. if !p.options.IgnoreInlineComment {
  230. var i int
  231. if p.options.SpaceBeforeInlineComment {
  232. i = strings.Index(line, " #")
  233. if i == -1 {
  234. i = strings.Index(line, " ;")
  235. }
  236. } else {
  237. i = strings.IndexAny(line, "#;")
  238. }
  239. if i > -1 {
  240. p.comment.WriteString(line[i:])
  241. line = strings.TrimSpace(line[:i])
  242. }
  243. }
  244. // Trim single and double quotes
  245. if (hasSurroundedQuote(line, '\'') ||
  246. hasSurroundedQuote(line, '"')) && !p.options.PreserveSurroundedQuote {
  247. line = line[1 : len(line)-1]
  248. } else if len(valQuote) == 0 && p.options.UnescapeValueCommentSymbols {
  249. if strings.Contains(line, `\;`) {
  250. line = strings.Replace(line, `\;`, ";", -1)
  251. }
  252. if strings.Contains(line, `\#`) {
  253. line = strings.Replace(line, `\#`, "#", -1)
  254. }
  255. } else if p.options.AllowPythonMultilineValues && lastChar == '\n' {
  256. return p.readPythonMultilines(line, bufferSize)
  257. }
  258. return line, nil
  259. }
  260. func (p *parser) readPythonMultilines(line string, bufferSize int) (string, error) {
  261. parserBufferPeekResult, _ := p.buf.Peek(bufferSize)
  262. peekBuffer := bytes.NewBuffer(parserBufferPeekResult)
  263. indentSize := 0
  264. for {
  265. peekData, peekErr := peekBuffer.ReadBytes('\n')
  266. if peekErr != nil {
  267. if peekErr == io.EOF {
  268. p.debug("readPythonMultilines: io.EOF, peekData: %q, line: %q", string(peekData), line)
  269. return line, nil
  270. }
  271. p.debug("readPythonMultilines: failed to peek with error: %v", peekErr)
  272. return "", peekErr
  273. }
  274. p.debug("readPythonMultilines: parsing %q", string(peekData))
  275. peekMatches := pythonMultiline.FindStringSubmatch(string(peekData))
  276. p.debug("readPythonMultilines: matched %d parts", len(peekMatches))
  277. for n, v := range peekMatches {
  278. p.debug(" %d: %q", n, v)
  279. }
  280. // Return if not a Python multiline value.
  281. if len(peekMatches) != 3 {
  282. p.debug("readPythonMultilines: end of value, got: %q", line)
  283. return line, nil
  284. }
  285. // Determine indent size and line prefix.
  286. currentIndentSize := len(peekMatches[1])
  287. if indentSize < 1 {
  288. indentSize = currentIndentSize
  289. p.debug("readPythonMultilines: indent size is %d", indentSize)
  290. }
  291. // Make sure each line is indented at least as far as first line.
  292. if currentIndentSize < indentSize {
  293. p.debug("readPythonMultilines: end of value, current indent: %d, expected indent: %d, line: %q", currentIndentSize, indentSize, line)
  294. return line, nil
  295. }
  296. // Advance the parser reader (buffer) in-sync with the peek buffer.
  297. _, err := p.buf.Discard(len(peekData))
  298. if err != nil {
  299. p.debug("readPythonMultilines: failed to skip to the end, returning error")
  300. return "", err
  301. }
  302. // Handle indented empty line.
  303. line += "\n" + peekMatches[1][indentSize:] + peekMatches[2]
  304. }
  305. }
  306. // parse parses data through an io.Reader.
  307. func (f *File) parse(reader io.Reader) (err error) {
  308. p := newParser(reader, parserOptions{
  309. IgnoreContinuation: f.options.IgnoreContinuation,
  310. IgnoreInlineComment: f.options.IgnoreInlineComment,
  311. AllowPythonMultilineValues: f.options.AllowPythonMultilineValues,
  312. SpaceBeforeInlineComment: f.options.SpaceBeforeInlineComment,
  313. UnescapeValueDoubleQuotes: f.options.UnescapeValueDoubleQuotes,
  314. UnescapeValueCommentSymbols: f.options.UnescapeValueCommentSymbols,
  315. PreserveSurroundedQuote: f.options.PreserveSurroundedQuote,
  316. DebugFunc: f.options.DebugFunc,
  317. ReaderBufferSize: f.options.ReaderBufferSize,
  318. })
  319. if err = p.BOM(); err != nil {
  320. return fmt.Errorf("BOM: %v", err)
  321. }
  322. // Ignore error because default section name is never empty string.
  323. name := DefaultSection
  324. if f.options.Insensitive {
  325. name = strings.ToLower(DefaultSection)
  326. }
  327. section, _ := f.NewSection(name)
  328. // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key
  329. var isLastValueEmpty bool
  330. var lastRegularKey *Key
  331. var line []byte
  332. var inUnparseableSection bool
  333. // NOTE: Iterate and increase `currentPeekSize` until
  334. // the size of the parser buffer is found.
  335. // TODO(unknwon): When Golang 1.10 is the lowest version supported, replace with `parserBufferSize := p.buf.Size()`.
  336. parserBufferSize := 0
  337. // NOTE: Peek 4kb at a time.
  338. currentPeekSize := minReaderBufferSize
  339. if f.options.AllowPythonMultilineValues {
  340. for {
  341. peekBytes, _ := p.buf.Peek(currentPeekSize)
  342. peekBytesLength := len(peekBytes)
  343. if parserBufferSize >= peekBytesLength {
  344. break
  345. }
  346. currentPeekSize *= 2
  347. parserBufferSize = peekBytesLength
  348. }
  349. }
  350. for !p.isEOF {
  351. line, err = p.readUntil('\n')
  352. if err != nil {
  353. return err
  354. }
  355. if f.options.AllowNestedValues &&
  356. isLastValueEmpty && len(line) > 0 {
  357. if line[0] == ' ' || line[0] == '\t' {
  358. lastRegularKey.addNestedValue(string(bytes.TrimSpace(line)))
  359. continue
  360. }
  361. }
  362. line = bytes.TrimLeftFunc(line, unicode.IsSpace)
  363. if len(line) == 0 {
  364. continue
  365. }
  366. // Comments
  367. if line[0] == '#' || line[0] == ';' {
  368. // Note: we do not care ending line break,
  369. // it is needed for adding second line,
  370. // so just clean it once at the end when set to value.
  371. p.comment.Write(line)
  372. continue
  373. }
  374. // Section
  375. if line[0] == '[' {
  376. // Read to the next ']' (TODO: support quoted strings)
  377. closeIdx := bytes.LastIndexByte(line, ']')
  378. if closeIdx == -1 {
  379. return fmt.Errorf("unclosed section: %s", line)
  380. }
  381. name := string(line[1:closeIdx])
  382. section, err = f.NewSection(name)
  383. if err != nil {
  384. return err
  385. }
  386. comment, has := cleanComment(line[closeIdx+1:])
  387. if has {
  388. p.comment.Write(comment)
  389. }
  390. section.Comment = strings.TrimSpace(p.comment.String())
  391. // Reset aotu-counter and comments
  392. p.comment.Reset()
  393. p.count = 1
  394. inUnparseableSection = false
  395. for i := range f.options.UnparseableSections {
  396. if f.options.UnparseableSections[i] == name ||
  397. (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) {
  398. inUnparseableSection = true
  399. continue
  400. }
  401. }
  402. continue
  403. }
  404. if inUnparseableSection {
  405. section.isRawSection = true
  406. section.rawBody += string(line)
  407. continue
  408. }
  409. kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line)
  410. if err != nil {
  411. // Treat as boolean key when desired, and whole line is key name.
  412. if IsErrDelimiterNotFound(err) {
  413. switch {
  414. case f.options.AllowBooleanKeys:
  415. kname, err := p.readValue(line, parserBufferSize)
  416. if err != nil {
  417. return err
  418. }
  419. key, err := section.NewBooleanKey(kname)
  420. if err != nil {
  421. return err
  422. }
  423. key.Comment = strings.TrimSpace(p.comment.String())
  424. p.comment.Reset()
  425. continue
  426. case f.options.SkipUnrecognizableLines:
  427. continue
  428. }
  429. }
  430. return err
  431. }
  432. // Auto increment.
  433. isAutoIncr := false
  434. if kname == "-" {
  435. isAutoIncr = true
  436. kname = "#" + strconv.Itoa(p.count)
  437. p.count++
  438. }
  439. value, err := p.readValue(line[offset:], parserBufferSize)
  440. if err != nil {
  441. return err
  442. }
  443. isLastValueEmpty = len(value) == 0
  444. key, err := section.NewKey(kname, value)
  445. if err != nil {
  446. return err
  447. }
  448. key.isAutoIncrement = isAutoIncr
  449. key.Comment = strings.TrimSpace(p.comment.String())
  450. p.comment.Reset()
  451. lastRegularKey = key
  452. }
  453. return nil
  454. }