parser.go 13 KB

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