You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ini.go 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. // InsensitiveSections indicates whether the parser forces all section to lowercase.
  63. InsensitiveSections bool
  64. // InsensitiveKeys indicates whether the parser forces all key names to lowercase.
  65. InsensitiveKeys bool
  66. // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
  67. IgnoreContinuation bool
  68. // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
  69. IgnoreInlineComment bool
  70. // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
  71. SkipUnrecognizableLines bool
  72. // ShortCircuit indicates whether to ignore other configuration sources after loaded the first available configuration source.
  73. ShortCircuit bool
  74. // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
  75. // This type of keys are mostly used in my.cnf.
  76. AllowBooleanKeys bool
  77. // AllowShadows indicates whether to keep track of keys with same name under same section.
  78. AllowShadows bool
  79. // AllowNestedValues indicates whether to allow AWS-like nested values.
  80. // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
  81. AllowNestedValues bool
  82. // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
  83. // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
  84. // Relevant quote: Values can also span multiple lines, as long as they are indented deeper
  85. // than the first line of the value.
  86. AllowPythonMultilineValues bool
  87. // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
  88. // Docs: https://docs.python.org/2/library/configparser.html
  89. // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
  90. // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
  91. SpaceBeforeInlineComment bool
  92. // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
  93. // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
  94. UnescapeValueDoubleQuotes bool
  95. // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
  96. // when value is NOT surrounded by any quotes.
  97. // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
  98. UnescapeValueCommentSymbols bool
  99. // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
  100. // conform to key/value pairs. Specify the names of those blocks here.
  101. UnparseableSections []string
  102. // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
  103. KeyValueDelimiters string
  104. // KeyValueDelimiterOnWrite is the delimiter that are used to separate key and value output. By default, it is "=".
  105. KeyValueDelimiterOnWrite string
  106. // ChildSectionDelimiter is the delimiter that is used to separate child sections. By default, it is ".".
  107. ChildSectionDelimiter string
  108. // PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
  109. PreserveSurroundedQuote bool
  110. // DebugFunc is called to collect debug information (currently only useful to debug parsing Python-style multiline values).
  111. DebugFunc DebugFunc
  112. // ReaderBufferSize is the buffer size of the reader in bytes.
  113. ReaderBufferSize int
  114. // AllowNonUniqueSections indicates whether to allow sections with the same name multiple times.
  115. AllowNonUniqueSections bool
  116. }
  117. // DebugFunc is the type of function called to log parse events.
  118. type DebugFunc func(message string)
  119. // LoadSources allows caller to apply customized options for loading from data source(s).
  120. func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
  121. sources := make([]dataSource, len(others)+1)
  122. sources[0], err = parseDataSource(source)
  123. if err != nil {
  124. return nil, err
  125. }
  126. for i := range others {
  127. sources[i+1], err = parseDataSource(others[i])
  128. if err != nil {
  129. return nil, err
  130. }
  131. }
  132. f := newFile(sources, opts)
  133. if err = f.Reload(); err != nil {
  134. return nil, err
  135. }
  136. return f, nil
  137. }
  138. // Load loads and parses from INI data sources.
  139. // Arguments can be mixed of file name with string type, or raw data in []byte.
  140. // It will return error if list contains nonexistent files.
  141. func Load(source interface{}, others ...interface{}) (*File, error) {
  142. return LoadSources(LoadOptions{}, source, others...)
  143. }
  144. // LooseLoad has exactly same functionality as Load function
  145. // except it ignores nonexistent files instead of returning error.
  146. func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
  147. return LoadSources(LoadOptions{Loose: true}, source, others...)
  148. }
  149. // InsensitiveLoad has exactly same functionality as Load function
  150. // except it forces all section and key names to be lowercased.
  151. func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
  152. return LoadSources(LoadOptions{Insensitive: true}, source, others...)
  153. }
  154. // ShadowLoad has exactly same functionality as Load function
  155. // except it allows have shadow keys.
  156. func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
  157. return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
  158. }