ini.go 7.0 KB

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