mirror of
https://github.com/offen/docker-volume-backup.git
synced 2025-12-06 01:28:03 +01:00
Use proper path expansion
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/offen/docker-volume-backup/internal/errwrap"
|
||||
"github.com/offen/envconfig"
|
||||
shell "mvdan.cc/sh/v3/shell"
|
||||
)
|
||||
|
||||
type configStrategy string
|
||||
@@ -99,11 +101,7 @@ func loadConfigsFromEnvFiles(directory string) ([]*Config, error) {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(directory, item.Name())
|
||||
f, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, errwrap.Wrap(err, fmt.Sprintf("error reading %s", item.Name()))
|
||||
}
|
||||
envFile, err := godotenv.Unmarshal(os.ExpandEnv(string(f)))
|
||||
envFile, err := source(p)
|
||||
if err != nil {
|
||||
return nil, errwrap.Wrap(err, fmt.Sprintf("error reading config file %s", p))
|
||||
}
|
||||
@@ -125,3 +123,39 @@ func loadConfigsFromEnvFiles(directory string) ([]*Config, error) {
|
||||
|
||||
return configs, nil
|
||||
}
|
||||
|
||||
// source tries to mimic the pre v2.37.0 behavior of calling
|
||||
// `set +a; source $path; set -a` and returns the env vars as a map
|
||||
func source(path string) (map[string]string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, errwrap.Wrap(err, fmt.Sprintf("error opening %s", path))
|
||||
}
|
||||
|
||||
result := map[string]string{}
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
withExpansion, err := shell.Expand(line, nil)
|
||||
if err != nil {
|
||||
return nil, errwrap.Wrap(err, "error expanding env")
|
||||
}
|
||||
m, err := godotenv.Unmarshal(withExpansion)
|
||||
if err != nil {
|
||||
return nil, errwrap.Wrap(err, fmt.Sprintf("error sourcing %s", path))
|
||||
}
|
||||
for key, value := range m {
|
||||
currentValue, currentOk := os.LookupEnv(key)
|
||||
defer func() {
|
||||
if currentOk {
|
||||
os.Setenv(key, currentValue)
|
||||
return
|
||||
}
|
||||
os.Unsetenv(key)
|
||||
}()
|
||||
result[key] = value
|
||||
os.Setenv(key, value)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user