ini.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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.32.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. // Explicitly write DEFAULT section header
  48. DefaultHeader = false
  49. // Indicate whether to put a line between sections
  50. PrettySection = true
  51. )
  52. func init() {
  53. if runtime.GOOS == "windows" {
  54. LineBreak = "\r\n"
  55. }
  56. }
  57. func inSlice(str string, s []string) bool {
  58. for _, v := range s {
  59. if str == v {
  60. return true
  61. }
  62. }
  63. return false
  64. }
  65. // dataSource is an interface that returns object which can be read and closed.
  66. type dataSource interface {
  67. ReadCloser() (io.ReadCloser, error)
  68. }
  69. // sourceFile represents an object that contains content on the local file system.
  70. type sourceFile struct {
  71. name string
  72. }
  73. func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
  74. return os.Open(s.name)
  75. }
  76. // sourceData represents an object that contains content in memory.
  77. type sourceData struct {
  78. data []byte
  79. }
  80. func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
  81. return ioutil.NopCloser(bytes.NewReader(s.data)), nil
  82. }
  83. // sourceReadCloser represents an input stream with Close method.
  84. type sourceReadCloser struct {
  85. reader io.ReadCloser
  86. }
  87. func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
  88. return s.reader, nil
  89. }
  90. func parseDataSource(source interface{}) (dataSource, error) {
  91. switch s := source.(type) {
  92. case string:
  93. return sourceFile{s}, nil
  94. case []byte:
  95. return &sourceData{s}, nil
  96. case io.ReadCloser:
  97. return &sourceReadCloser{s}, nil
  98. default:
  99. return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
  100. }
  101. }
  102. type LoadOptions struct {
  103. // Loose indicates whether the parser should ignore nonexistent files or return error.
  104. Loose bool
  105. // Insensitive indicates whether the parser forces all section and key names to lowercase.
  106. Insensitive bool
  107. // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
  108. IgnoreContinuation bool
  109. // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
  110. IgnoreInlineComment bool
  111. // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
  112. // This type of keys are mostly used in my.cnf.
  113. AllowBooleanKeys bool
  114. // AllowShadows indicates whether to keep track of keys with same name under same section.
  115. AllowShadows bool
  116. // AllowNestedValues indicates whether to allow AWS-like nested values.
  117. // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
  118. AllowNestedValues bool
  119. // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
  120. // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
  121. UnescapeValueDoubleQuotes bool
  122. // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
  123. // when value is NOT surrounded by any quotes.
  124. // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
  125. UnescapeValueCommentSymbols bool
  126. // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise
  127. // conform to key/value pairs. Specify the names of those blocks here.
  128. UnparseableSections []string
  129. }
  130. func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
  131. sources := make([]dataSource, len(others)+1)
  132. sources[0], err = parseDataSource(source)
  133. if err != nil {
  134. return nil, err
  135. }
  136. for i := range others {
  137. sources[i+1], err = parseDataSource(others[i])
  138. if err != nil {
  139. return nil, err
  140. }
  141. }
  142. f := newFile(sources, opts)
  143. if err = f.Reload(); err != nil {
  144. return nil, err
  145. }
  146. return f, nil
  147. }
  148. // Load loads and parses from INI data sources.
  149. // Arguments can be mixed of file name with string type, or raw data in []byte.
  150. // It will return error if list contains nonexistent files.
  151. func Load(source interface{}, others ...interface{}) (*File, error) {
  152. return LoadSources(LoadOptions{}, source, others...)
  153. }
  154. // LooseLoad has exactly same functionality as Load function
  155. // except it ignores nonexistent files instead of returning error.
  156. func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
  157. return LoadSources(LoadOptions{Loose: true}, source, others...)
  158. }
  159. // InsensitiveLoad has exactly same functionality as Load function
  160. // except it forces all section and key names to be lowercased.
  161. func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
  162. return LoadSources(LoadOptions{Insensitive: true}, source, others...)
  163. }
  164. // InsensitiveLoad has exactly same functionality as Load function
  165. // except it allows have shadow keys.
  166. func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
  167. return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
  168. }