Skip to content

Commit

Permalink
Example of loading flags from a file
Browse files Browse the repository at this point in the history
  • Loading branch information
Rob Percival committed May 19, 2017
1 parent 89a2fd7 commit c6d3fc8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions cmd/createtree/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ import (
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/google/trillian"
"github.com/google/trillian/cmd"
"github.com/google/trillian/crypto/keyspb"
"github.com/google/trillian/crypto/sigpb"
"google.golang.org/grpc"
)

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

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

if *configFile != "" {
if flag.NFlag() != 1 {
fmt.Printf("No other flags can be provided when --config is set")
os.Exit(1)
}

if err := cmd.ParseFlagFile(*configFile); err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse %v: %v\n", *configFile, err)
os.Exit(1)
}

// Alternative to printing error if more than just "--config" flag is provided:
// let command-line flags take precedent by re-parsing from the command-line.
// flag.Parse()
}

ctx := context.Background()
tree, err := createTree(ctx, newOptsFromFlags())
if err != nil {
Expand Down
24 changes: 24 additions & 0 deletions cmd/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cmd

import (
"flag"
"io/ioutil"

"github.com/mattn/go-shellwords"
)

func ParseFlagFile(path string) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}

p := shellwords.NewParser()
p.ParseEnv = true
args, err := p.Parse(string(file))
if err != nil {
return err
}

return flag.CommandLine.Parse(args)
}

0 comments on commit c6d3fc8

Please sign in to comment.