Skip to content

Commit c6d3fc8

Browse files
author
Rob Percival
committed
Example of loading flags from a file
1 parent 89a2fd7 commit c6d3fc8

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

cmd/createtree/main.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,14 @@ import (
4141
"github.com/golang/protobuf/ptypes"
4242
"github.com/golang/protobuf/ptypes/any"
4343
"github.com/google/trillian"
44+
"github.com/google/trillian/cmd"
4445
"github.com/google/trillian/crypto/keyspb"
4546
"github.com/google/trillian/crypto/sigpb"
4647
"google.golang.org/grpc"
4748
)
4849

4950
var (
51+
configFile = flag.String("config", "", "Config file containing flags")
5052
adminServerAddr = flag.String("admin_server", "", "Address of the gRPC Trillian Admin Server (host:port)")
5153

5254
treeState = flag.String("tree_state", trillian.TreeState_ACTIVE.String(), "State of the new tree")
@@ -175,6 +177,22 @@ func newOptsFromFlags() *createOpts {
175177
func main() {
176178
flag.Parse()
177179

180+
if *configFile != "" {
181+
if flag.NFlag() != 1 {
182+
fmt.Printf("No other flags can be provided when --config is set")
183+
os.Exit(1)
184+
}
185+
186+
if err := cmd.ParseFlagFile(*configFile); err != nil {
187+
fmt.Fprintf(os.Stderr, "Failed to parse %v: %v\n", *configFile, err)
188+
os.Exit(1)
189+
}
190+
191+
// Alternative to printing error if more than just "--config" flag is provided:
192+
// let command-line flags take precedent by re-parsing from the command-line.
193+
// flag.Parse()
194+
}
195+
178196
ctx := context.Background()
179197
tree, err := createTree(ctx, newOptsFromFlags())
180198
if err != nil {

cmd/flags.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package cmd
2+
3+
import (
4+
"flag"
5+
"io/ioutil"
6+
7+
"github.com/mattn/go-shellwords"
8+
)
9+
10+
func ParseFlagFile(path string) error {
11+
file, err := ioutil.ReadFile(path)
12+
if err != nil {
13+
return err
14+
}
15+
16+
p := shellwords.NewParser()
17+
p.ParseEnv = true
18+
args, err := p.Parse(string(file))
19+
if err != nil {
20+
return err
21+
}
22+
23+
return flag.CommandLine.Parse(args)
24+
}

0 commit comments

Comments
 (0)