gunk-dev/the-valley

origin.go

source08dfaa862db7main's published tip history
5.9 KiB
1package rebase
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "sort"
9 "strings"
10
11 "the-valley/change"
12)
13
14// Target is the one target a change may name for now. The hook refuses a
15// record for any other.
16const Target = "main"
17
18// The namespaces of origin's integration requests, the integrator's
19// outcome records, and the attestations the evidence is kept under.
20const (
21 RequestPrefix = "refs/the-valley/integration-requests/" + Target + "/"
22 OutcomePrefix = "refs/the-valley/integration-outcomes/" + Target + "/"
23 AttestationRefs = "refs/the-valley/attestations/"
24)
25
26// RecordPatterns are the ls-remote patterns that list every record.
27var RecordPatterns = []string{change.RefPrefix + Target + "/*"}
28
29// InventoryPatterns are the ls-remote patterns of every ref a snapshot
30// reads: every branch, every record, every integration request and
31// outcome, and every attestation ref.
32var InventoryPatterns = []string{
33 "refs/heads/*",
34 change.RefPrefix + Target + "/*",
35 RequestPrefix + "*",
36 OutcomePrefix + "*",
37 AttestationRefs + "*",
38}
39
40// Origin is one ls-remote snapshot of the refs a reader reads.
41type Origin struct {
42 Refs map[string]string // ref → object ID
43}
44
45// ListOrigin takes one snapshot of origin's refs matching the patterns.
46// ls-remote matches a pattern against the tail of a ref name, so every ref
47// is compared whole afterwards.
48func ListOrigin(ctx context.Context, g Git, patterns ...string) (Origin, error) {
49 out, err := g.output(ctx, false, append([]string{"ls-remote", "--refs", "origin"}, patterns...)...)
50 if err != nil {
51 return Origin{}, errors.New("could not read origin")
52 }
53 o := Origin{Refs: map[string]string{}}
54 for _, line := range strings.Split(out, "\n") {
55 oid, ref, ok := strings.Cut(line, "\t")
56 if ok && ref != "" {
57 o.Refs[ref] = oid
58 }
59 }
60 return o, nil
61}
62
63// Changes is the ID of every change origin holds a record for, in order.
64func (o Origin) Changes() []string {
65 var ids []string
66 for ref := range o.Refs {
67 if target, id, ok := change.ParseRef(ref); ok && target == Target {
68 ids = append(ids, id)
69 }
70 }
71 sort.Strings(ids)
72 return ids
73}
74
75// Handle is the change's handle among the changes origin holds, and this
76// one, which may not be among them yet.
77func (o Origin) Handle(id string) string {
78 return change.Handle(id, append(o.Changes(), id))
79}
80
81// Fetch brings the objects named into this checkout's object store,
82// without writing FETCH_HEAD, moving a ref or fetching tags. An object
83// already here is not asked for: a fetch brings an object with everything
84// it reaches, so one that is here has what it reaches here too.
85func Fetch(ctx context.Context, g Git, oids ...string) error {
86 var query bytes.Buffer
87 for _, oid := range oids {
88 if oid != "" {
89 fmt.Fprintln(&query, oid)
90 }
91 }
92 if query.Len() == 0 {
93 return nil
94 }
95 present, _ := g.input(ctx, true, &query, "cat-file", "--batch-check=%(objectname)")
96 here := map[string]bool{}
97 for _, line := range strings.Split(present, "\n") {
98 here[line] = true
99 }
100 var stdin bytes.Buffer
101 for _, oid := range oids {
102 if oid != "" && !here[oid] {
103 fmt.Fprintln(&stdin, oid)
104 }
105 }
106 if stdin.Len() == 0 {
107 return nil
108 }
109 if _, err := g.input(ctx, false, &stdin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--stdin", "origin"); err != nil {
110 return errors.New("could not fetch from origin")
111 }
112 return nil
113}
114
115// Recorded is a change origin holds a record of: its ID, the record commit
116// origin's ref points at, and the record that commit holds.
117type Recorded struct {
118 ID string
119 Commit string
120 Record *change.Record
121}
122
123// ReadRecord reads the record a record commit holds. The commit must have
124// been fetched.
125func ReadRecord(ctx context.Context, g Git, commit string) (*change.Record, error) {
126 data, err := g.output(ctx, true, "cat-file", "blob", commit+":record.json")
127 if err != nil {
128 return nil, fmt.Errorf("the change record %s holds no record.json", short(commit))
129 }
130 r, err := change.Parse([]byte(data + "\n"))
131 if err != nil {
132 return nil, fmt.Errorf("the change record %s does not read: %v", short(commit), err)
133 }
134 return r, nil
135}
136
137// UnreadRecord is a record on origin that does not read.
138type UnreadRecord struct {
139 Ref, Commit, Why string
140}
141
142// ReadAll reads every record origin holds, in the order of their IDs. A
143// record that does not read is kept apart, in unread, and is no change for
144// any reader: the integrator treats it the same way. The hook refuses such
145// a record, so only corrupt storage holds one. err is for origin that
146// could not be read.
147func ReadAll(ctx context.Context, g Git, o Origin) (all []Recorded, unread []UnreadRecord, err error) {
148 ids := o.Changes()
149 var commits []string
150 for _, id := range ids {
151 commits = append(commits, o.Refs[change.Ref(Target, id)])
152 }
153 if err := Fetch(ctx, g, commits...); err != nil {
154 return nil, nil, err
155 }
156 for i, id := range ids {
157 r, err := ReadRecord(ctx, g, commits[i])
158 if err != nil {
159 unread = append(unread, UnreadRecord{Ref: change.Ref(Target, id), Commit: commits[i], Why: err.Error()})
160 continue
161 }
162 all = append(all, Recorded{ID: id, Commit: commits[i], Record: r})
163 }
164 return all, unread, nil
165}
166
167// HeadOf is a version's head as an object ID.
168func HeadOf(v change.Version) string {
169 return strings.TrimPrefix(v.Head, change.HeadPrefix)
170}
171
172// ChangeName is the change segment of a request ref. The integrator reads
173// a request as <prefix>/<target>/<change> and refuses a change segment
174// holding a slash (integrator/refs.go), so a branch name with one is
175// written with dashes instead. bin/valley's change_name is the same
176// mapping, and the request approve files is named by it.
177func ChangeName(branch string) string {
178 return strings.ReplaceAll(branch, "/", "-")
179}
180
181// RequestNames are the names a request for a version is filed under: its
182// branch, the way approve names one, and c-<change ID>.
183func RequestNames(id string, v change.Version) []string {
184 var names []string
185 if v.Branch != "" {
186 names = append(names, ChangeName(v.Branch))
187 }
188 return append(names, change.RequestName(id))
189}