1 // Copyright 2017 Unknwon
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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
28 // File represents a combination of a or more INI file(s) in memory.
31 dataSources []dataSource
33 // Should make things safe, but sometimes doesn't matter.
37 // To keep data in order.
39 // Actual data is stored here.
40 sections map[string]*Section
46 // newFile initializes File object with given data sources.
47 func newFile(dataSources []dataSource, opts LoadOptions) *File {
48 if len(opts.KeyValueDelimiters) == 0 {
49 opts.KeyValueDelimiters = "=:"
53 dataSources: dataSources,
54 sections: make(map[string]*Section),
55 sectionList: make([]string, 0, 10),
60 // Empty returns an empty file object.
62 // Ignore error here, we sure our data is good.
63 f, _ := Load([]byte(""))
67 // NewSection creates a new section.
68 func (f *File) NewSection(name string) (*Section, error) {
70 return nil, errors.New("error creating new section: empty section name")
71 } else if f.options.Insensitive && name != DefaultSection {
72 name = strings.ToLower(name)
80 if inSlice(name, f.sectionList) {
81 return f.sections[name], nil
84 f.sectionList = append(f.sectionList, name)
85 f.sections[name] = newSection(f, name)
86 return f.sections[name], nil
89 // NewRawSection creates a new section with an unparseable body.
90 func (f *File) NewRawSection(name, body string) (*Section, error) {
91 section, err := f.NewSection(name)
96 section.isRawSection = true
97 section.rawBody = body
101 // NewSections creates a list of sections.
102 func (f *File) NewSections(names ...string) (err error) {
103 for _, name := range names {
104 if _, err = f.NewSection(name); err != nil {
111 // GetSection returns section by given name.
112 func (f *File) GetSection(name string) (*Section, error) {
114 name = DefaultSection
116 if f.options.Insensitive {
117 name = strings.ToLower(name)
122 defer f.lock.RUnlock()
125 sec := f.sections[name]
127 return nil, fmt.Errorf("section '%s' does not exist", name)
132 // Section assumes named section exists and returns a zero-value when not.
133 func (f *File) Section(name string) *Section {
134 sec, err := f.GetSection(name)
136 // Note: It's OK here because the only possible error is empty section name,
137 // but if it's empty, this piece of code won't be executed.
138 sec, _ = f.NewSection(name)
144 // Sections returns a list of Section stored in the current instance.
145 func (f *File) Sections() []*Section {
148 defer f.lock.RUnlock()
151 sections := make([]*Section, len(f.sectionList))
152 for i, name := range f.sectionList {
153 sections[i] = f.sections[name]
158 // ChildSections returns a list of child sections of given section name.
159 func (f *File) ChildSections(name string) []*Section {
160 return f.Section(name).ChildSections()
163 // SectionStrings returns list of section names.
164 func (f *File) SectionStrings() []string {
165 list := make([]string, len(f.sectionList))
166 copy(list, f.sectionList)
170 // DeleteSection deletes a section.
171 func (f *File) DeleteSection(name string) {
174 defer f.lock.Unlock()
178 name = DefaultSection
181 for i, s := range f.sectionList {
183 f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
184 delete(f.sections, name)
190 func (f *File) reload(s dataSource) error {
191 r, err := s.ReadCloser()
200 // Reload reloads and parses all data sources.
201 func (f *File) Reload() (err error) {
202 for _, s := range f.dataSources {
203 if err = f.reload(s); err != nil {
204 // In loose mode, we create an empty default section for nonexistent files.
205 if os.IsNotExist(err) && f.options.Loose {
206 f.parse(bytes.NewBuffer(nil))
215 // Append appends one or more data sources and reloads automatically.
216 func (f *File) Append(source interface{}, others ...interface{}) error {
217 ds, err := parseDataSource(source)
221 f.dataSources = append(f.dataSources, ds)
222 for _, s := range others {
223 ds, err = parseDataSource(s)
227 f.dataSources = append(f.dataSources, ds)
232 func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
233 equalSign := DefaultFormatLeft + "=" + DefaultFormatRight
235 if PrettyFormat || PrettyEqual {
239 // Use buffer to make sure target is safe until finish encoding.
240 buf := bytes.NewBuffer(nil)
241 for i, sname := range f.sectionList {
242 sec := f.Section(sname)
243 if len(sec.Comment) > 0 {
244 // Support multiline comments
245 lines := strings.Split(sec.Comment, LineBreak)
246 for i := range lines {
247 if lines[i][0] != '#' && lines[i][0] != ';' {
248 lines[i] = "; " + lines[i]
250 lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
253 if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
259 if i > 0 || DefaultHeader {
260 if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
264 // Write nothing if default section is empty
265 if len(sec.keyList) == 0 {
270 if sec.isRawSection {
271 if _, err := buf.WriteString(sec.rawBody); err != nil {
276 // Put a line between sections
277 if _, err := buf.WriteString(LineBreak); err != nil {
284 // Count and generate alignment length and buffer spaces using the
285 // longest key. Keys may be modifed if they contain certain characters so
286 // we need to take that into account in our calculation.
289 for _, kname := range sec.keyList {
290 keyLength := len(kname)
291 // First case will surround key by ` and second by """
292 if strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters) {
294 } else if strings.Contains(kname, "`") {
298 if keyLength > alignLength {
299 alignLength = keyLength
303 alignSpaces := bytes.Repeat([]byte(" "), alignLength)
306 for _, kname := range sec.keyList {
307 key := sec.Key(kname)
308 if len(key.Comment) > 0 {
309 if len(indent) > 0 && sname != DefaultSection {
310 buf.WriteString(indent)
313 // Support multiline comments
314 lines := strings.Split(key.Comment, LineBreak)
315 for i := range lines {
316 if lines[i][0] != '#' && lines[i][0] != ';' {
317 lines[i] = "; " + strings.TrimSpace(lines[i])
319 lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
322 if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
328 if len(indent) > 0 && sname != DefaultSection {
329 buf.WriteString(indent)
333 case key.isAutoIncrement:
335 case strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters):
336 kname = "`" + kname + "`"
337 case strings.Contains(kname, "`"):
338 kname = `"""` + kname + `"""`
341 for _, val := range key.ValueWithShadows() {
342 if _, err := buf.WriteString(kname); err != nil {
346 if key.isBooleanType {
347 if kname != sec.keyList[len(sec.keyList)-1] {
348 buf.WriteString(LineBreak)
353 // Write out alignment spaces before "=" sign
355 buf.Write(alignSpaces[:alignLength-len(kname)])
358 // In case key value contains "\n", "`", "\"", "#" or ";"
359 if strings.ContainsAny(val, "\n`") {
360 val = `"""` + val + `"""`
361 } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") {
362 val = "`" + val + "`"
364 if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil {
369 for _, val := range key.nestedValues {
370 if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil {
377 // Put a line between sections
378 if _, err := buf.WriteString(LineBreak); err != nil {
387 // WriteToIndent writes content into io.Writer with given indention.
388 // If PrettyFormat has been set to be true,
389 // it will align "=" sign with spaces under each section.
390 func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) {
391 buf, err := f.writeToBuffer(indent)
395 return buf.WriteTo(w)
398 // WriteTo writes file content into io.Writer.
399 func (f *File) WriteTo(w io.Writer) (int64, error) {
400 return f.WriteToIndent(w, "")
403 // SaveToIndent writes content to file system with given value indention.
404 func (f *File) SaveToIndent(filename, indent string) error {
405 // Note: Because we are truncating with os.Create,
406 // so it's safer to save to a temporary file location and rename afte done.
407 buf, err := f.writeToBuffer(indent)
412 return ioutil.WriteFile(filename, buf.Bytes(), 0666)
415 // SaveTo writes content to file system.
416 func (f *File) SaveTo(filename string) error {
417 return f.SaveToIndent(filename, "")