summaryrefslogtreecommitdiff
path: root/cmd
diff options
context:
space:
mode:
authorVaibhav <vrongmeal@gmail.com>2020-02-29 22:42:16 +0530
committerGitHub <noreply@github.com>2020-02-29 10:12:16 -0700
commit5fe69ac4ab8bb1da84fc80776548fcc16f89b1db (patch)
tree4b3f4c0f21d88ebaa1d1f209110dd7e63f07d179 /cmd
parente717028f83bcb8187b8e4559c9abacd529c12eea (diff)
cmd: Add `caddy fmt` command. (#3090)
This takes the config file as input and formats it. Prints the result to stdout. Can write changes to file if `--write` flag is passed. Fixes #3020 Signed-off-by: Vaibhav <vrongmeal@gmail.com>
Diffstat (limited to 'cmd')
-rw-r--r--cmd/commandfuncs.go30
-rw-r--r--cmd/commands.go18
2 files changed, 48 insertions, 0 deletions
diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go
index a2c8e3d..4f86aa8 100644
--- a/cmd/commandfuncs.go
+++ b/cmd/commandfuncs.go
@@ -34,6 +34,7 @@ import (
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
+ "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/mholt/certmagic"
"go.uber.org/zap"
)
@@ -538,6 +539,35 @@ func cmdValidateConfig(fl Flags) (int, error) {
return caddy.ExitCodeSuccess, nil
}
+func cmdFormatConfig(fl Flags) (int, error) {
+ // Default path of file is Caddyfile
+ formatCmdConfigFile := fl.Arg(0)
+ if formatCmdConfigFile == "" {
+ formatCmdConfigFile = "Caddyfile"
+ }
+
+ formatCmdWriteFlag := fl.Bool("write")
+
+ input, err := ioutil.ReadFile(formatCmdConfigFile)
+ if err != nil {
+ return caddy.ExitCodeFailedStartup,
+ fmt.Errorf("reading input file: %v", err)
+ }
+
+ output := caddyfile.Format(input)
+
+ if formatCmdWriteFlag {
+ err = ioutil.WriteFile(formatCmdConfigFile, output, 0644)
+ if err != nil {
+ return caddy.ExitCodeFailedStartup, nil
+ }
+ } else {
+ fmt.Print(string(output))
+ }
+
+ return caddy.ExitCodeSuccess, nil
+}
+
func cmdHelp(fl Flags) (int, error) {
const fullDocs = `Full documentation is available at:
https://caddyserver.com/docs/command-line`
diff --git a/cmd/commands.go b/cmd/commands.go
index 87ded60..37ede3a 100644
--- a/cmd/commands.go
+++ b/cmd/commands.go
@@ -242,6 +242,24 @@ provisioning stages.`,
}(),
})
+ RegisterCommand(Command{
+ Name: "fmt",
+ Func: cmdFormatConfig,
+ Usage: "[--write] [<path>]",
+ Short: "Formats a Caddyfile",
+ Long: `
+Formats the Caddyfile by adding proper indentation and spaces to improve
+human readability. It prints the result to stdout.
+
+If --write is specified, the output will be written to the config file
+directly instead of printing it.`,
+ Flags: func() *flag.FlagSet {
+ fs := flag.NewFlagSet("format", flag.ExitOnError)
+ fs.Bool("write", false, "Over-write the output to specified file")
+ return fs
+ }(),
+ })
+
}
// RegisterCommand registers the command cmd.