ini.go

 1// Package ini implements parsing of the AWS shared config file.
 2//
 3//	Example:
 4//	sections, err := ini.OpenFile("/path/to/file")
 5//	if err != nil {
 6//		panic(err)
 7//	}
 8//
 9//	profile := "foo"
10//	section, ok := sections.GetSection(profile)
11//	if !ok {
12//		fmt.Printf("section %q could not be found", profile)
13//	}
14package ini
15
16import (
17	"fmt"
18	"io"
19	"os"
20	"strings"
21)
22
23// OpenFile parses shared config from the given file path.
24func OpenFile(path string) (sections Sections, err error) {
25	f, oerr := os.Open(path)
26	if oerr != nil {
27		return Sections{}, &UnableToReadFile{Err: oerr}
28	}
29
30	defer func() {
31		closeErr := f.Close()
32		if err == nil {
33			err = closeErr
34		} else if closeErr != nil {
35			err = fmt.Errorf("close error: %v, original error: %w", closeErr, err)
36		}
37	}()
38
39	return Parse(f, path)
40}
41
42// Parse parses shared config from the given reader.
43func Parse(r io.Reader, path string) (Sections, error) {
44	contents, err := io.ReadAll(r)
45	if err != nil {
46		return Sections{}, fmt.Errorf("read all: %v", err)
47	}
48
49	lines := strings.Split(string(contents), "\n")
50	tokens, err := tokenize(lines)
51	if err != nil {
52		return Sections{}, fmt.Errorf("tokenize: %v", err)
53	}
54
55	return parse(tokens, path), nil
56}