github.com/hashicorp/packer@v1.14.3/command/fmt.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package command 5 6 import ( 7 "context" 8 "os" 9 "strings" 10 11 hclutils "github.com/hashicorp/packer/hcl2template" 12 "github.com/posener/complete" 13 ) 14 15 type FormatCommand struct { 16 Meta 17 } 18 19 func (c *FormatCommand) Run(args []string) int { 20 ctx := context.Background() 21 cfg, ret := c.ParseArgs(args) 22 if ret != 0 { 23 return ret 24 } 25 26 return c.RunContext(ctx, cfg) 27 } 28 29 func (c *FormatCommand) ParseArgs(args []string) (*FormatArgs, int) { 30 var cfg FormatArgs 31 flags := c.Meta.FlagSet("format") 32 flags.Usage = func() { c.Ui.Say(c.Help()) } 33 cfg.AddFlagSets(flags) 34 if err := flags.Parse(args); err != nil { 35 return &cfg, 1 36 } 37 38 args = flags.Args() 39 if len(args) == 0 { 40 flags.Usage() 41 return &cfg, 1 42 } 43 44 cfg.Paths = args 45 return &cfg, 0 46 } 47 48 func (c *FormatCommand) RunContext(ctx context.Context, cla *FormatArgs) int { 49 if cla.Check { 50 cla.Write = false 51 } 52 53 formatter := hclutils.HCL2Formatter{ 54 ShowDiff: cla.Diff, 55 Write: cla.Write, 56 Output: os.Stdout, 57 Recursive: cla.Recursive, 58 } 59 60 bytesModified, diags := formatter.Format(cla.Paths) 61 ret := writeDiags(c.Ui, nil, diags) 62 if ret != 0 { 63 return ret 64 } 65 66 if cla.Check && bytesModified > 0 { 67 // exit code taken from `terraform fmt` command 68 return 3 69 } 70 71 return 0 72 } 73 74 func (*FormatCommand) Help() string { 75 helpText := ` 76 Usage: packer fmt [options] [TEMPLATE] 77 78 Rewrites all Packer configuration files to a canonical format. Both 79 configuration files (.pkr.hcl) and variable files (.pkrvars.hcl) are updated. 80 JSON files (.json) are not modified. 81 82 If TEMPLATE is "." the current directory will be used. 83 If TEMPLATE is "-" then content will be read from STDIN. 84 85 The given content must be in Packer's HCL2 configuration language; JSON is 86 not supported. 87 88 Options: 89 -check Check if the input is formatted. Exit status will be 0 if all 90 input is properly formatted and non-zero otherwise. 91 92 -diff Display diffs of formatting change 93 94 -write=false Don't write to source files 95 (always disabled if using -check) 96 97 -recursive Also process files in subdirectories. By default, only the 98 given directory (or current directory) is processed. 99 ` 100 101 return strings.TrimSpace(helpText) 102 } 103 104 func (*FormatCommand) Synopsis() string { 105 return "Rewrites HCL2 config files to canonical format" 106 } 107 108 func (*FormatCommand) AutocompleteArgs() complete.Predictor { 109 return complete.PredictNothing 110 } 111 112 func (*FormatCommand) AutocompleteFlags() complete.Flags { 113 return complete.Flags{ 114 "-check": complete.PredictNothing, 115 "-diff": complete.PredictNothing, 116 "-write": complete.PredictNothing, 117 "-recursive": complete.PredictNothing, 118 } 119 }