github.com/spirius/terraform@v0.10.0-beta2.0.20170714185654-87b2c0cf8fea/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, err := c.Meta.process(args, false)
    33  	if err != nil {
    34  		return 1
    35  	}
    36  
    37  	cmdFlags := flag.NewFlagSet("fmt", flag.ContinueOnError)
    38  	cmdFlags.BoolVar(&c.opts.List, "list", true, "list")
    39  	cmdFlags.BoolVar(&c.opts.Write, "write", true, "write")
    40  	cmdFlags.BoolVar(&c.opts.Diff, "diff", false, "diff")
    41  	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
    42  
    43  	if err := cmdFlags.Parse(args); err != nil {
    44  		return 1
    45  	}
    46  
    47  	args = cmdFlags.Args()
    48  	if len(args) > 1 {
    49  		c.Ui.Error("The fmt command expects at most one argument.")
    50  		cmdFlags.Usage()
    51  		return 1
    52  	}
    53  
    54  	var dirs []string
    55  	if len(args) == 0 {
    56  		dirs = []string{"."}
    57  	} else if args[0] == stdinArg {
    58  		c.opts.List = false
    59  		c.opts.Write = false
    60  	} else {
    61  		dirs = []string{args[0]}
    62  	}
    63  
    64  	output := &cli.UiWriter{Ui: c.Ui}
    65  	err = fmtcmd.Run(dirs, []string{fileExtension}, c.input, output, c.opts)
    66  	if err != nil {
    67  		c.Ui.Error(fmt.Sprintf("Error running fmt: %s", err))
    68  		return 2
    69  	}
    70  
    71  	return 0
    72  }
    73  
    74  func (c *FmtCommand) Help() string {
    75  	helpText := `
    76  Usage: terraform fmt [options] [DIR]
    77  
    78  	Rewrites all Terraform configuration files to a canonical format.
    79  
    80  	If DIR is not specified then the current working directory will be used.
    81  	If DIR is "-" then content will be read from STDIN.
    82  
    83  Options:
    84  
    85    -list=true       List files whose formatting differs (always false if using STDIN)
    86  
    87    -write=true      Write result to source file instead of STDOUT (always false if using STDIN)
    88  
    89    -diff=false      Display diffs of formatting changes
    90  
    91  `
    92  	return strings.TrimSpace(helpText)
    93  }
    94  
    95  func (c *FmtCommand) Synopsis() string {
    96  	return "Rewrites config files to canonical format"
    97  }