diff options
| author | elcore <eldinhadzic@protonmail.com> | 2020-05-15 23:49:51 +0200 | 
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-05-15 15:49:51 -0600 | 
| commit | 62c9f2cf3e86f8aaea7a1583f09adb6b8007cfe6 (patch) | |
| tree | 8407f9f2919a4ef66254fc6b20b361c56fd38901 /cmd/main.go | |
| parent | bde3823b76b457a933e684cd096ca84fc6378997 (diff) | |
cmd: Add --envfile flag to run command (#3278)
* run: Add the possibility to load an env file
* run: change envfile flag var
* run: do not ignore err values
* Apply suggestions from code review
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
Diffstat (limited to 'cmd/main.go')
| -rw-r--r-- | cmd/main.go | 68 | 
1 files changed, 68 insertions, 0 deletions
| diff --git a/cmd/main.go b/cmd/main.go index 7e8d9b7..4fd8d68 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -15,6 +15,7 @@  package caddycmd  import ( +	"bufio"  	"bytes"  	"flag"  	"fmt" @@ -339,6 +340,73 @@ func flagHelp(fs *flag.FlagSet) string {  	return buf.String()  } +func loadEnvFromFile(envFile string) error { +	file, err := os.Open(envFile) +	if err != nil { +		return fmt.Errorf("reading environment file: %v", err) +	} +	defer file.Close() + +	envMap, err := parseEnvFile(file) +	if err != nil { +		return fmt.Errorf("parsing environment file: %v", err) +	} + +	for k, v := range envMap { +		if err := os.Setenv(k, v); err != nil { +			return fmt.Errorf("setting environment variables: %v", err) +		} +	} + +	return nil +} + +func parseEnvFile(envInput io.Reader) (map[string]string, error) { +	envMap := make(map[string]string) + +	scanner := bufio.NewScanner(envInput) +	var line string +	lineNumber := 0 + +	for scanner.Scan() { +		line = strings.TrimSpace(scanner.Text()) +		lineNumber++ + +		// skip lines starting with comment +		if strings.HasPrefix(line, "#") { +			continue +		} + +		// skip empty line +		if len(line) == 0 { +			continue +		} + +		fields := strings.SplitN(line, "=", 2) +		if len(fields) != 2 { +			return nil, fmt.Errorf("can't parse line %d; line should be in KEY=VALUE format", lineNumber) +		} + +		if strings.Contains(fields[0], " ") { +			return nil, fmt.Errorf("bad key on line %d: contains whitespace", lineNumber) +		} + +		key := fields[0] +		val := fields[1] + +		if key == "" { +			return nil, fmt.Errorf("missing or empty key on line %d", lineNumber) +		} +		envMap[key] = val +	} + +	if err := scanner.Err(); err != nil { +		return nil, err +	} + +	return envMap, nil +} +  func printEnvironment() {  	fmt.Printf("caddy.HomeDir=%s\n", caddy.HomeDir())  	fmt.Printf("caddy.AppDataDir=%s\n", caddy.AppDataDir()) | 
