gunk-dev/the-valley

origin.go

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