123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 |
- package ini
- import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- const (
-
-
- DEFAULT_SECTION = "DEFAULT"
-
- _DEPTH_VALUES = 99
- _VERSION = "1.24.0"
- )
- func Version() string {
- return _VERSION
- }
- var (
-
-
-
- LineBreak = "\n"
-
- varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
-
-
- PrettyFormat = true
-
- DefaultHeader = false
- )
- func init() {
- if runtime.GOOS == "windows" {
- LineBreak = "\r\n"
- }
- }
- func inSlice(str string, s []string) bool {
- for _, v := range s {
- if str == v {
- return true
- }
- }
- return false
- }
- type dataSource interface {
- ReadCloser() (io.ReadCloser, error)
- }
- type sourceFile struct {
- name string
- }
- func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
- return os.Open(s.name)
- }
- type bytesReadCloser struct {
- reader io.Reader
- }
- func (rc *bytesReadCloser) Read(p []byte) (n int, err error) {
- return rc.reader.Read(p)
- }
- func (rc *bytesReadCloser) Close() error {
- return nil
- }
- type sourceData struct {
- data []byte
- }
- func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(s.data)), nil
- }
- type sourceReadCloser struct {
- reader io.ReadCloser
- }
- func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
- return s.reader, nil
- }
- type File struct {
-
- BlockMode bool
-
- lock sync.RWMutex
-
- dataSources []dataSource
-
- sections map[string]*Section
-
- sectionList []string
- options LoadOptions
- NameMapper
- ValueMapper
- }
- func newFile(dataSources []dataSource, opts LoadOptions) *File {
- return &File{
- BlockMode: true,
- dataSources: dataSources,
- sections: make(map[string]*Section),
- sectionList: make([]string, 0, 10),
- options: opts,
- }
- }
- func parseDataSource(source interface{}) (dataSource, error) {
- switch s := source.(type) {
- case string:
- return sourceFile{s}, nil
- case []byte:
- return &sourceData{s}, nil
- case io.ReadCloser:
- return &sourceReadCloser{s}, nil
- default:
- return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
- }
- }
- type LoadOptions struct {
-
- Loose bool
-
- Insensitive bool
-
- IgnoreContinuation bool
-
-
- AllowBooleanKeys bool
-
-
- UnparseableSections []string
- }
- func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
- sources := make([]dataSource, len(others)+1)
- sources[0], err = parseDataSource(source)
- if err != nil {
- return nil, err
- }
- for i := range others {
- sources[i+1], err = parseDataSource(others[i])
- if err != nil {
- return nil, err
- }
- }
- f := newFile(sources, opts)
- if err = f.Reload(); err != nil {
- return nil, err
- }
- return f, nil
- }
- func Load(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{}, source, others...)
- }
- func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Loose: true}, source, others...)
- }
- func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Insensitive: true}, source, others...)
- }
- func Empty() *File {
-
- f, _ := Load([]byte(""))
- return f
- }
- func (f *File) NewSection(name string) (*Section, error) {
- if len(name) == 0 {
- return nil, errors.New("error creating new section: empty section name")
- } else if f.options.Insensitive && name != DEFAULT_SECTION {
- name = strings.ToLower(name)
- }
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
- if inSlice(name, f.sectionList) {
- return f.sections[name], nil
- }
- f.sectionList = append(f.sectionList, name)
- f.sections[name] = newSection(f, name)
- return f.sections[name], 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) {
- if len(name) == 0 {
- name = DEFAULT_SECTION
- } else if f.options.Insensitive {
- name = strings.ToLower(name)
- }
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
- sec := f.sections[name]
- if sec == nil {
- return nil, fmt.Errorf("section '%s' does not exist", name)
- }
- return sec, 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) Sections() []*Section {
- sections := make([]*Section, len(f.sectionList))
- for i := range f.sectionList {
- sections[i] = f.Section(f.sectionList[i])
- }
- return sections
- }
- func (f *File) SectionStrings() []string {
- list := make([]string, len(f.sectionList))
- copy(list, f.sectionList)
- return list
- }
- func (f *File) DeleteSection(name string) {
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
- if len(name) == 0 {
- name = DEFAULT_SECTION
- }
- for i, s := range f.sectionList {
- if s == name {
- f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
- delete(f.sections, name)
- return
- }
- }
- }
- 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) WriteToIndent(w io.Writer, indent string) (n int64, err error) {
- equalSign := "="
- if PrettyFormat {
- equalSign = " = "
- }
-
- buf := bytes.NewBuffer(nil)
- for i, sname := range f.sectionList {
- sec := f.Section(sname)
- if len(sec.Comment) > 0 {
- if sec.Comment[0] != '#' && sec.Comment[0] != ';' {
- sec.Comment = "; " + sec.Comment
- }
- if _, err = buf.WriteString(sec.Comment + LineBreak); err != nil {
- return 0, err
- }
- }
- if i > 0 || DefaultHeader {
- if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
- return 0, err
- }
- } else {
-
- if len(sec.keyList) == 0 {
- continue
- }
- }
- if sec.isRawSection {
- if _, err = buf.WriteString(sec.rawBody); err != nil {
- return 0, err
- }
- continue
- }
-
-
-
- alignLength := 0
- if PrettyFormat {
- for _, kname := range sec.keyList {
- keyLength := len(kname)
-
- if strings.ContainsAny(kname, "\"=:") {
- keyLength += 2
- } else if strings.Contains(kname, "`") {
- keyLength += 6
- }
- if keyLength > alignLength {
- alignLength = keyLength
- }
- }
- }
- alignSpaces := bytes.Repeat([]byte(" "), alignLength)
- for _, kname := range sec.keyList {
- key := sec.Key(kname)
- if len(key.Comment) > 0 {
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
- if key.Comment[0] != '#' && key.Comment[0] != ';' {
- key.Comment = "; " + key.Comment
- }
- if _, err = buf.WriteString(key.Comment + LineBreak); err != nil {
- return 0, err
- }
- }
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
- switch {
- case key.isAutoIncrement:
- kname = "-"
- case strings.ContainsAny(kname, "\"=:"):
- kname = "`" + kname + "`"
- case strings.Contains(kname, "`"):
- kname = `"""` + kname + `"""`
- }
- if _, err = buf.WriteString(kname); err != nil {
- return 0, err
- }
- if key.isBooleanType {
- if kname != sec.keyList[len(sec.keyList)-1] {
- buf.WriteString(LineBreak)
- }
- continue
- }
-
- if PrettyFormat {
- buf.Write(alignSpaces[:alignLength-len(kname)])
- }
- val := key.value
-
- if strings.ContainsAny(val, "\n`") {
- val = `"""` + val + `"""`
- } else if strings.ContainsAny(val, "#;") {
- val = "`" + val + "`"
- }
- if _, err = buf.WriteString(equalSign + val + LineBreak); err != nil {
- return 0, err
- }
- }
-
- if _, err = buf.WriteString(LineBreak); 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 {
-
-
- tmpPath := filename + "." + strconv.Itoa(time.Now().Nanosecond()) + ".tmp"
- defer os.Remove(tmpPath)
- fw, err := os.Create(tmpPath)
- if err != nil {
- return err
- }
- if _, err = f.WriteToIndent(fw, indent); err != nil {
- fw.Close()
- return err
- }
- fw.Close()
-
- os.Remove(filename)
- return os.Rename(tmpPath, filename)
- }
- func (f *File) SaveTo(filename string) error {
- return f.SaveToIndent(filename, "")
- }
|