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.

219 lines
7.5 KiB

  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. "bytes"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "os"
  23. "regexp"
  24. "runtime"
  25. )
  26. const (
  27. // Name for default section. You can use this constant or the string literal.
  28. // In most of cases, an empty string is all you need to access the section.
  29. DEFAULT_SECTION = "DEFAULT"
  30. // Maximum allowed depth when recursively substituing variable names.
  31. _DEPTH_VALUES = 99
  32. _VERSION = "1.42.0"
  33. )
  34. // Version returns current package version literal.
  35. func Version() string {
  36. return _VERSION
  37. }
  38. var (
  39. // Delimiter to determine or compose a new line.
  40. // This variable will be changed to "\r\n" automatically on Windows
  41. // at package init time.
  42. LineBreak = "\n"
  43. // Place custom spaces when PrettyFormat and PrettyEqual are both disabled
  44. DefaultFormatLeft = ""
  45. DefaultFormatRight = ""
  46. // Variable regexp pattern: %(variable)s
  47. varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
  48. // Indicate whether to align "=" sign with spaces to produce pretty output
  49. // or reduce all possible spaces for compact format.
  50. PrettyFormat = true
  51. // Place spaces around "=" sign even when PrettyFormat is false
  52. PrettyEqual = false
  53. // Explicitly write DEFAULT section header
  54. DefaultHeader = false
  55. // Indicate whether to put a line between sections
  56. PrettySection = true
  57. )
  58. func init() {
  59. if runtime.GOOS == "windows" {
  60. LineBreak = "\r\n"
  61. }
  62. }
  63. func inSlice(str string, s []string) bool {
  64. for _, v := range s {
  65. if str == v {
  66. return true
  67. }
  68. }
  69. return false
  70. }
  71. // dataSource is an interface that returns object which can be read and closed.
  72. type dataSource interface {
  73. ReadCloser() (io.ReadCloser, error)
  74. }
  75. // sourceFile represents an object that contains content on the local file system.
  76. type sourceFile struct {
  77. name string
  78. }
  79. func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
  80. return os.Open(s.name)
  81. }
  82. // sourceData represents an object that contains content in memory.
  83. type sourceData struct {
  84. data []byte
  85. }
  86. func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
  87. return ioutil.NopCloser(bytes.NewReader(s.data)), nil
  88. }
  89. // sourceReadCloser represents an input stream with Close method.
  90. type sourceReadCloser struct {
  91. reader io.ReadCloser
  92. }
  93. func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
  94. return s.reader, nil
  95. }
  96. func parseDataSource(source interface{}) (dataSource, error) {
  97. switch s := source.(type) {
  98. case string:
  99. return sourceFile{s}, nil
  100. case []byte:
  101. return &sourceData{s}, nil
  102. case io.ReadCloser:
  103. return &sourceReadCloser{s}, nil
  104. default:
  105. return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
  106. }
  107. }
  108. type LoadOptions struct {
  109. // Loose indicates whether the parser should ignore nonexistent files or return error.
  110. Loose bool
  111. // Insensitive indicates whether the parser forces all section and key names to lowercase.
  112. Insensitive bool
  113. // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
  114. IgnoreContinuation bool
  115. // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
  116. IgnoreInlineComment bool
  117. // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
  118. SkipUnrecognizableLines bool
  119. // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
  120. // This type of keys are mostly used in my.cnf.
  121. AllowBooleanKeys bool
  122. // AllowShadows indicates whether to keep track of keys with same name under same section.
  123. AllowShadows bool
  124. // AllowNestedValues indicates whether to allow AWS-like nested values.
  125. // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
  126. AllowNestedValues bool
  127. // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
  128. // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
  129. // Relevant quote: Values can also span multiple lines, as long as they are indented deeper
  130. // than the first line of the value.
  131. AllowPythonMultilineValues bool
  132. // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
  133. // Docs: https://docs.python.org/2/library/configparser.html
  134. // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
  135. // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
  136. SpaceBeforeInlineComment bool
  137. // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
  138. // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
  139. UnescapeValueDoubleQuotes bool
  140. // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
  141. // when value is NOT surrounded by any quotes.
  142. // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
  143. UnescapeValueCommentSymbols bool
  144. // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
  145. // conform to key/value pairs. Specify the names of those blocks here.
  146. UnparseableSections []string
  147. // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
  148. KeyValueDelimiters string
  149. // PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
  150. PreserveSurroundedQuote bool
  151. }
  152. func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
  153. sources := make([]dataSource, len(others)+1)
  154. sources[0], err = parseDataSource(source)
  155. if err != nil {
  156. return nil, err
  157. }
  158. for i := range others {
  159. sources[i+1], err = parseDataSource(others[i])
  160. if err != nil {
  161. return nil, err
  162. }
  163. }
  164. f := newFile(sources, opts)
  165. if err = f.Reload(); err != nil {
  166. return nil, err
  167. }
  168. return f, nil
  169. }
  170. // Load loads and parses from INI data sources.
  171. // Arguments can be mixed of file name with string type, or raw data in []byte.
  172. // It will return error if list contains nonexistent files.
  173. func Load(source interface{}, others ...interface{}) (*File, error) {
  174. return LoadSources(LoadOptions{}, source, others...)
  175. }
  176. // LooseLoad has exactly same functionality as Load function
  177. // except it ignores nonexistent files instead of returning error.
  178. func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
  179. return LoadSources(LoadOptions{Loose: true}, source, others...)
  180. }
  181. // InsensitiveLoad has exactly same functionality as Load function
  182. // except it forces all section and key names to be lowercased.
  183. func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
  184. return LoadSources(LoadOptions{Insensitive: true}, source, others...)
  185. }
  186. // ShadowLoad has exactly same functionality as Load function
  187. // except it allows have shadow keys.
  188. func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
  189. return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
  190. }