internal/gitutil/messages.go

33f4fa3490944ada57c2a5c57e6650020c1afeab
gitbay/internal/gitutil/messages.go history · blame · raw

46 lines · 1340 bytes

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