|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/hashicorp/hcl/v2" |
| 10 | + "github.com/hashicorp/hcl/v2/hclwrite" |
| 11 | + "github.com/jumppad-labs/jumppad/pkg/utils" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +func newFormatCmd() *cobra.Command { |
| 16 | + formatCmd := &cobra.Command{ |
| 17 | + Use: "fmt [file] | [directory]", |
| 18 | + Short: "fmt the configuration at the given path", |
| 19 | + Long: `fmt the configuration at the given path`, |
| 20 | + Example: ` |
| 21 | + # fmt configuration in .hcl files in the current folder |
| 22 | + jumppad fmt |
| 23 | +
|
| 24 | + # format configuration in a specific file |
| 25 | + jumppad fmt my-stack/network.hcl |
| 26 | +
|
| 27 | + # format configuration in a specific directory |
| 28 | + jumppad fmt ./my-stack |
| 29 | + `, |
| 30 | + Args: cobra.ArbitraryArgs, |
| 31 | + RunE: newFormatCmdFunc(), |
| 32 | + SilenceUsage: true, |
| 33 | + } |
| 34 | + |
| 35 | + return formatCmd |
| 36 | +} |
| 37 | + |
| 38 | +func newFormatCmdFunc() func(cmd *cobra.Command, args []string) error { |
| 39 | + return func(cmd *cobra.Command, args []string) error { |
| 40 | + dst := "" |
| 41 | + if len(args) == 1 { |
| 42 | + dst = args[0] |
| 43 | + } else { |
| 44 | + dst = "./" |
| 45 | + } |
| 46 | + |
| 47 | + if dst == "." { |
| 48 | + dst = "./" |
| 49 | + } |
| 50 | + |
| 51 | + if dst != "" { |
| 52 | + if utils.IsHCLFile(dst) { |
| 53 | + err := format(dst) |
| 54 | + if err != nil { |
| 55 | + return err |
| 56 | + } |
| 57 | + } else if utils.IsLocalFolder(dst) { |
| 58 | + err := filepath.Walk(dst, func(path string, info os.FileInfo, err error) error { |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + |
| 63 | + if !info.IsDir() && strings.HasSuffix(path, ".hcl") { |
| 64 | + err := format(path) |
| 65 | + if err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return nil |
| 71 | + }) |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + } else { |
| 76 | + return fmt.Errorf("error: can only format local files and directories") |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return nil |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +func format(path string) error { |
| 85 | + data, err := os.ReadFile(path) |
| 86 | + if err != nil { |
| 87 | + return err |
| 88 | + } |
| 89 | + |
| 90 | + file, diags := hclwrite.ParseConfig(data, path, hcl.InitialPos) |
| 91 | + if diags.HasErrors() { |
| 92 | + return fmt.Errorf("errors: %v", diags) |
| 93 | + } |
| 94 | + |
| 95 | + err = os.WriteFile(path, file.Bytes(), 0644) |
| 96 | + if err != nil { |
| 97 | + return err |
| 98 | + } |
| 99 | + |
| 100 | + return nil |
| 101 | +} |
0 commit comments