3 // Copyright 2014 Unknwon
5 // Licensed under the Apache License, Version 2.0 (the "License"): you may
6 // not use this file except in compliance with the License. You may obtain
7 // a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 // License for the specific language governing permissions and limitations
17 // Package ini provides INI file read and write functionality in Go.
31 // DefaultSection is the name of default section. You can use this constant or the string literal.
32 // In most of cases, an empty string is all you need to access the section.
33 DefaultSection = "DEFAULT"
34 // Deprecated: Use "DefaultSection" instead.
35 DEFAULT_SECTION = DefaultSection
37 // Maximum allowed depth when recursively substituing variable names.
42 // Version returns current package version literal.
43 func Version() string {
48 // LineBreak is the delimiter to determine or compose a new line.
49 // This variable will be changed to "\r\n" automatically on Windows at package init time.
52 // DefaultFormatLeft places custom spaces on the left when PrettyFormat and PrettyEqual are both disabled.
53 DefaultFormatLeft = ""
54 // DefaultFormatRight places custom spaces on the right when PrettyFormat and PrettyEqual are both disabled.
55 DefaultFormatRight = ""
57 // Variable regexp pattern: %(variable)s
58 varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
60 // PrettyFormat indicates whether to align "=" sign with spaces to produce pretty output
61 // or reduce all possible spaces for compact format.
64 // PrettyEqual places spaces around "=" sign even when PrettyFormat is false.
67 // DefaultHeader explicitly writes default section header.
70 // PrettySection indicates whether to put a line between sections.
75 if runtime.GOOS == "windows" {
80 func inSlice(str string, s []string) bool {
89 // dataSource is an interface that returns object which can be read and closed.
90 type dataSource interface {
91 ReadCloser() (io.ReadCloser, error)
94 // sourceFile represents an object that contains content on the local file system.
95 type sourceFile struct {
99 func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
100 return os.Open(s.name)
103 // sourceData represents an object that contains content in memory.
104 type sourceData struct {
108 func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
109 return ioutil.NopCloser(bytes.NewReader(s.data)), nil
112 // sourceReadCloser represents an input stream with Close method.
113 type sourceReadCloser struct {
117 func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
121 func parseDataSource(source interface{}) (dataSource, error) {
122 switch s := source.(type) {
124 return sourceFile{s}, nil
126 return &sourceData{s}, nil
128 return &sourceReadCloser{s}, nil
130 return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
134 // LoadOptions contains all customized options used for load data source(s).
135 type LoadOptions struct {
136 // Loose indicates whether the parser should ignore nonexistent files or return error.
138 // Insensitive indicates whether the parser forces all section and key names to lowercase.
140 // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
141 IgnoreContinuation bool
142 // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
143 IgnoreInlineComment bool
144 // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
145 SkipUnrecognizableLines bool
146 // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
147 // This type of keys are mostly used in my.cnf.
148 AllowBooleanKeys bool
149 // AllowShadows indicates whether to keep track of keys with same name under same section.
151 // AllowNestedValues indicates whether to allow AWS-like nested values.
152 // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
153 AllowNestedValues bool
154 // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
155 // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
156 // Relevant quote: Values can also span multiple lines, as long as they are indented deeper
157 // than the first line of the value.
158 AllowPythonMultilineValues bool
159 // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
160 // Docs: https://docs.python.org/2/library/configparser.html
161 // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
162 // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
163 SpaceBeforeInlineComment bool
164 // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
165 // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
166 UnescapeValueDoubleQuotes bool
167 // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
168 // when value is NOT surrounded by any quotes.
169 // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
170 UnescapeValueCommentSymbols bool
171 // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
172 // conform to key/value pairs. Specify the names of those blocks here.
173 UnparseableSections []string
174 // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
175 KeyValueDelimiters string
176 // PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
177 PreserveSurroundedQuote bool
180 // LoadSources allows caller to apply customized options for loading from data source(s).
181 func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
182 sources := make([]dataSource, len(others)+1)
183 sources[0], err = parseDataSource(source)
187 for i := range others {
188 sources[i+1], err = parseDataSource(others[i])
193 f := newFile(sources, opts)
194 if err = f.Reload(); err != nil {
200 // Load loads and parses from INI data sources.
201 // Arguments can be mixed of file name with string type, or raw data in []byte.
202 // It will return error if list contains nonexistent files.
203 func Load(source interface{}, others ...interface{}) (*File, error) {
204 return LoadSources(LoadOptions{}, source, others...)
207 // LooseLoad has exactly same functionality as Load function
208 // except it ignores nonexistent files instead of returning error.
209 func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
210 return LoadSources(LoadOptions{Loose: true}, source, others...)
213 // InsensitiveLoad has exactly same functionality as Load function
214 // except it forces all section and key names to be lowercased.
215 func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
216 return LoadSources(LoadOptions{Insensitive: true}, source, others...)
219 // ShadowLoad has exactly same functionality as Load function
220 // except it allows have shadow keys.
221 func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
222 return LoadSources(LoadOptions{AllowShadows: true}, source, others...)