← history for internal/gitrepo/diff.go
49eae49binternal/gitrepo/diff.go32 lines⬡ raw↓ download
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package gitrepo

import (
    "fmt"
    "os/exec"
    "strings"
)

// DiffCommits returns the unified diff between two refs (commits, branches,
// or tags). The second return value is the git command string for display in
// the UI (matching the pattern used by the rest of the gitrepo package), and
// the third is any error.
func DiffCommits(rp string, from, to string) (string, string, error) {
    args := []string{
        "-C", rp,
        "diff",
        "--unified=3", // 3 lines of context (standard)
        "--no-color",
        from + ".." + to,
    }
    cmd := fmt.Sprintf("git %s", strings.Join(args[2:], " "))
    out, err := exec.Command("git", args...).Output()
    if err != nil {
        // git diff exits non-zero for certain conditions; capture stderr for a
        // useful error message.
        if ee, ok := err.(*exec.ExitError); ok {
            return "", cmd, fmt.Errorf("%s", strings.TrimSpace(string(ee.Stderr)))
        }
        return "", cmd, err
    }
    return string(out), cmd, nil
}