ini.go 8.0 KB

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