← history for internal/gitrepo/diff.go
f861c317internal/gitrepo/diff.go42 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
33
34
35
36
37
38
39
40
41
42
/**
 * AltGit - altgit
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2026
 */

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
}