-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
68 lines (56 loc) · 1.23 KB
/
load.go
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
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2023, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package env
import (
"strings"
"github.com/go-pogo/errors"
)
// Load sets the system's environment variables with those from the Map when
// they do not exist.
func Load(envs Environment) error {
return load(envs, false)
}
// Overload sets and overwrites the system's environment variables with those
// from the Map.
func Overload(envs Environment) error {
return load(envs, true)
}
func load(envs Environment, overload bool) (err error) {
var m Map
if em, ok := envs.(Map); ok {
m = em
} else if m, err = envs.Environ(); err != nil {
return errors.WithStack(err)
}
if len(m) == 0 {
return nil
}
var r *Replacer
if predictReplacerNeed(m) {
r = NewReplacer(Chain(m, System()))
}
for k, v := range m {
if _, has := LookupEnv(k); has && !overload {
continue
}
if r != nil {
v, err = r.Replace(v)
if err != nil {
return err
}
}
if err = Setenv(k, v); err != nil {
return err
}
}
return nil
}
func predictReplacerNeed(m Map) bool {
for _, v := range m {
if strings.ContainsRune(v.String(), '$') {
return true
}
}
return false
}