gunk-dev/the-valley

history.go

source9e4736a353f5main's published tip history
2.6 KiB
1// Main's history, read once and kept in memory.
2//
3// A listing asks whether one commit is an ancestor of another many times
4// over: every change against every other, in valley changes and valley
5// pending. Most of the commits asked about are on main. A snapshot reads
6// main's history once, each commit with its parents, and answers those
7// questions from it, without starting git for each one.
8
9package rebase
10
11import (
12 "context"
13 "errors"
14 "strings"
15)
16
17// history is every commit main reaches, each with its parents, as
18// `git rev-list --parents <main>` lists them.
19type history struct {
20 index map[string]int // commit → its place in parents
21 parents [][]int // each commit's parents, by their places
22 // below is, for each commit walked from, every commit it reaches,
23 // itself included, as a set of places: bit i is the commit at place i.
24 below map[int][]uint64
25}
26
27// readHistory reads every commit tip reaches, with its parents. A parent
28// the listing does not also list is an error: the history read is then
29// not the history git walks.
30func readHistory(ctx context.Context, g Git, tip string) (*history, error) {
31 out, err := g.output(ctx, true, "rev-list", "--parents", tip)
32 if err != nil {
33 return nil, err
34 }
35 lines := strings.Split(out, "\n")
36 h := &history{index: make(map[string]int, len(lines)), parents: make([][]int, len(lines)), below: map[int][]uint64{}}
37 for i, line := range lines {
38 commit, _, _ := strings.Cut(line, " ")
39 if commit == "" {
40 return nil, errors.New("git listed main's history in a form this does not read")
41 }
42 h.index[commit] = i
43 }
44 for i, line := range lines {
45 for _, p := range strings.Fields(line)[1:] {
46 j, ok := h.index[p]
47 if !ok {
48 return nil, errors.New("git listed a parent outside main's history")
49 }
50 h.parents[i] = append(h.parents[i], j)
51 }
52 }
53 return h, nil
54}
55
56// has reports whether main reaches a commit.
57func (h *history) has(commit string) bool {
58 _, ok := h.index[commit]
59 return ok
60}
61
62// reaches reports whether from is to or has it as an ancestor, both
63// commits main reaches. Every commit from reaches is found once, and
64// kept.
65func (h *history) reaches(from, to string) bool {
66 i, j := h.index[from], h.index[to]
67 set, walked := h.below[i]
68 if !walked {
69 set = make([]uint64, (len(h.parents)+63)/64)
70 set[i/64] |= 1 << (i % 64)
71 for stack := []int{i}; len(stack) > 0; {
72 k := stack[len(stack)-1]
73 stack = stack[:len(stack)-1]
74 for _, p := range h.parents[k] {
75 if set[p/64]&(1<<(p%64)) == 0 {
76 set[p/64] |= 1 << (p % 64)
77 stack = append(stack, p)
78 }
79 }
80 }
81 h.below[i] = set
82 }
83 return set[j/64]&(1<<(j%64)) != 0
84}