|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + |
| 8 | + "github.com/numtide/treefmt/v2/cmd/format" |
| 9 | + "github.com/numtide/treefmt/v2/stats" |
| 10 | + "github.com/spf13/cobra" |
| 11 | + "github.com/spf13/viper" |
| 12 | +) |
| 13 | + |
| 14 | +// gitMergetool handles a 3-way merge using `git merge-file` and formats the resulting merged file. |
| 15 | +// It expects 4 arguments: current, base, other, and merged filenames. |
| 16 | +// Returns an error if the process fails or if arguments are invalid. |
| 17 | +func gitMergetool( |
| 18 | + v *viper.Viper, |
| 19 | + statz *stats.Stats, |
| 20 | + cmd *cobra.Command, |
| 21 | + args []string, |
| 22 | +) error { |
| 23 | + if len(args) != 4 { |
| 24 | + return fmt.Errorf("expected 4 arguments, got %d", len(args)) |
| 25 | + } |
| 26 | + |
| 27 | + current := args[0] |
| 28 | + base := args[1] |
| 29 | + other := args[2] |
| 30 | + merged := args[3] |
| 31 | + |
| 32 | + // run treefmt on the first three arguments: current, base and other |
| 33 | + _, _ = fmt.Fprintf(os.Stderr, "formatting: %s, %s, %s\n\n", current, base, other) |
| 34 | + |
| 35 | + //nolint:wrapcheck |
| 36 | + if err := format.Run(v, statz, cmd, args[:3]); err != nil { |
| 37 | + return err |
| 38 | + } |
| 39 | + |
| 40 | + // open merge file |
| 41 | + mergeFile, err := os.OpenFile(merged, os.O_WRONLY|os.O_CREATE, 0o600) |
| 42 | + if err != nil { |
| 43 | + return fmt.Errorf("failed to open merge file: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + // merge current base and other |
| 47 | + merge := exec.Command("git", "merge-file", "--stdout", current, base, other) |
| 48 | + _, _ = fmt.Fprintf(os.Stderr, "\n%s\n", merge.String()) |
| 49 | + |
| 50 | + // redirect stdout to the merge file |
| 51 | + merge.Stdout = mergeFile |
| 52 | + // capture stderr |
| 53 | + merge.Stderr = os.Stderr |
| 54 | + |
| 55 | + if err = merge.Run(); err != nil { |
| 56 | + return fmt.Errorf("failed to run git merge-file: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + // close the merge file |
| 60 | + if err = mergeFile.Close(); err != nil { |
| 61 | + return fmt.Errorf("failed to close temporary merge file: %w", err) |
| 62 | + } |
| 63 | + |
| 64 | + // format the merge file |
| 65 | + _, _ = fmt.Fprintf(os.Stderr, "formatting: %s\n\n", mergeFile.Name()) |
| 66 | + |
| 67 | + if err = format.Run(v, stats.New(), cmd, []string{mergeFile.Name()}); err != nil { |
| 68 | + return fmt.Errorf("failed to format merged file: %w", err) |
| 69 | + } |
| 70 | + |
| 71 | + return nil |
| 72 | +} |
0 commit comments