@marcel91200 / caddy Mirror · read-only / commits / 6512832f
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 13, 19:15 UTC

cmd: Add `--diff` option for `caddy fmt` (#4695)

Francis Lavoie committed Apr 12, 2022 at 14:49 UTC 6512832f9f3904209ccb3c305e38ebde108083fb
2 files changed +21
cmd/commandfuncs.go
+15
@@ -32,6 +32,7 @@ import (
32 "sort"
33 "strings"
34
35 + "github.com/aryann/difflib"
36 "github.com/caddyserver/caddy/v2"
37 "github.com/caddyserver/caddy/v2/caddyconfig"
38 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
@@ -569,6 +570,20 @@ func cmdFmt(fl Flags) (int, error) {
570 if err := os.WriteFile(formatCmdConfigFile, output, 0600); err != nil {
571 return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err)
572 }
573 + } else if fl.Bool("diff") {
574 + diff := difflib.Diff(
575 + strings.Split(string(input), "\n"),
576 + strings.Split(string(output), "\n"))
577 + for _, d := range diff {
578 + switch d.Delta {
579 + case difflib.Common:
580 + fmt.Printf(" %s\n", d.Payload)
581 + case difflib.LeftOnly:
582 + fmt.Printf("- %s\n", d.Payload)
583 + case difflib.RightOnly:
584 + fmt.Printf("+ %s\n", d.Payload)
585 + }
586 + }
587 } else {
588 fmt.Print(string(output))
589 }
cmd/commands.go
+6
@@ -282,12 +282,18 @@ human readability. It prints the result to stdout.
282 If --overwrite is specified, the output will be written to the config file
283 directly instead of printing it.
284
285 +If --diff is specified, the output will be compared against the input, and
286 +lines will be prefixed with '-' and '+' where they differ. Note that
287 +unchanged lines are prefixed with two spaces for alignment, and that this
288 +is not a valid patch format.
289 +
290 If you wish you use stdin instead of a regular file, use - as the path.
291 When reading from stdin, the --overwrite flag has no effect: the result
292 is always printed to stdout.`,
293 Flags: func() *flag.FlagSet {
294 fs := flag.NewFlagSet("fmt", flag.ExitOnError)
295 fs.Bool("overwrite", false, "Overwrite the input file with the results")
296 + fs.Bool("diff", false, "Print the differences between the input file and the formatted output")
297 return fs
298 }(),
299 })