code.dwrz.net

Go monorepo.
Log | Files | Refs

ini.go (1140B)


      1 package ini
      2 
      3 import (
      4 	"fmt"
      5 	"io"
      6 	"os"
      7 )
      8 
      9 // OpenFile takes a path to a given file, and will open  and parse
     10 // that file.
     11 func OpenFile(path string) (sections Sections, err error) {
     12 	f, oerr := os.Open(path)
     13 	if oerr != nil {
     14 		return Sections{}, &UnableToReadFile{Err: oerr}
     15 	}
     16 
     17 	defer func() {
     18 		closeErr := f.Close()
     19 		if err == nil {
     20 			err = closeErr
     21 		} else if closeErr != nil {
     22 			err = fmt.Errorf("close error: %v, original error: %w", closeErr, err)
     23 		}
     24 	}()
     25 
     26 	return Parse(f, path)
     27 }
     28 
     29 // Parse will parse the given file using the shared config
     30 // visitor.
     31 func Parse(f io.Reader, path string) (Sections, error) {
     32 	tree, err := ParseAST(f)
     33 	if err != nil {
     34 		return Sections{}, err
     35 	}
     36 
     37 	v := NewDefaultVisitor(path)
     38 	if err = Walk(tree, v); err != nil {
     39 		return Sections{}, err
     40 	}
     41 
     42 	return v.Sections, nil
     43 }
     44 
     45 // ParseBytes will parse the given bytes and return the parsed sections.
     46 func ParseBytes(b []byte) (Sections, error) {
     47 	tree, err := ParseASTBytes(b)
     48 	if err != nil {
     49 		return Sections{}, err
     50 	}
     51 
     52 	v := NewDefaultVisitor("")
     53 	if err = Walk(tree, v); err != nil {
     54 		return Sections{}, err
     55 	}
     56 
     57 	return v.Sections, nil
     58 }