| 683 | } |
| 684 | |
| 685 | func cmdFmt(fl Flags) (int, error) { |
| 686 | configFile := fl.Arg(0) |
| 687 | configFlag := fl.String("config") |
| 688 | if (len(fl.Args()) > 1) || (configFlag != "" && configFile != "") { |
| 689 | return caddy.ExitCodeFailedStartup, fmt.Errorf("fmt does not support multiple files %s %s", configFlag, strings.Join(fl.Args(), " ")) |
| 690 | } |
| 691 | if configFile == "" && configFlag == "" { |
| 692 | configFile = "Caddyfile" |
| 693 | } else if configFile == "" { |
| 694 | configFile = configFlag |
| 695 | } |
| 696 | // as a special case, read from stdin if the file name is "-" |
| 697 | if configFile == "-" { |
| 698 | input, err := io.ReadAll(os.Stdin) |
| 699 | if err != nil { |
| 700 | return caddy.ExitCodeFailedStartup, |
| 701 | fmt.Errorf("reading stdin: %v", err) |
| 702 | } |
| 703 | fmt.Print(string(caddyfile.Format(input))) |
| 704 | return caddy.ExitCodeSuccess, nil |
| 705 | } |
| 706 | |
| 707 | input, err := os.ReadFile(configFile) |
| 708 | if err != nil { |
| 709 | return caddy.ExitCodeFailedStartup, |
| 710 | fmt.Errorf("reading input file: %v", err) |
| 711 | } |
| 712 | |
| 713 | output := caddyfile.Format(input) |
| 714 | |
| 715 | if fl.Bool("overwrite") { |
| 716 | if err := os.WriteFile(configFile, output, 0o600); err != nil { //nolint:gosec // path traversal is not really a thing here, this is either "Caddyfile" or admin-controlled |
| 717 | return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err) |
| 718 | } |
| 719 | return caddy.ExitCodeSuccess, nil |
| 720 | } |
| 721 | |
| 722 | if fl.Bool("diff") { |
| 723 | diff := difflib.Diff( |
| 724 | strings.Split(string(input), "\n"), |
| 725 | strings.Split(string(output), "\n")) |
| 726 | for _, d := range diff { |
| 727 | switch d.Delta { |
| 728 | case difflib.Common: |
| 729 | fmt.Printf(" %s\n", d.Payload) |
| 730 | case difflib.LeftOnly: |
| 731 | fmt.Printf("- %s\n", d.Payload) |
| 732 | case difflib.RightOnly: |
| 733 | fmt.Printf("+ %s\n", d.Payload) |
| 734 | } |
| 735 | } |
| 736 | } else { |
| 737 | fmt.Print(string(output)) |
| 738 | } |
| 739 | |
| 740 | if warning, diff := caddyfile.FormattingDifference(configFile, input); diff { |
| 741 | return caddy.ExitCodeFailedStartup, fmt.Errorf(`%s:%d: Caddyfile input is not formatted; Tip: use '--overwrite' to update your Caddyfile in-place instead of previewing it. Consult '--help' for more options`, |
| 742 | warning.File, |