gunk-dev/the-valley

project.go

sourcee4e4f8eff586main's published tip history
13.4 KiB
1package export
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "sort"
8 "strings"
9 "unicode"
10 "unicode/utf8"
11)
12
13// The schemas of the valley's own JSON the projection reads.
14const (
15 planSchema = "valley-plan/v1"
16 pendingSchema = "valley-pending/v1"
17 detailSchema = "valley-knot/v1"
18)
19
20// ErrInconsistent is the error for inputs read at different graph tips: a
21// knot's detail read after the plan saw a later graph. The publisher reads
22// the inputs again rather than publish them.
23var ErrInconsistent = errors.New("the inputs were read at different graph tips")
24
25// Inputs are what the projection reads: the valley's own JSON, as its
26// commands print it, and the publisher's configuration.
27type Inputs struct {
28 // Plan is `valley plan --all --json`.
29 Plan []byte
30 // Pending is `valley pending --all --json`.
31 Pending []byte
32 // Details are `valley knot show --project P <id> --json`, one for
33 // every knot of every public project.
34 Details [][]byte
35 // Visibility is each project's visibility. A project it does not name
36 // is not exported.
37 Visibility map[string]Visibility
38 // SourceTips are each public project's main.
39 SourceTips map[string]string
40 // Principals is the display mapping principal names pass through.
41 Principals Principals
42}
43
44// Principals maps a principal's name to what an export shows in its place,
45// such as operator or agent. A name it does not map is shown as Unmapped.
46type Principals map[string]string
47
48// Unmapped is what an export shows for a principal the display mapping
49// does not name.
50const Unmapped = "contributor"
51
52// Show is what an export shows for the principal name: its mapping, or
53// Unmapped. The empty name, for a field that names nobody, stays empty.
54func (p Principals) Show(name string) string {
55 if name == "" {
56 return ""
57 }
58 if shown, ok := p[name]; ok {
59 return shown
60 }
61 return Unmapped
62}
63
64// check holds every shown name to 1 to 64 bytes of UTF-8 with no control
65// character.
66func (p Principals) check() error {
67 for name, shown := range p {
68 bad := len(shown) == 0 || len(shown) > 64 || !utf8.ValidString(shown) ||
69 containsControl(shown)
70 if bad {
71 return fmt.Errorf("the display mapping shows %q as %q; a shown name is 1 to 64 bytes of text, with no control character", name, shown)
72 }
73 }
74 return nil
75}
76
77func containsControl(s string) bool {
78 for _, r := range s {
79 if unicode.IsControl(r) {
80 return true
81 }
82 }
83 return false
84}
85
86// The valley's JSON, as far as the projection reads it. A field not named
87// here is never read, so a field the valley adds is not exported until the
88// projection names it.
89type (
90 planDoc struct {
91 Schema string `json:"schema"`
92 Now string `json:"now"`
93 Projects []planProject `json:"projects"`
94 }
95 planProject struct {
96 Project string `json:"project"`
97 Error *string `json:"error"`
98 Tip string `json:"tip"`
99 Roots []string `json:"roots"`
100 Knots []planKnot `json:"knots"`
101 InFlight []string `json:"in_flight"`
102 OpenResiduals []Residuals `json:"open_residuals"`
103 }
104 planKnot struct {
105 ID string `json:"id"`
106 Type string `json:"type"`
107 Status string `json:"status"`
108 Active bool `json:"active"`
109 Title string `json:"title"`
110 Created string `json:"created"`
111 CreatedBy string `json:"created_by"`
112 Source string `json:"source"`
113 Parent string `json:"parent"`
114 Owner string `json:"owner"`
115 BlockedBy []string `json:"blocked_by"`
116 Changes []string `json:"changes"`
117 Target string `json:"target"`
118 GraduatedInto string `json:"graduated_into"`
119 CommentCount int `json:"comment_count"`
120 State string `json:"state"`
121 Ready bool `json:"ready"`
122 WaitingOn []string `json:"waiting_on"`
123 ClearedByEnding []string `json:"cleared_by_ending"`
124 Dangling []string `json:"dangling"`
125 Unresolved []string `json:"unresolved"`
126 Children []string `json:"children"`
127 Blocks []string `json:"blocks"`
128 Progress *Progress `json:"progress"`
129 Claim *Claim `json:"claim"`
130 Edges []Edge `json:"edges"`
131 }
132 detailDoc struct {
133 Schema string `json:"schema"`
134 Project string `json:"project"`
135 Tip string `json:"tip"`
136 Knot struct {
137 ID string `json:"id"`
138 Body *string `json:"body"`
139 Comments []Comment `json:"comments"`
140 } `json:"knot"`
141 }
142 pendingDoc struct {
143 Schema string `json:"schema"`
144 Repos []pendingRepo `json:"repos"`
145 }
146 pendingRepo struct {
147 Repo string `json:"repo"`
148 Error *string `json:"error"`
149 Changes []pendingChange `json:"changes"`
150 }
151 pendingChange struct {
152 ChangeID string `json:"change_id"`
153 Handle string `json:"handle"`
154 Target string `json:"target"`
155 Owner string `json:"owner"`
156 State string `json:"state"`
157 Active int `json:"active"`
158 Versions []pendingVersion `json:"versions"`
159 Includes []string `json:"includes"`
160 Knots []KnotRef `json:"knots"`
161 }
162 pendingVersion struct {
163 N int `json:"n"`
164 Head string `json:"head"`
165 Title string `json:"title"`
166 Uploader string `json:"uploader"`
167 Landing string `json:"landing"`
168 Request *struct {
169 Commit string `json:"commit"`
170 } `json:"request"`
171 Outcome *Outcome `json:"outcome"`
172 }
173)
174
175// detailKey names a knot's detail: IDs are unique within a project, not
176// across projects.
177type detailKey struct{ project, id string }
178
179// Build projects the valley's JSON onto the public export. It is a pure
180// function of its inputs. It exports each project whose visibility is
181// public, and everything of it an anonymous reader may see: every knot,
182// with its body and comments, and the changes ready for approval, each
183// with its active version alone. It leaves out what is not the reader's:
184// the plan's operator sections, drafts, branches, older versions,
185// repository URLs, error text and the file each knot is stored in. A
186// reference to a project that is not exported keeps only the reference,
187// and every principal name passes through the display mapping.
188//
189// A public project whose plan or pending listing could not be read, whose
190// knot lacks its detail, or whose detail was read at another graph tip
191// fails the projection, so a partial export is never published. The last
192// of these is ErrInconsistent.
193func Build(in Inputs) (*Export, error) {
194 if err := in.Principals.check(); err != nil {
195 return nil, err
196 }
197 var plan planDoc
198 if err := decodeInput("the plan", in.Plan, planSchema, &plan, &plan.Schema); err != nil {
199 return nil, err
200 }
201 var pending pendingDoc
202 if err := decodeInput("the pending listing", in.Pending, pendingSchema, &pending, &pending.Schema); err != nil {
203 return nil, err
204 }
205 details := map[detailKey]detailDoc{}
206 for _, raw := range in.Details {
207 var d detailDoc
208 if err := decodeInput("a knot's detail", raw, detailSchema, &d, &d.Schema); err != nil {
209 return nil, err
210 }
211 key := detailKey{d.Project, d.Knot.ID}
212 if _, twice := details[key]; twice {
213 return nil, fmt.Errorf("the details hold knot %s:%s twice", d.Project, d.Knot.ID)
214 }
215 details[key] = d
216 }
217
218 exported := map[string]bool{}
219 for name, v := range in.Visibility {
220 switch v {
221 case Public:
222 exported[name] = true
223 default:
224 return nil, fmt.Errorf("project %s has visibility %q; v1 exports public projects alone", name, v)
225 }
226 }
227 planned := map[string]planProject{}
228 for _, p := range plan.Projects {
229 planned[p.Project] = p
230 }
231 repos := map[string]pendingRepo{}
232 for _, r := range pending.Repos {
233 repos[r.Repo] = r
234 }
235
236 e := &Export{Schema: Schema, Collected: plan.Now, Projects: []Project{}}
237 var names []string
238 for name := range exported {
239 names = append(names, name)
240 }
241 sort.Strings(names)
242 for _, name := range names {
243 p, ok := planned[name]
244 if !ok {
245 return nil, fmt.Errorf("public project %s is not in the plan", name)
246 }
247 if p.Error != nil {
248 return nil, fmt.Errorf("the plan could not read public project %s", name)
249 }
250 r, ok := repos[name]
251 if !ok {
252 return nil, fmt.Errorf("public project %s is not in the pending listing", name)
253 }
254 if r.Error != nil {
255 return nil, fmt.Errorf("the pending listing could not read public project %s", name)
256 }
257 out, err := project(name, p, r, details, exported, in)
258 if err != nil {
259 return nil, err
260 }
261 e.Projects = append(e.Projects, out)
262 }
263 if err := e.Validate(); err != nil {
264 return nil, err
265 }
266 return e, nil
267}
268
269func project(name string, p planProject, r pendingRepo, details map[detailKey]detailDoc,
270 exported map[string]bool, in Inputs) (Project, error) {
271 shown := in.Principals.Show
272 tip := in.SourceTips[name]
273 if !ValidObjectID(tip) {
274 return Project{}, fmt.Errorf("public project %s has no source tip, or one that is not an object ID", name)
275 }
276 out := Project{
277 Name: name, Visibility: Public, GraphTip: p.Tip, SourceTip: tip,
278 Roots: nonNil(p.Roots), Knots: []Knot{}, OpenResiduals: []Residuals{}, Changes: []Change{},
279 }
280 for _, g := range p.OpenResiduals {
281 out.OpenResiduals = append(out.OpenResiduals, Residuals{Parent: g.Parent, Bugs: nonNil(g.Bugs)})
282 }
283
284 // A reference to another project's knot is hidden when that project
285 // is not exported. Each list of the view a hidden reference appears in
286 // says something of the knot's status, so it is dropped from them all.
287 hidden := func(ref string) bool {
288 project, _, qualified := strings.Cut(ref, ":")
289 return qualified && !exported[project]
290 }
291 var inProgress []string
292 inFlight := map[string]bool{}
293 for _, id := range p.InFlight {
294 inFlight[id] = true
295 }
296 for _, k := range p.Knots {
297 d, ok := details[detailKey{name, k.ID}]
298 if !ok {
299 return Project{}, fmt.Errorf("knot %s:%s has no detail", name, k.ID)
300 }
301 if d.Tip != p.Tip {
302 return Project{}, fmt.Errorf("%w: the plan read %s at %s, and knot %s at %s", ErrInconsistent, name, p.Tip, k.ID, d.Tip)
303 }
304 if d.Knot.Body == nil {
305 return Project{}, fmt.Errorf("the detail of knot %s:%s holds no body", name, k.ID)
306 }
307 if len(d.Knot.Comments) != k.CommentCount {
308 return Project{}, fmt.Errorf("%w: the plan counts %d comments on %s:%s, and its detail holds %d", ErrInconsistent, k.CommentCount, name, k.ID, len(d.Knot.Comments))
309 }
310 x := Knot{
311 ID: k.ID, Type: k.Type, Status: k.Status, Active: k.Active, Title: k.Title,
312 Created: k.Created, CreatedBy: shown(k.CreatedBy), Source: k.Source, Parent: k.Parent,
313 Owner: shown(k.Owner), BlockedBy: nonNil(k.BlockedBy), Changes: nonNil(k.Changes),
314 Target: k.Target, GraduatedInto: k.GraduatedInto,
315 State: k.State, Ready: k.Ready,
316 WaitingOn: drop(k.WaitingOn, hidden), ClearedByEnding: drop(k.ClearedByEnding, hidden),
317 Dangling: drop(k.Dangling, hidden), Unresolved: drop(k.Unresolved, hidden),
318 Children: nonNil(k.Children), Blocks: nonNil(k.Blocks), Progress: k.Progress,
319 Edges: []Edge{}, Body: *d.Knot.Body, Comments: []Comment{}, CommentCount: k.CommentCount,
320 }
321 if k.Claim != nil {
322 c := *k.Claim
323 c.By = shown(c.By)
324 x.Claim = &c
325 }
326 for _, edge := range k.Edges {
327 if !exported[edge.Project] {
328 edge = Edge{Field: edge.Field, Ref: edge.Ref, Project: edge.Project, ID: edge.ID, State: EdgeHidden}
329 }
330 x.Edges = append(x.Edges, edge)
331 }
332 for _, c := range d.Knot.Comments {
333 c.Author = shown(c.Author)
334 x.Comments = append(x.Comments, c)
335 }
336 if k.Active && k.Status == "in-progress" && !inFlight[k.ID] {
337 inProgress = append(inProgress, k.ID)
338 }
339 out.Knots = append(out.Knots, x)
340 }
341 out.InFlight = append(nonNil(p.InFlight), inProgress...)
342
343 // includes may name a draft, which the export does not carry.
344 listed := map[string]bool{}
345 for _, c := range r.Changes {
346 listed[c.ChangeID] = true
347 }
348 for _, c := range r.Changes {
349 if c.State != "ready" {
350 return Project{}, fmt.Errorf("the pending listing holds change %s of %s, which is %s, among the ready changes", c.ChangeID, name, c.State)
351 }
352 var active *pendingVersion
353 for i := range c.Versions {
354 if c.Versions[i].N == c.Active {
355 active = &c.Versions[i]
356 }
357 }
358 if active == nil {
359 return Project{}, fmt.Errorf("change %s of %s holds no version %d, its active one", c.ChangeID, name, c.Active)
360 }
361 v := Version{N: active.N, Head: active.Head, Title: active.Title, Uploader: shown(active.Uploader),
362 Landing: active.Landing, Outcome: active.Outcome}
363 if active.Request != nil {
364 v.Request = &Request{Commit: active.Request.Commit}
365 }
366 out.Changes = append(out.Changes, Change{
367 ChangeID: c.ChangeID, Handle: c.Handle, Target: c.Target, Owner: shown(c.Owner), Version: v,
368 Includes: drop(c.Includes, func(id string) bool { return !listed[id] }), Knots: nonNilRefs(c.Knots),
369 })
370 }
371 return out, nil
372}
373
374// decodeInput reads one of the valley's documents and checks its schema.
375func decodeInput(what string, raw []byte, schema string, into any, got *string) error {
376 if err := json.Unmarshal(raw, into); err != nil {
377 return fmt.Errorf("%s: %w", what, err)
378 }
379 if *got != schema {
380 return fmt.Errorf("%s has schema %q, not %q", what, *got, schema)
381 }
382 return nil
383}
384
385// drop is list without the entries hidden reports, never nil.
386func drop(list []string, hidden func(string) bool) []string {
387 kept := []string{}
388 for _, s := range list {
389 if !hidden(s) {
390 kept = append(kept, s)
391 }
392 }
393 return kept
394}
395
396func nonNil(list []string) []string {
397 if list == nil {
398 return []string{}
399 }
400 return list
401}
402
403func nonNilRefs(list []KnotRef) []KnotRef {
404 if list == nil {
405 return []KnotRef{}
406 }
407 return list
408}