parser.go 13 KB

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