ini.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // }
  14. package ini
  15. import (
  16. "fmt"
  17. "io"
  18. "os"
  19. "strings"
  20. )
  21. // OpenFile parses shared config from the given file path.
  22. func OpenFile(path string) (sections Sections, err error) {
  23. f, oerr := os.Open(path)
  24. if oerr != nil {
  25. return Sections{}, &UnableToReadFile{Err: oerr}
  26. }
  27. defer func() {
  28. closeErr := f.Close()
  29. if err == nil {
  30. err = closeErr
  31. } else if closeErr != nil {
  32. err = fmt.Errorf("close error: %v, original error: %w", closeErr, err)
  33. }
  34. }()
  35. return Parse(f, path)
  36. }
  37. // Parse parses shared config from the given reader.
  38. func Parse(r io.Reader, path string) (Sections, error) {
  39. contents, err := io.ReadAll(r)
  40. if err != nil {
  41. return Sections{}, fmt.Errorf("read all: %v", err)
  42. }
  43. lines := strings.Split(string(contents), "\n")
  44. tokens, err := tokenize(lines)
  45. if err != nil {
  46. return Sections{}, fmt.Errorf("tokenize: %v", err)
  47. }
  48. return parse(tokens, path), nil
  49. }