123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509 |
- package ini
- import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "strings"
- "sync"
- )
- type File struct {
- options LoadOptions
- dataSources []dataSource
-
- BlockMode bool
- lock sync.RWMutex
-
- sectionList []string
-
-
- sectionIndexes []int
-
- sections map[string][]*Section
- NameMapper
- ValueMapper
- }
- func newFile(dataSources []dataSource, opts LoadOptions) *File {
- if len(opts.KeyValueDelimiters) == 0 {
- opts.KeyValueDelimiters = "=:"
- }
- if len(opts.KeyValueDelimiterOnWrite) == 0 {
- opts.KeyValueDelimiterOnWrite = "="
- }
- return &File{
- BlockMode: true,
- dataSources: dataSources,
- sections: make(map[string][]*Section),
- options: opts,
- }
- }
- func Empty(opts ...LoadOptions) *File {
- var opt LoadOptions
- if len(opts) > 0 {
- opt = opts[0]
- }
-
- f, _ := LoadSources(opt, []byte(""))
- return f
- }
- func (f *File) NewSection(name string) (*Section, error) {
- if len(name) == 0 {
- return nil, errors.New("empty section name")
- }
- if f.options.Insensitive && name != DefaultSection {
- name = strings.ToLower(name)
- }
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
- if !f.options.AllowNonUniqueSections && inSlice(name, f.sectionList) {
- return f.sections[name][0], nil
- }
- f.sectionList = append(f.sectionList, name)
-
-
- f.sectionIndexes = append(f.sectionIndexes, len(f.sections[name]))
- sec := newSection(f, name)
- f.sections[name] = append(f.sections[name], sec)
- return sec, nil
- }
- func (f *File) NewRawSection(name, body string) (*Section, error) {
- section, err := f.NewSection(name)
- if err != nil {
- return nil, err
- }
- section.isRawSection = true
- section.rawBody = body
- return section, nil
- }
- func (f *File) NewSections(names ...string) (err error) {
- for _, name := range names {
- if _, err = f.NewSection(name); err != nil {
- return err
- }
- }
- return nil
- }
- func (f *File) GetSection(name string) (*Section, error) {
- secs, err := f.SectionsByName(name)
- if err != nil {
- return nil, err
- }
- return secs[0], err
- }
- func (f *File) SectionsByName(name string) ([]*Section, error) {
- if len(name) == 0 {
- name = DefaultSection
- }
- if f.options.Insensitive {
- name = strings.ToLower(name)
- }
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
- secs := f.sections[name]
- if len(secs) == 0 {
- return nil, fmt.Errorf("section %q does not exist", name)
- }
- return secs, nil
- }
- func (f *File) Section(name string) *Section {
- sec, err := f.GetSection(name)
- if err != nil {
-
-
- sec, _ = f.NewSection(name)
- return sec
- }
- return sec
- }
- func (f *File) SectionWithIndex(name string, index int) *Section {
- secs, err := f.SectionsByName(name)
- if err != nil || len(secs) <= index {
-
-
- newSec, _ := f.NewSection(name)
- return newSec
- }
- return secs[index]
- }
- func (f *File) Sections() []*Section {
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
- sections := make([]*Section, len(f.sectionList))
- for i, name := range f.sectionList {
- sections[i] = f.sections[name][f.sectionIndexes[i]]
- }
- return sections
- }
- func (f *File) ChildSections(name string) []*Section {
- return f.Section(name).ChildSections()
- }
- func (f *File) SectionStrings() []string {
- list := make([]string, len(f.sectionList))
- copy(list, f.sectionList)
- return list
- }
- func (f *File) DeleteSection(name string) {
- secs, err := f.SectionsByName(name)
- if err != nil {
- return
- }
- for i := 0; i < len(secs); i++ {
-
-
-
- _ = f.DeleteSectionWithIndex(name, 0)
- }
- }
- func (f *File) DeleteSectionWithIndex(name string, index int) error {
- if !f.options.AllowNonUniqueSections && index != 0 {
- return fmt.Errorf("delete section with non-zero index is only allowed when non-unique sections is enabled")
- }
- if len(name) == 0 {
- name = DefaultSection
- }
- if f.options.Insensitive {
- name = strings.ToLower(name)
- }
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
-
- occurrences := 0
- sectionListCopy := make([]string, len(f.sectionList))
- copy(sectionListCopy, f.sectionList)
- for i, s := range sectionListCopy {
- if s != name {
- continue
- }
- if occurrences == index {
- if len(f.sections[name]) <= 1 {
- delete(f.sections, name)
- } else {
- f.sections[name] = append(f.sections[name][:index], f.sections[name][index+1:]...)
- }
-
- f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
- f.sectionIndexes = append(f.sectionIndexes[:i], f.sectionIndexes[i+1:]...)
- } else if occurrences > index {
-
- f.sectionIndexes[i-1]--
- }
- occurrences++
- }
- return nil
- }
- func (f *File) reload(s dataSource) error {
- r, err := s.ReadCloser()
- if err != nil {
- return err
- }
- defer r.Close()
- return f.parse(r)
- }
- func (f *File) Reload() (err error) {
- for _, s := range f.dataSources {
- if err = f.reload(s); err != nil {
-
- if os.IsNotExist(err) && f.options.Loose {
- _ = f.parse(bytes.NewBuffer(nil))
- continue
- }
- return err
- }
- }
- return nil
- }
- func (f *File) Append(source interface{}, others ...interface{}) error {
- ds, err := parseDataSource(source)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- for _, s := range others {
- ds, err = parseDataSource(s)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- }
- return f.Reload()
- }
- func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
- equalSign := DefaultFormatLeft + f.options.KeyValueDelimiterOnWrite + DefaultFormatRight
- if PrettyFormat || PrettyEqual {
- equalSign = fmt.Sprintf(" %s ", f.options.KeyValueDelimiterOnWrite)
- }
-
- buf := bytes.NewBuffer(nil)
- for i, sname := range f.sectionList {
- sec := f.SectionWithIndex(sname, f.sectionIndexes[i])
- if len(sec.Comment) > 0 {
-
- lines := strings.Split(sec.Comment, LineBreak)
- for i := range lines {
- if lines[i][0] != '#' && lines[i][0] != ';' {
- lines[i] = "; " + lines[i]
- } else {
- lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
- }
- if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
- return nil, err
- }
- }
- }
- if i > 0 || DefaultHeader {
- if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
- return nil, err
- }
- } else {
-
- if len(sec.keyList) == 0 {
- continue
- }
- }
- if sec.isRawSection {
- if _, err := buf.WriteString(sec.rawBody); err != nil {
- return nil, err
- }
- if PrettySection {
-
- if _, err := buf.WriteString(LineBreak); err != nil {
- return nil, err
- }
- }
- continue
- }
-
-
-
- alignLength := 0
- if PrettyFormat {
- for _, kname := range sec.keyList {
- keyLength := len(kname)
-
- if strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters) {
- keyLength += 2
- } else if strings.Contains(kname, "`") {
- keyLength += 6
- }
- if keyLength > alignLength {
- alignLength = keyLength
- }
- }
- }
- alignSpaces := bytes.Repeat([]byte(" "), alignLength)
- KeyList:
- for _, kname := range sec.keyList {
- key := sec.Key(kname)
- if len(key.Comment) > 0 {
- if len(indent) > 0 && sname != DefaultSection {
- buf.WriteString(indent)
- }
-
- lines := strings.Split(key.Comment, LineBreak)
- for i := range lines {
- if lines[i][0] != '#' && lines[i][0] != ';' {
- lines[i] = "; " + strings.TrimSpace(lines[i])
- } else {
- lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
- }
- if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
- return nil, err
- }
- }
- }
- if len(indent) > 0 && sname != DefaultSection {
- buf.WriteString(indent)
- }
- switch {
- case key.isAutoIncrement:
- kname = "-"
- case strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters):
- kname = "`" + kname + "`"
- case strings.Contains(kname, "`"):
- kname = `"""` + kname + `"""`
- }
- for _, val := range key.ValueWithShadows() {
- if _, err := buf.WriteString(kname); err != nil {
- return nil, err
- }
- if key.isBooleanType {
- if kname != sec.keyList[len(sec.keyList)-1] {
- buf.WriteString(LineBreak)
- }
- continue KeyList
- }
-
- if PrettyFormat {
- buf.Write(alignSpaces[:alignLength-len(kname)])
- }
-
- if strings.ContainsAny(val, "\n`") {
- val = `"""` + val + `"""`
- } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") {
- val = "`" + val + "`"
- }
- if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil {
- return nil, err
- }
- }
- for _, val := range key.nestedValues {
- if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil {
- return nil, err
- }
- }
- }
- if PrettySection {
-
- if _, err := buf.WriteString(LineBreak); err != nil {
- return nil, err
- }
- }
- }
- return buf, nil
- }
- func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) {
- buf, err := f.writeToBuffer(indent)
- if err != nil {
- return 0, err
- }
- return buf.WriteTo(w)
- }
- func (f *File) WriteTo(w io.Writer) (int64, error) {
- return f.WriteToIndent(w, "")
- }
- func (f *File) SaveToIndent(filename, indent string) error {
-
-
- buf, err := f.writeToBuffer(indent)
- if err != nil {
- return err
- }
- return ioutil.WriteFile(filename, buf.Bytes(), 0666)
- }
- func (f *File) SaveTo(filename string) error {
- return f.SaveToIndent(filename, "")
- }
|