github.com/m3db/m3@v1.5.0/src/x/config/configflag/flag.go (about)

     1  // Copyright (c) 2019 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package configflag
    22  
    23  import (
    24  	"errors"
    25  	"flag"
    26  	"fmt"
    27  	"io"
    28  	"os"
    29  
    30  	"github.com/m3db/m3/src/x/config"
    31  )
    32  
    33  var _ flag.Value = (*FlagStringSlice)(nil)
    34  
    35  // Options represents the values of config command line flags
    36  type Options struct {
    37  	// set by commandline flags
    38  	// ConfigFiles (-f) is a list of config files to load
    39  	ConfigFiles FlagStringSlice
    40  
    41  	// ShouldDumpConfigAndExit (-d) causes MainLoad to print config to stdout,
    42  	// and then exit.
    43  	ShouldDumpConfigAndExit bool
    44  
    45  	// for Usage()
    46  	cmd *flag.FlagSet
    47  
    48  	// test mocking options
    49  	osFns osIface
    50  }
    51  
    52  // Register registers commandline options with the default flagset.
    53  func (opts *Options) Register() {
    54  	opts.RegisterFlagSet(flag.CommandLine)
    55  }
    56  
    57  // RegisterFlagSet registers commandline options with the given flagset.
    58  func (opts *Options) RegisterFlagSet(cmd *flag.FlagSet) {
    59  	opts.cmd = cmd
    60  
    61  	cmd.Var(&opts.ConfigFiles, "f", "Configuration files to load")
    62  	cmd.BoolVar(&opts.ShouldDumpConfigAndExit, "d", false, "Dump configuration and exit")
    63  }
    64  
    65  // MainLoad is a convenience method, intended for use in main(), which handles all
    66  // config commandline options. It:
    67  //  - Dumps config and exits if -d was passed.
    68  //  - Loads configuration otherwise.
    69  // Users who want a subset of this behavior should call individual methods.
    70  func (opts *Options) MainLoad(target interface{}, loadOpts config.Options) error {
    71  	osFns := opts.osFns
    72  	if osFns == nil {
    73  		osFns = realOS{}
    74  	}
    75  
    76  	if len(opts.ConfigFiles.Value) == 0 {
    77  		opts.cmd.Usage()
    78  		return errors.New("-f is required (no config files provided)")
    79  	}
    80  
    81  	if err := config.LoadFiles(target, opts.ConfigFiles.Value, loadOpts); err != nil {
    82  		return fmt.Errorf("unable to load config from %s: %v", opts.ConfigFiles.Value, err)
    83  	}
    84  
    85  	if opts.ShouldDumpConfigAndExit {
    86  		if err := config.Dump(target, osFns.Stdout()); err != nil {
    87  			return fmt.Errorf("failed to dump config: %v", err)
    88  		}
    89  
    90  		osFns.Exit(0)
    91  	}
    92  	return nil
    93  }
    94  
    95  // FlagStringSlice represents a slice of strings. When used as a flag variable,
    96  // it allows for multiple string values. For example, it can be used like this:
    97  // 	var configFiles FlagStringSlice
    98  // 	flag.Var(&configFiles, "f", "configuration file(s)")
    99  // Then it can be invoked like this:
   100  // 	./app -f file1.yaml -f file2.yaml -f valueN.yaml
   101  // Finally, when the flags are parsed, the variable contains all the values.
   102  type FlagStringSlice struct {
   103  	Value []string
   104  
   105  	overridden bool
   106  }
   107  
   108  // String() returns a string implementation of the slice.
   109  func (i *FlagStringSlice) String() string {
   110  	if i == nil {
   111  		return ""
   112  	}
   113  	return fmt.Sprintf("%v", i.Value)
   114  }
   115  
   116  // Set appends a string value to the slice.
   117  func (i *FlagStringSlice) Set(value string) error {
   118  	// on first call, reset
   119  	// afterwards, append. This allows better defaulting behavior (defaults
   120  	// are overridden by explicitly specified flags).
   121  	if !i.overridden {
   122  		// make this a new slice.
   123  		i.overridden = true
   124  		i.Value = nil
   125  	}
   126  
   127  	i.Value = append(i.Value, value)
   128  	return nil
   129  }
   130  
   131  type osIface interface {
   132  	Exit(status int)
   133  	Stdout() io.Writer
   134  }
   135  
   136  type realOS struct{}
   137  
   138  func (r realOS) Exit(status int) {
   139  	os.Exit(status)
   140  }
   141  
   142  func (r realOS) Stdout() io.Writer {
   143  	return os.Stdout
   144  }