github.com/criteo-forks/consul@v1.4.5-criteonogrpc/command/validate/validate.go (about) 1 package validate 2 3 import ( 4 "flag" 5 "fmt" 6 7 "github.com/hashicorp/consul/agent/config" 8 "github.com/hashicorp/consul/command/flags" 9 "github.com/mitchellh/cli" 10 ) 11 12 func New(ui cli.Ui) *cmd { 13 c := &cmd{UI: ui} 14 c.init() 15 return c 16 } 17 18 type cmd struct { 19 UI cli.Ui 20 flags *flag.FlagSet 21 // configFormat forces all config files to be interpreted as this 22 // format independent of their extension. 23 configFormat string 24 quiet bool 25 help string 26 } 27 28 func (c *cmd) init() { 29 c.flags = flag.NewFlagSet("", flag.ContinueOnError) 30 c.flags.StringVar(&c.configFormat, "config-format", "", 31 "Config files are in this format irrespective of their extension. Must be 'hcl' or 'json'") 32 c.flags.BoolVar(&c.quiet, "quiet", false, 33 "When given, a successful run will produce no output.") 34 c.help = flags.Usage(help, c.flags) 35 } 36 37 func (c *cmd) Run(args []string) int { 38 if err := c.flags.Parse(args); err != nil { 39 c.UI.Error(err.Error()) 40 return 1 41 } 42 43 configFiles := c.flags.Args() 44 if len(configFiles) < 1 { 45 c.UI.Error("Must specify at least one config file or directory") 46 return 1 47 } 48 49 if c.configFormat != "" && c.configFormat != "json" && c.configFormat != "hcl" { 50 c.UI.Error("-config-format must be either 'hcl' or 'json") 51 return 1 52 } 53 54 b, err := config.NewBuilder(config.Flags{ConfigFiles: configFiles, ConfigFormat: &c.configFormat}) 55 if err != nil { 56 c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error())) 57 return 1 58 } 59 if _, err := b.BuildAndValidate(); err != nil { 60 c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error())) 61 return 1 62 } 63 if !c.quiet { 64 c.UI.Output("Configuration is valid!") 65 } 66 return 0 67 } 68 69 func (c *cmd) Synopsis() string { 70 return synopsis 71 } 72 73 func (c *cmd) Help() string { 74 return c.help 75 } 76 77 const synopsis = "Validate config files/directories" 78 const help = ` 79 Usage: consul validate [options] FILE_OR_DIRECTORY... 80 81 Performs a thorough sanity test on Consul configuration files. For each file 82 or directory given, the validate command will attempt to parse the contents 83 just as the "consul agent" command would, and catch any errors. 84 85 This is useful to do a test of the configuration only, without actually 86 starting the agent. This performs all of the validation the agent would, so 87 this should be given the complete set of configuration files that are going 88 to be loaded by the agent. This command cannot operate on partial 89 configuration fragments since those won't pass the full agent validation. 90 91 Returns 0 if the configuration is valid, or 1 if there are problems. 92 `