gunk-dev/the-valley

export.go

sourcea9ea3ba977damain's published tip history
10.5 KiB
1package export
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12
13 "the-valley/knot"
14)
15
16// Schema is the export.json document's schema. A change to any field's
17// name or meaning is a new schema version.
18const Schema = "valley-web-export/v1"
19
20// Visibility is who may read an exported project. Public is the only
21// visibility v1 carries: the export holds what an anonymous reader may see.
22type Visibility string
23
24const Public Visibility = "public"
25
26// Export is export.json: every public project of one valley, as an
27// anonymous reader may see it.
28type Export struct {
29 Schema string `json:"schema"`
30 // Collected is when the plan was read (valley-plan/v1's now), in
31 // RFC 3339. It is display-time: the content digest leaves it out.
32 Collected string `json:"collected"`
33 Projects []Project `json:"projects"`
34}
35
36// Project is one exported project. Its two tips are different refs: the
37// graph tip is refs/the-valley/knots, which its knots were read at, and
38// the source tip is main, which its bundle carries.
39type Project struct {
40 Name string `json:"project"`
41 Visibility Visibility `json:"visibility"`
42 // GraphTip is "" for a project with no plan graph.
43 GraphTip string `json:"graph_tip"`
44 SourceTip string `json:"source_tip"`
45 // Roots are the outcomes with no parent, in tree order.
46 Roots []string `json:"roots"`
47 // Knots are every knot, in tree order, each with its body and comments.
48 Knots []Knot `json:"knots"`
49 // InFlight are the active knots that are claimed, the oldest claim
50 // first, then the active knots whose status is in-progress and that
51 // nobody claims, in tree order.
52 InFlight []string `json:"in_flight"`
53 OpenResiduals []Residuals `json:"open_residuals"`
54 // Changes are the changes ready for approval: ready, with an active
55 // version that has not landed.
56 Changes []Change `json:"changes"`
57}
58
59// Knot is one knot: its fields, what the graph derives of it, its edges to
60// other projects' knots, and its body and comments. Every principal name
61// in it has passed through the publisher's display mapping.
62type Knot struct {
63 ID string `json:"id"`
64 Type string `json:"type"`
65 Status string `json:"status"`
66 Active bool `json:"active"`
67 Title string `json:"title"`
68 Created string `json:"created"`
69 CreatedBy string `json:"created_by"`
70 Source string `json:"source,omitempty"`
71 Parent string `json:"parent,omitempty"`
72 Owner string `json:"owner,omitempty"`
73 BlockedBy []string `json:"blocked_by"`
74 Changes []string `json:"changes"`
75 Target string `json:"target,omitempty"`
76 GraduatedInto string `json:"graduated_into,omitempty"`
77
78 // State is valley-plan/v1's: ready, in-progress, blocked, active,
79 // done or abandoned.
80 State string `json:"state"`
81 Ready bool `json:"ready"`
82 WaitingOn []string `json:"waiting_on"`
83 ClearedByEnding []string `json:"cleared_by_ending"`
84 Dangling []string `json:"dangling"`
85 Unresolved []string `json:"unresolved"`
86 Children []string `json:"children"`
87 Blocks []string `json:"blocks"`
88 Progress *Progress `json:"progress,omitempty"`
89 Claim *Claim `json:"claim,omitempty"`
90 Edges []Edge `json:"edges"`
91
92 Body string `json:"body"`
93 Comments []Comment `json:"comments"`
94 CommentCount int `json:"comment_count"`
95}
96
97// Progress is a parent's finished descendants, out of those not abandoned.
98type Progress struct {
99 Done int `json:"done"`
100 Of int `json:"of"`
101}
102
103// Claim is a knot's claim. AgeSeconds and Stale are as of Collected; they
104// are display-time, and a reader derives a claim's age from At.
105type Claim struct {
106 By string `json:"by"`
107 At string `json:"at"`
108 AgeSeconds int64 `json:"age_seconds"`
109 Stale bool `json:"stale"`
110}
111
112// Edge is a reference to another project's knot, from blocked_by or
113// target. State is resolved or dangling, as valley-plan/v1 says, or hidden
114// when the project is not exported. A hidden edge carries the reference
115// alone: no status, no title and no why.
116type Edge struct {
117 Field string `json:"field"`
118 Ref string `json:"ref"`
119 Project string `json:"project"`
120 ID string `json:"id"`
121 State string `json:"state"`
122 Why *string `json:"why"`
123 Status *string `json:"status"`
124 Title *string `json:"title"`
125}
126
127// Edge states.
128const (
129 EdgeResolved = "resolved"
130 EdgeDangling = "dangling"
131 EdgeHidden = "hidden"
132)
133
134// Comment is one comment on a knot, oldest first. Op is the operation that
135// wrote it, which with the knot names the comment. A comment that has been
136// edited says when it was last edited, in Edited, and by whom, in
137// EditedBy; one never edited has neither.
138type Comment struct {
139 Author string `json:"author"`
140 At string `json:"at"`
141 Op string `json:"op"`
142 Edited string `json:"edited,omitempty"`
143 EditedBy string `json:"edited_by,omitempty"`
144 Body string `json:"body"`
145}
146
147// Residuals are the open bugs under one parent, or under none.
148type Residuals struct {
149 Parent *string `json:"parent"`
150 Bugs []string `json:"bugs"`
151}
152
153// Change is a change ready for approval, with its active version alone.
154type Change struct {
155 ChangeID string `json:"change_id"`
156 Handle string `json:"handle"`
157 Target string `json:"target"`
158 Owner string `json:"owner"`
159 Version Version `json:"version"`
160 // Includes are the changes this one includes that the export carries.
161 Includes []string `json:"includes"`
162 Knots []KnotRef `json:"knots"`
163}
164
165// Version is a change's active version.
166type Version struct {
167 N int `json:"n"`
168 Head string `json:"head"`
169 Title string `json:"title"`
170 Uploader string `json:"uploader"`
171 // Landing is not-landed or uncertain: a ready change's active version
172 // has not landed.
173 Landing string `json:"landing"`
174 Request *Request `json:"request"`
175 Outcome *Outcome `json:"outcome"`
176}
177
178// Request is the integration request that approves the version's head.
179type Request struct {
180 Commit string `json:"commit"`
181}
182
183// Outcome is the integrator's last decision about the version.
184type Outcome struct {
185 Decision string `json:"decision"`
186 Head string `json:"head"`
187 Tip *string `json:"tip"`
188}
189
190// KnotRef is a knot of the same project that links a change.
191type KnotRef struct {
192 ID string `json:"id"`
193 Type string `json:"type"`
194 Status string `json:"status"`
195 Title string `json:"title"`
196}
197
198// Encode writes the export as export.json's bytes: compact JSON and a
199// closing newline.
200func (e *Export) Encode() ([]byte, error) {
201 if err := e.Validate(); err != nil {
202 return nil, err
203 }
204 b, err := json.Marshal(e)
205 if err != nil {
206 return nil, err
207 }
208 return append(b, '\n'), nil
209}
210
211// Decode reads export.json strictly: a field the schema does not name,
212// anything but white space after the document, or an export Validate
213// refuses, fails the read.
214func Decode(data []byte) (*Export, error) {
215 dec := json.NewDecoder(bytes.NewReader(data))
216 dec.DisallowUnknownFields()
217 var e Export
218 if err := dec.Decode(&e); err != nil {
219 return nil, fmt.Errorf("export.json: %w", err)
220 }
221 // More reports false at a closing bracket or brace, so only a second
222 // Decode that finds the end of the input proves there is nothing after
223 // the document.
224 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
225 return nil, errors.New("export.json holds more than its one document")
226 }
227 if err := e.Validate(); err != nil {
228 return nil, err
229 }
230 return &e, nil
231}
232
233// Validate holds an export to what a server may route by and show without
234// further checks: its schema, project names that are safe as file names,
235// one entry per project in name order, object IDs for tips, and knot IDs
236// that are unique within their project. Text fields are valid UTF-8 with
237// no control character other than a newline or a tab.
238func (e *Export) Validate() error {
239 if e.Schema != Schema {
240 return fmt.Errorf("export.json has schema %q, not %q", e.Schema, Schema)
241 }
242 for i, p := range e.Projects {
243 if !ValidName(p.Name) {
244 return fmt.Errorf("export.json names a project %q, which is not a project name", p.Name)
245 }
246 if i > 0 && e.Projects[i-1].Name >= p.Name {
247 return fmt.Errorf("export.json lists project %s out of order or twice", p.Name)
248 }
249 if p.Visibility != Public {
250 return fmt.Errorf("project %s has visibility %q; v1 exports public projects alone", p.Name, p.Visibility)
251 }
252 if p.GraphTip != "" && !ValidObjectID(p.GraphTip) {
253 return fmt.Errorf("project %s has graph tip %q, which is not an object ID", p.Name, p.GraphTip)
254 }
255 if !ValidObjectID(p.SourceTip) {
256 return fmt.Errorf("project %s has source tip %q, which is not an object ID", p.Name, p.SourceTip)
257 }
258 seen := map[string]bool{}
259 for _, k := range p.Knots {
260 if !knot.IsLocalID(k.ID) {
261 return fmt.Errorf("project %s holds a knot %q, which is not a knot ID", p.Name, k.ID)
262 }
263 if seen[k.ID] {
264 return fmt.Errorf("project %s holds knot %s twice", p.Name, k.ID)
265 }
266 seen[k.ID] = true
267 for _, s := range []string{k.Title, k.Body, k.Source, k.CreatedBy, k.Owner} {
268 if !validText(s) {
269 return fmt.Errorf("knot %s:%s holds text that is not valid UTF-8 or holds a control character", p.Name, k.ID)
270 }
271 }
272 for _, c := range k.Comments {
273 if !validText(c.Body) || !validText(c.Author) || !validText(c.EditedBy) || !validText(c.Edited) {
274 return fmt.Errorf("a comment on knot %s:%s holds text that is not valid UTF-8 or holds a control character", p.Name, k.ID)
275 }
276 }
277 }
278 for _, c := range p.Changes {
279 if !ValidObjectID(c.Version.Head) {
280 return fmt.Errorf("change %s of project %s has head %q, which is not an object ID", c.ChangeID, p.Name, c.Version.Head)
281 }
282 }
283 }
284 return nil
285}
286
287// ValidName reports whether s is a project's name: the plan graph's rule
288// for a project's or a principal's name. Such a name holds no slash and
289// cannot be a dot segment, so it is safe as a file name.
290func ValidName(s string) bool { return knot.IsName(s) }
291
292// ValidObjectID reports whether s is a full git object ID, SHA-1 or
293// SHA-256, in lowercase hex.
294func ValidObjectID(s string) bool {
295 return (len(s) == 40 || len(s) == 64) && isHex(s)
296}
297
298func isHex(s string) bool {
299 for _, c := range []byte(s) {
300 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
301 return false
302 }
303 }
304 return true
305}
306
307// validText is valid UTF-8 holding no control character but a newline or
308// a tab.
309func validText(s string) bool {
310 return utf8.ValidString(s) && !strings.ContainsFunc(s, func(r rune) bool {
311 return unicode.IsControl(r) && r != '\n' && r != '\t'
312 })
313}