ini.go 7.9 KB

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