|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +var diffCmd = &cobra.Command{ |
| 14 | + Use: "diff <patch>", |
| 15 | + Short: "Show the diff between the current file and the patch content", |
| 16 | + Args: cobra.ExactArgs(1), |
| 17 | + Run: func(cmd *cobra.Command, args []string) { |
| 18 | + patchFile := args[0] |
| 19 | + |
| 20 | + f, err := os.Open(patchFile) |
| 21 | + if err != nil { |
| 22 | + fmt.Println("Error reading patch file:", err) |
| 23 | + os.Exit(1) |
| 24 | + } |
| 25 | + defer f.Close() |
| 26 | + |
| 27 | + var targetFile string |
| 28 | + var inContent bool |
| 29 | + var patchContent []byte |
| 30 | + |
| 31 | + scanner := bufio.NewScanner(f) |
| 32 | + for scanner.Scan() { |
| 33 | + line := scanner.Text() |
| 34 | + if strings.HasPrefix(line, "TARGET") { |
| 35 | + parts := strings.SplitN(line, "=", 2) |
| 36 | + targetFile = strings.TrimSpace(parts[1]) |
| 37 | + } |
| 38 | + if strings.HasPrefix(line, "--- PATCH CONTENT ---") { |
| 39 | + inContent = true |
| 40 | + continue |
| 41 | + } |
| 42 | + if inContent { |
| 43 | + patchContent = append(patchContent, []byte(line+"\n")...) |
| 44 | + } |
| 45 | + } |
| 46 | + if err := scanner.Err(); err != nil { |
| 47 | + fmt.Println("Error reading patch file:", err) |
| 48 | + os.Exit(1) |
| 49 | + } |
| 50 | + |
| 51 | + if targetFile == "" { |
| 52 | + fmt.Println("Malformed patch file: missing TARGET") |
| 53 | + os.Exit(1) |
| 54 | + } |
| 55 | + |
| 56 | + currentContent, err := os.ReadFile(targetFile) |
| 57 | + if err != nil { |
| 58 | + fmt.Println("Error reading target file:", err) |
| 59 | + os.Exit(1) |
| 60 | + } |
| 61 | + |
| 62 | + // Simple line-by-line diff |
| 63 | + currentLines := bytes.Split(currentContent, []byte("\n")) |
| 64 | + patchLines := bytes.Split(patchContent, []byte("\n")) |
| 65 | + |
| 66 | + max := len(currentLines) |
| 67 | + if len(patchLines) > max { |
| 68 | + max = len(patchLines) |
| 69 | + } |
| 70 | + for i := 0; i < max; i++ { |
| 71 | + var cur, pat []byte |
| 72 | + if i < len(currentLines) { |
| 73 | + cur = currentLines[i] |
| 74 | + } |
| 75 | + if i < len(patchLines) { |
| 76 | + pat = patchLines[i] |
| 77 | + } |
| 78 | + if !bytes.Equal(cur, pat) { |
| 79 | + fmt.Printf("-%s\n+%s\n", cur, pat) |
| 80 | + } |
| 81 | + } |
| 82 | + }, |
| 83 | +} |
| 84 | + |
| 85 | +func init() { |
| 86 | + rootCmd.AddCommand(diffCmd) |
| 87 | +} |
0 commit comments