github.com/bartle-stripe/trillian@v1.2.1/cmd/flags.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cmd
    16  
    17  import (
    18  	"errors"
    19  	"flag"
    20  	"io/ioutil"
    21  	"os"
    22  
    23  	"bitbucket.org/creachadair/shell"
    24  )
    25  
    26  func parseFlags(file string) error {
    27  	args, valid := shell.Split(file)
    28  	if !valid {
    29  		return errors.New("flag file contains unclosed quotations")
    30  	}
    31  	// Expand any environment variables in the args
    32  	for i := range args {
    33  		args[i] = os.ExpandEnv(args[i])
    34  	}
    35  
    36  	if err := flag.CommandLine.Parse(args); err != nil {
    37  		return err
    38  	}
    39  
    40  	// Call flag.Parse() again so that command line flags
    41  	// can override flags provided in the provided flag file.
    42  	flag.Parse()
    43  	return nil
    44  }
    45  
    46  // ParseFlagFile parses a set of flags from a file at the provided
    47  // path. Re-calls flag.Parse() after parsing the flags in the file
    48  // so that flags provided on the command line take precedence over
    49  // flags provided in the file.
    50  func ParseFlagFile(path string) error {
    51  	file, err := ioutil.ReadFile(path)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	return parseFlags(string(file))
    56  }