forked from thanos-io/thanos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathorcontent.go
70 lines (55 loc) · 1.95 KB
/
pathorcontent.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
package extflag
import (
"fmt"
"io/ioutil"
"github.com/pkg/errors"
"gopkg.in/alecthomas/kingpin.v2"
)
// PathOrContent is a flag type that defines two flags to fetch bytes. Either from file (*-file flag) or content (* flag).
type PathOrContent struct {
flagName string
required bool
path *string
content *string
}
type CmdClause interface {
Flag(name, help string) *kingpin.FlagClause
}
// RegisterPathOrContent registers PathOrContent flag in kingpinCmdClause.
func RegisterPathOrContent(cmd CmdClause, flagName string, help string, required bool) *PathOrContent {
fileFlagName := fmt.Sprintf("%s-file", flagName)
contentFlagName := flagName
fileHelp := fmt.Sprintf("Path to %s", help)
fileFlag := cmd.Flag(fileFlagName, fileHelp).PlaceHolder("<file-path>").String()
contentHelp := fmt.Sprintf("Alternative to '%s' flag (lower priority). Content of %s", fileFlagName, help)
contentFlag := cmd.Flag(contentFlagName, contentHelp).PlaceHolder("<content>").String()
return &PathOrContent{
flagName: flagName,
required: required,
path: fileFlag,
content: contentFlag,
}
}
// Content returns content of the file. Flag that specifies path has priority.
// It returns error if the content is empty and required flag is set to true.
func (p *PathOrContent) Content() ([]byte, error) {
contentFlagName := p.flagName
fileFlagName := fmt.Sprintf("%s-file", p.flagName)
if len(*p.path) > 0 && len(*p.content) > 0 {
return nil, errors.Errorf("both %s and %s flags set.", fileFlagName, contentFlagName)
}
var content []byte
if len(*p.path) > 0 {
c, err := ioutil.ReadFile(*p.path)
if err != nil {
return nil, errors.Wrapf(err, "loading YAML file %s for %s", *p.path, fileFlagName)
}
content = c
} else {
content = []byte(*p.content)
}
if len(content) == 0 && p.required {
return nil, errors.Errorf("flag %s or %s is required for running this command and content cannot be empty.", fileFlagName, contentFlagName)
}
return content, nil
}