internal/gitutil/messages.go

57c622974bf94408ba5b9267a77724221528ed2b
gitbay/internal/gitutil/messages.go history · blame · raw

41 lines · 1140 bytes

 1package gitutil
 2
 3import (
 4	"fmt"
 5	"os/exec"
 6	"strings"
 7)
 8
 9const zeroSHA = "0000000000000000000000000000000000000000"
10
11type CommitMsg struct {
12	SHA     string
13	Message string
14}
15
16// RevListMessages returns sha and full message for commits reachable from
17// new but not old, newest first, capped at max. An empty or zero old (new
18// branch) lists from new alone, still capped.
19func RevListMessages(dir, old, new string, max int) ([]CommitMsg, error) {
20	args := []string{"-C", dir, "rev-list", fmt.Sprintf("-n%d", max), "--format=%B%x00", new}
21	if old != "" && old != zeroSHA {
22		args = append(args, "^"+old)
23	}
24	out, err := exec.Command("git", args...).Output()
25	if err != nil {
26		return nil, fmt.Errorf("rev-list messages: %w", err)
27	}
28	var msgs []CommitMsg
29	for _, chunk := range strings.Split(string(out), "\x00") {
30		chunk = strings.TrimLeft(chunk, "\n")
31		if chunk == "" {
32			continue
33		}
34		header, body, ok := strings.Cut(chunk, "\n")
35		if !ok || !strings.HasPrefix(header, "commit ") {
36			continue
37		}
38		msgs = append(msgs, CommitMsg{SHA: strings.TrimPrefix(header, "commit "), Message: strings.TrimSpace(body)})
39	}
40	return msgs, nil
41}