~samwhited/env

ref: v0.0.1 env/env.go -rw-r--r-- 935 bytes
3d601a08Sam Whited Initial public release 1 year, 4 months ago
                                                                                
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
// Package env can be used to load environment variables from files.
package env // import "code.soquee.net/env"

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

// Read loads a list of environment variables from a reader and puts them into
// the processes local environment.
func Read(fd io.Reader) error {
	scanner := bufio.NewScanner(fd)
	line := 0
	for scanner.Scan() {
		text := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(text, "#") || text == "" {
			continue
		}
		parts := strings.SplitN(text, "=", 2)
		if len(parts) != 2 {
			return fmt.Errorf("invalid .env line %d", line)
		}
		val := strings.TrimSpace(parts[1])
		unquoted, err := strconv.Unquote(val)
		// ignore any errors, assume that means the original string wasn't quoted.
		if err == nil {
			val = unquoted
		}
		err = os.Setenv(strings.TrimSpace(parts[0]), val)
		if err != nil {
			return err
		}
		line++
	}
	return scanner.Err()
}