ini.go 7.0 KB

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