-
Notifications
You must be signed in to change notification settings - Fork 24
/
fileread_flag.go
70 lines (59 loc) · 1.84 KB
/
fileread_flag.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
// Copyright 2015 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package flagz
import (
"fmt"
"io/ioutil"
flag "github.com/spf13/pflag"
)
// ReadFileFlags parses the flagset to discover all "fileread" flags and evaluates them.
//
// By reading and evaluating it means: attempts to read the file and set the value.
func ReadFileFlags(flagSet *flag.FlagSet) error {
var outerErr error
flagSet.VisitAll(func(f *flag.Flag) {
if frv, ok := f.Value.(*FileReadValue); ok {
if err := frv.readFile(); err != nil {
outerErr = fmt.Errorf("reading file flag '%v' failed: %v", f.Name, err)
}
}
})
return outerErr
}
// FileReadValue is a flag that wraps another flag and makes it readable from a local file in the filesystem.
type FileReadValue struct {
parentFlagName string
filePath string
flagSet *flag.FlagSet
}
// FileReadFlag creates a `Flag` that allows you to pass a flag.
//
// If defaultFilePath is non empty, the flagz.ReadFileFlags will expect the file to be there.
func FileReadFlag(flagSet *flag.FlagSet, parentFlagName string, defaultFilePath string) *FileReadValue {
dynValue := &FileReadValue{parentFlagName: parentFlagName, filePath: defaultFilePath, flagSet: flagSet}
flagSet.VarPF(dynValue,
parentFlagName+"_path",
"",
fmt.Sprintf("Path to read contents to a file to read contents of '%v' from.", parentFlagName))
return dynValue
}
func (f *FileReadValue) String() string {
return fmt.Sprintf("fileread_for(%v)", f.parentFlagName)
}
func (f *FileReadValue) Set(path string) error {
f.filePath = path
return nil
}
func (f *FileReadValue) Type() string {
return "fileread"
}
func (f *FileReadValue) readFile() error {
if f.filePath == "" {
return nil
}
data, err := ioutil.ReadFile(f.filePath)
if err != nil {
return err
}
return f.flagSet.Set(f.parentFlagName, string(data))
}