ini.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // +build go1.6
  2. // Copyright 2014 Unknwon
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. // Package ini provides INI file read and write functionality in Go.
  16. package ini
  17. import (
  18. "os"
  19. "regexp"
  20. "runtime"
  21. "strings"
  22. )
  23. const (
  24. // DefaultSection is the name of default section. You can use this constant or the string literal.
  25. // In most of cases, an empty string is all you need to access the section.
  26. DefaultSection = "DEFAULT"
  27. // Maximum allowed depth when recursively substituing variable names.
  28. depthValues = 99
  29. )
  30. var (
  31. // LineBreak is the delimiter to determine or compose a new line.
  32. // This variable will be changed to "\r\n" automatically on Windows at package init time.
  33. LineBreak = "\n"
  34. // Variable regexp pattern: %(variable)s
  35. varPattern = regexp.MustCompile(`%\(([^)]+)\)s`)
  36. // DefaultHeader explicitly writes default section header.
  37. DefaultHeader = false
  38. // PrettySection indicates whether to put a line between sections.
  39. PrettySection = true
  40. // PrettyFormat indicates whether to align "=" sign with spaces to produce pretty output
  41. // or reduce all possible spaces for compact format.
  42. PrettyFormat = true
  43. // PrettyEqual places spaces around "=" sign even when PrettyFormat is false.
  44. PrettyEqual = false
  45. // DefaultFormatLeft places custom spaces on the left when PrettyFormat and PrettyEqual are both disabled.
  46. DefaultFormatLeft = ""
  47. // DefaultFormatRight places custom spaces on the right when PrettyFormat and PrettyEqual are both disabled.
  48. DefaultFormatRight = ""
  49. )
  50. var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
  51. func init() {
  52. if runtime.GOOS == "windows" && !inTest {
  53. LineBreak = "\r\n"
  54. }
  55. }
  56. // LoadOptions contains all customized options used for load data source(s).
  57. type LoadOptions struct {
  58. // Loose indicates whether the parser should ignore nonexistent files or return error.
  59. Loose bool
  60. // Insensitive indicates whether the parser forces all section and key names to lowercase.
  61. Insensitive bool
  62. // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
  63. IgnoreContinuation bool
  64. // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
  65. IgnoreInlineComment bool
  66. // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
  67. SkipUnrecognizableLines bool
  68. // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
  69. // This type of keys are mostly used in my.cnf.
  70. AllowBooleanKeys bool
  71. // AllowShadows indicates whether to keep track of keys with same name under same section.
  72. AllowShadows bool
  73. // AllowNestedValues indicates whether to allow AWS-like nested values.
  74. // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
  75. AllowNestedValues bool
  76. // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
  77. // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
  78. // Relevant quote: Values can also span multiple lines, as long as they are indented deeper
  79. // than the first line of the value.
  80. AllowPythonMultilineValues bool
  81. // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
  82. // Docs: https://docs.python.org/2/library/configparser.html
  83. // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
  84. // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
  85. SpaceBeforeInlineComment bool
  86. // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
  87. // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
  88. UnescapeValueDoubleQuotes bool
  89. // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
  90. // when value is NOT surrounded by any quotes.
  91. // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
  92. UnescapeValueCommentSymbols bool
  93. // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
  94. // conform to key/value pairs. Specify the names of those blocks here.
  95. UnparseableSections []string
  96. // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
  97. KeyValueDelimiters string
  98. // KeyValueDelimiters is the delimiter that are used to separate key and value output. By default, it is "=".
  99. KeyValueDelimiterOnWrite string
  100. // PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
  101. PreserveSurroundedQuote bool
  102. // DebugFunc is called to collect debug information (currently only useful to debug parsing Python-style multiline values).
  103. DebugFunc DebugFunc
  104. // ReaderBufferSize is the buffer size of the reader in bytes.
  105. ReaderBufferSize int
  106. // AllowNonUniqueSections indicates whether to allow sections with the same name multiple times.
  107. AllowNonUniqueSections bool
  108. }
  109. // DebugFunc is the type of function called to log parse events.
  110. type DebugFunc func(message string)
  111. // LoadSources allows caller to apply customized options for loading from data source(s).
  112. func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
  113. sources := make([]dataSource, len(others)+1)
  114. sources[0], err = parseDataSource(source)
  115. if err != nil {
  116. return nil, err
  117. }
  118. for i := range others {
  119. sources[i+1], err = parseDataSource(others[i])
  120. if err != nil {
  121. return nil, err
  122. }
  123. }
  124. f := newFile(sources, opts)
  125. if err = f.Reload(); err != nil {
  126. return nil, err
  127. }
  128. return f, nil
  129. }
  130. // Load loads and parses from INI data sources.
  131. // Arguments can be mixed of file name with string type, or raw data in []byte.
  132. // It will return error if list contains nonexistent files.
  133. func Load(source interface{}, others ...interface{}) (*File, error) {
  134. return LoadSources(LoadOptions{}, source, others...)
  135. }
  136. // LooseLoad has exactly same functionality as Load function
  137. // except it ignores nonexistent files instead of returning error.
  138. func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
  139. return LoadSources(LoadOptions{Loose: true}, source, others...)
  140. }
  141. // InsensitiveLoad has exactly same functionality as Load function
  142. // except it forces all section and key names to be lowercased.
  143. func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
  144. return LoadSources(LoadOptions{Insensitive: true}, source, others...)
  145. }
  146. // ShadowLoad has exactly same functionality as Load function
  147. // except it allows have shadow keys.
  148. func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
  149. return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
  150. }