-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathread_from_file.go
More file actions
49 lines (41 loc) · 1.01 KB
/
read_from_file.go
File metadata and controls
49 lines (41 loc) · 1.01 KB
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
package flags
import (
"fmt"
"os"
"strings"
"github.com/spf13/pflag"
)
type readFromFileFlag struct {
// Used to read file.
// Set to os.ReadFile, except during tests
reader func(filename string) ([]byte, error)
value string
}
// Ensure the implementation satisfies the expected interface
var _ pflag.Value = &readFromFileFlag{}
// ReadFromFileFlag returns a string flag.
// If it starts with "@", it is assumed to be a file path and content is read from file instead
func ReadFromFileFlag() *readFromFileFlag {
return &readFromFileFlag{
reader: os.ReadFile,
}
}
func (f *readFromFileFlag) String() string {
return f.value
}
func (f *readFromFileFlag) Set(value string) error {
if !strings.HasPrefix(value, "@") {
f.value = value
} else {
valuePath := strings.Trim(value[1:], `"'`)
valueBytes, err := f.reader(valuePath)
if err != nil {
return fmt.Errorf("read data from file: %w", err)
}
f.value = string(valueBytes)
}
return nil
}
func (f *readFromFileFlag) Type() string {
return "string"
}