File: ini.go

package info (click to toggle)
golang-github-aws-aws-sdk-go-v2 1.24.1-2~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 554,032 kB
  • sloc: java: 15,941; makefile: 419; sh: 175
file content (56 lines) | stat: -rw-r--r-- 1,206 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Package ini implements parsing of the AWS shared config file.
//
//	Example:
//	sections, err := ini.OpenFile("/path/to/file")
//	if err != nil {
//		panic(err)
//	}
//
//	profile := "foo"
//	section, ok := sections.GetSection(profile)
//	if !ok {
//		fmt.Printf("section %q could not be found", profile)
//	}
package ini

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// OpenFile parses shared config from the given file path.
func OpenFile(path string) (sections Sections, err error) {
	f, oerr := os.Open(path)
	if oerr != nil {
		return Sections{}, &UnableToReadFile{Err: oerr}
	}

	defer func() {
		closeErr := f.Close()
		if err == nil {
			err = closeErr
		} else if closeErr != nil {
			err = fmt.Errorf("close error: %v, original error: %w", closeErr, err)
		}
	}()

	return Parse(f, path)
}

// Parse parses shared config from the given reader.
func Parse(r io.Reader, path string) (Sections, error) {
	contents, err := io.ReadAll(r)
	if err != nil {
		return Sections{}, fmt.Errorf("read all: %v", err)
	}

	lines := strings.Split(string(contents), "\n")
	tokens, err := tokenize(lines)
	if err != nil {
		return Sections{}, fmt.Errorf("tokenize: %v", err)
	}

	return parse(tokens, path), nil
}