-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenv.go
89 lines (67 loc) · 1.43 KB
/
env.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cmd
import (
"encoding/base64"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/alexfalkowski/go-service/file"
)
// ErrLocationMissing for cmd.
var ErrLocationMissing = errors.New("location is missing")
// ENV for cmd.
type ENV struct {
location string
}
// NewENV for cmd.
func NewENV(location string) *ENV {
return &ENV{location: location}
}
// Read for env.
func (e *ENV) Read() ([]byte, error) {
if e.isMem() {
_, e := e.split()
return base64.StdEncoding.DecodeString(os.Getenv(e))
}
if e.name() == "" {
return nil, e.missingLocationError()
}
return os.ReadFile(e.path())
}
// Write for env.
func (e *ENV) Write(data []byte, mode fs.FileMode) error {
if e.isMem() {
_, e := e.split()
return os.Setenv(e, base64.StdEncoding.EncodeToString(data))
}
if e.name() == "" {
return e.missingLocationError()
}
return os.WriteFile(e.path(), data, mode)
}
// Kind for env.
func (e *ENV) Kind() string {
if e.isMem() {
k, _ := e.split()
return k
}
return file.Extension(e.path())
}
func (e *ENV) path() string {
return filepath.Clean(e.name())
}
func (e *ENV) name() string {
return os.Getenv(e.location)
}
func (e *ENV) isMem() bool {
return strings.Contains(e.name(), ":")
}
func (e *ENV) split() (string, string) {
s := strings.Split(e.name(), ":")
return s[0], s[1]
}
func (e *ENV) missingLocationError() error {
return fmt.Errorf("%s: %w", e.location, ErrLocationMissing)
}