github.com/jrperritt/terraform@v0.1.1-0.20170525065507-96f391dafc38/command/fmt.go (about) 1 package command 2 3 import ( 4 "flag" 5 "fmt" 6 "io" 7 "os" 8 "strings" 9 10 "github.com/hashicorp/hcl/hcl/fmtcmd" 11 "github.com/mitchellh/cli" 12 ) 13 14 const ( 15 stdinArg = "-" 16 fileExtension = "tf" 17 ) 18 19 // FmtCommand is a Command implementation that rewrites Terraform config 20 // files to a canonical format and style. 21 type FmtCommand struct { 22 Meta 23 opts fmtcmd.Options 24 input io.Reader // STDIN if nil 25 } 26 27 func (c *FmtCommand) Run(args []string) int { 28 if c.input == nil { 29 c.input = os.Stdin 30 } 31 32 args = c.Meta.process(args, false) 33 34 cmdFlags := flag.NewFlagSet("fmt", flag.ContinueOnError) 35 cmdFlags.BoolVar(&c.opts.List, "list", true, "list") 36 cmdFlags.BoolVar(&c.opts.Write, "write", true, "write") 37 cmdFlags.BoolVar(&c.opts.Diff, "diff", false, "diff") 38 cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } 39 40 if err := cmdFlags.Parse(args); err != nil { 41 return 1 42 } 43 44 args = cmdFlags.Args() 45 if len(args) > 1 { 46 c.Ui.Error("The fmt command expects at most one argument.") 47 cmdFlags.Usage() 48 return 1 49 } 50 51 var dirs []string 52 if len(args) == 0 { 53 dirs = []string{"."} 54 } else if args[0] == stdinArg { 55 c.opts.List = false 56 c.opts.Write = false 57 } else { 58 dirs = []string{args[0]} 59 } 60 61 output := &cli.UiWriter{Ui: c.Ui} 62 err := fmtcmd.Run(dirs, []string{fileExtension}, c.input, output, c.opts) 63 if err != nil { 64 c.Ui.Error(fmt.Sprintf("Error running fmt: %s", err)) 65 return 2 66 } 67 68 return 0 69 } 70 71 func (c *FmtCommand) Help() string { 72 helpText := ` 73 Usage: terraform fmt [options] [DIR] 74 75 Rewrites all Terraform configuration files to a canonical format. 76 77 If DIR is not specified then the current working directory will be used. 78 If DIR is "-" then content will be read from STDIN. 79 80 Options: 81 82 -list=true List files whose formatting differs (always false if using STDIN) 83 84 -write=true Write result to source file instead of STDOUT (always false if using STDIN) 85 86 -diff=false Display diffs of formatting changes 87 88 ` 89 return strings.TrimSpace(helpText) 90 } 91 92 func (c *FmtCommand) Synopsis() string { 93 return "Rewrites config files to canonical format" 94 }