| 1 | // Package change is the change record: the versions of one change, as the |
| 2 | // valley command writes them and the valley's push hook guards them. |
| 3 | // |
| 4 | // A change is one piece of work aimed at a target branch, with a stable |
| 5 | // ID that survives rebases. Each time its author marks a new head ready, |
| 6 | // the change gains a version. The record lists every version in order, |
| 7 | // says which one is active, and says whether the change is ready or |
| 8 | // withdrawn. |
| 9 | // |
| 10 | // A record lives at refs/the-valley/changes/<target>/<change ID>. The ref |
| 11 | // points at a record commit whose tree holds one file, record.json, in the |
| 12 | // schema valley-change-record/v1: |
| 13 | // |
| 14 | // { |
| 15 | // "schema": "valley-change-record/v1", |
| 16 | // "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz", |
| 17 | // "target": "main", |
| 18 | // "owner": "klaus-env", |
| 19 | // "state": "ready", |
| 20 | // "seq": 1, |
| 21 | // "versions": [ |
| 22 | // {"n": 1, "head": "git-sha1:<40 hex>", "title": "the head's subject", |
| 23 | // "branch": "topic", "uploader": "klaus-env"} |
| 24 | // ], |
| 25 | // "active": 1 |
| 26 | // } |
| 27 | // |
| 28 | // Reading is strict. The record must be valid UTF-8, name no key twice in |
| 29 | // any object, hold no field the schema does not, and hold nothing after |
| 30 | // the object. Every field has exactly the type above, and every integer is |
| 31 | // in range. This package is the one reading of a record: the valley |
| 32 | // command reads the record it is about to extend with it, and the hook |
| 33 | // reads both sides of every pushed update with it, so a record one of them |
| 34 | // accepts is a record the other accepts. |
| 35 | // |
| 36 | // The package depends on the standard library alone, like everything that |
| 37 | // uses it. |
| 38 | package change |
| 39 | |
| 40 | import ( |
| 41 | "bytes" |
| 42 | "encoding/json" |
| 43 | "errors" |
| 44 | "fmt" |
| 45 | "regexp" |
| 46 | "strconv" |
| 47 | "strings" |
| 48 | "unicode" |
| 49 | "unicode/utf8" |
| 50 | ) |
| 51 | |
| 52 | // Schema names the record format. |
| 53 | const Schema = "valley-change-record/v1" |
| 54 | |
| 55 | // The states a change can be in. |
| 56 | const ( |
| 57 | Ready = "ready" |
| 58 | Withdrawn = "withdrawn" |
| 59 | ) |
| 60 | |
| 61 | // The bounds a record is held to. |
| 62 | const ( |
| 63 | MaxSeq = 100000 // record updates in a change's life |
| 64 | MaxVersions = 1000 // versions of one change |
| 65 | MaxTitle = 200 // bytes in a version's title |
| 66 | ) |
| 67 | |
| 68 | // HeadPrefix opens a version's head: the head is named by its hash |
| 69 | // function and then its object ID. |
| 70 | const HeadPrefix = "git-sha1:" |
| 71 | |
| 72 | // Record is one change's record. |
| 73 | type Record struct { |
| 74 | Schema string `json:"schema"` |
| 75 | ChangeID string `json:"change_id"` |
| 76 | Target string `json:"target"` |
| 77 | Owner string `json:"owner"` |
| 78 | State string `json:"state"` |
| 79 | Seq int `json:"seq"` |
| 80 | Versions []Version `json:"versions"` |
| 81 | Active int `json:"active"` |
| 82 | } |
| 83 | |
| 84 | // Version is one head a change was marked ready at. |
| 85 | type Version struct { |
| 86 | N int `json:"n"` |
| 87 | Head string `json:"head"` |
| 88 | Title string `json:"title"` |
| 89 | Branch string `json:"branch"` |
| 90 | Uploader string `json:"uploader"` |
| 91 | } |
| 92 | |
| 93 | // ActiveVersion is the version Active names. A record that parsed always |
| 94 | // has one. |
| 95 | func (r *Record) ActiveVersion() Version { |
| 96 | return r.Versions[r.Active-1] |
| 97 | } |
| 98 | |
| 99 | // Last is the newest version. |
| 100 | func (r *Record) Last() Version { |
| 101 | return r.Versions[len(r.Versions)-1] |
| 102 | } |
| 103 | |
| 104 | // Parse reads record.json, strictly. |
| 105 | func Parse(data []byte) (*Record, error) { |
| 106 | v, err := readJSON(data) |
| 107 | if err != nil { |
| 108 | return nil, err |
| 109 | } |
| 110 | o, err := fieldsOf(v, "the record", "schema", "change_id", "target", "owner", "state", "seq", "versions", "active") |
| 111 | if err != nil { |
| 112 | return nil, err |
| 113 | } |
| 114 | r := &Record{} |
| 115 | for _, f := range []struct { |
| 116 | name string |
| 117 | into *string |
| 118 | }{ |
| 119 | {"schema", &r.Schema}, {"change_id", &r.ChangeID}, {"target", &r.Target}, |
| 120 | {"owner", &r.Owner}, {"state", &r.State}, |
| 121 | } { |
| 122 | if *f.into, err = stringOf(o[f.name], f.name); err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | } |
| 126 | if r.Seq, err = integerOf(o["seq"], "seq", MaxSeq); err != nil { |
| 127 | return nil, err |
| 128 | } |
| 129 | if r.Active, err = integerOf(o["active"], "active", MaxVersions); err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | versions := o["versions"] |
| 133 | if versions.kind != kindArray { |
| 134 | return nil, fmt.Errorf("its versions is %s, where an array is expected", versions.kind) |
| 135 | } |
| 136 | if len(versions.items) > MaxVersions { |
| 137 | return nil, fmt.Errorf("it holds %d versions, more than the %d a change may have", len(versions.items), MaxVersions) |
| 138 | } |
| 139 | for i, item := range versions.items { |
| 140 | where := fmt.Sprintf("versions[%d]", i) |
| 141 | vo, err := fieldsOf(item, where, "n", "head", "title", "branch", "uploader") |
| 142 | if err != nil { |
| 143 | return nil, err |
| 144 | } |
| 145 | var ver Version |
| 146 | if ver.N, err = integerOf(vo["n"], where+".n", MaxVersions); err != nil { |
| 147 | return nil, err |
| 148 | } |
| 149 | for _, f := range []struct { |
| 150 | name string |
| 151 | into *string |
| 152 | }{ |
| 153 | {"head", &ver.Head}, {"title", &ver.Title}, {"branch", &ver.Branch}, {"uploader", &ver.Uploader}, |
| 154 | } { |
| 155 | if *f.into, err = stringOf(vo[f.name], where+"."+f.name); err != nil { |
| 156 | return nil, err |
| 157 | } |
| 158 | } |
| 159 | r.Versions = append(r.Versions, ver) |
| 160 | } |
| 161 | if err := r.Check(); err != nil { |
| 162 | return nil, err |
| 163 | } |
| 164 | return r, nil |
| 165 | } |
| 166 | |
| 167 | // Check holds a record to everything the schema says beyond the types of |
| 168 | // its fields: the formats of its strings, the ranges of its integers, and |
| 169 | // versions numbered 1, 2, 3 with no gap. |
| 170 | func (r *Record) Check() error { |
| 171 | switch { |
| 172 | case r.Schema != Schema: |
| 173 | return fmt.Errorf("its schema is %q, where %q is expected", r.Schema, Schema) |
| 174 | case !ValidID(r.ChangeID): |
| 175 | return fmt.Errorf("its change_id %q is not a change ID: 32 letters from k to z", r.ChangeID) |
| 176 | case !ValidBranch(r.Target): |
| 177 | return fmt.Errorf("its target %q is not a branch name", r.Target) |
| 178 | case !ValidPrincipal(r.Owner): |
| 179 | return fmt.Errorf("its owner %q is not a principal name", r.Owner) |
| 180 | case r.State != Ready && r.State != Withdrawn: |
| 181 | return fmt.Errorf("its state is %q, where %q or %q is expected", r.State, Ready, Withdrawn) |
| 182 | case r.Seq < 1 || r.Seq > MaxSeq: |
| 183 | return fmt.Errorf("its seq is %d, outside 1 to %d", r.Seq, MaxSeq) |
| 184 | case len(r.Versions) == 0: |
| 185 | return errors.New("it holds no version, and a change has at least one") |
| 186 | case len(r.Versions) > MaxVersions: |
| 187 | return fmt.Errorf("it holds %d versions, more than the %d a change may have", len(r.Versions), MaxVersions) |
| 188 | case r.Active < 1 || r.Active > len(r.Versions): |
| 189 | return fmt.Errorf("its active is %d, which names none of its %d versions", r.Active, len(r.Versions)) |
| 190 | } |
| 191 | for i, v := range r.Versions { |
| 192 | where := fmt.Sprintf("versions[%d]", i) |
| 193 | switch { |
| 194 | case v.N != i+1: |
| 195 | return fmt.Errorf("its %s.n is %d, and versions are numbered 1, 2, 3 in order with no gap", where, v.N) |
| 196 | case !ValidHead(v.Head): |
| 197 | return fmt.Errorf("its %s.head %q is not %s and 40 lowercase hex digits", where, v.Head, HeadPrefix) |
| 198 | case !ValidTitle(v.Title): |
| 199 | return fmt.Errorf("its %s.title is not 1 to %d bytes free of control characters", where, MaxTitle) |
| 200 | case v.Branch != "" && !ValidBranch(v.Branch): |
| 201 | return fmt.Errorf("its %s.branch %q is not a branch name", where, v.Branch) |
| 202 | case !ValidPrincipal(v.Uploader): |
| 203 | return fmt.Errorf("its %s.uploader %q is not a principal name", where, v.Uploader) |
| 204 | } |
| 205 | } |
| 206 | return nil |
| 207 | } |
| 208 | |
| 209 | // Encode writes a record as record.json. It refuses a record Parse would |
| 210 | // refuse, so what it writes always reads back as the same record. |
| 211 | func Encode(r *Record) ([]byte, error) { |
| 212 | if err := r.Check(); err != nil { |
| 213 | return nil, fmt.Errorf("the record cannot be written: %w", err) |
| 214 | } |
| 215 | var buf bytes.Buffer |
| 216 | enc := json.NewEncoder(&buf) |
| 217 | enc.SetEscapeHTML(false) |
| 218 | enc.SetIndent("", " ") |
| 219 | if err := enc.Encode(r); err != nil { |
| 220 | return nil, err |
| 221 | } |
| 222 | return buf.Bytes(), nil |
| 223 | } |
| 224 | |
| 225 | // fieldsOf is v's fields, when v is an object holding exactly the fields |
| 226 | // named, no more and no fewer. |
| 227 | func fieldsOf(v *value, what string, names ...string) (map[string]*value, error) { |
| 228 | if v.kind != kindObject { |
| 229 | return nil, fmt.Errorf("%s is %s, where an object is expected", what, v.kind) |
| 230 | } |
| 231 | for _, key := range v.keys { |
| 232 | known := false |
| 233 | for _, n := range names { |
| 234 | known = known || key == n |
| 235 | } |
| 236 | if !known { |
| 237 | return nil, fmt.Errorf("%s holds the field %q, which the schema does not have", what, key) |
| 238 | } |
| 239 | } |
| 240 | for _, n := range names { |
| 241 | if _, ok := v.fields[n]; !ok { |
| 242 | return nil, fmt.Errorf("%s has no field %q", what, n) |
| 243 | } |
| 244 | } |
| 245 | return v.fields, nil |
| 246 | } |
| 247 | |
| 248 | func stringOf(v *value, name string) (string, error) { |
| 249 | if v.kind != kindString { |
| 250 | return "", fmt.Errorf("its %s is %s, where a string is expected", name, v.kind) |
| 251 | } |
| 252 | return v.text, nil |
| 253 | } |
| 254 | |
| 255 | // integerOf reads an integer from 1 to max. Only a plain run of digits is |
| 256 | // an integer: 3.0 and 3e0 are numbers of another type. |
| 257 | func integerOf(v *value, name string, max int) (int, error) { |
| 258 | if v.kind != kindNumber { |
| 259 | return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.kind) |
| 260 | } |
| 261 | for _, c := range []byte(v.text) { |
| 262 | if c < '0' || c > '9' { |
| 263 | return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.text) |
| 264 | } |
| 265 | } |
| 266 | n, err := strconv.Atoi(v.text) |
| 267 | if err != nil || n < 1 || n > max { |
| 268 | return 0, fmt.Errorf("its %s is %s, outside 1 to %d", name, v.text, max) |
| 269 | } |
| 270 | return n, nil |
| 271 | } |
| 272 | |
| 273 | // principalName is the shape of a principal's name (#PrincipalName in |
| 274 | // schema/valley.cue). |
| 275 | var principalName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`) |
| 276 | |
| 277 | // ValidPrincipal reports whether s is a principal's name. |
| 278 | func ValidPrincipal(s string) bool { |
| 279 | return principalName.MatchString(s) |
| 280 | } |
| 281 | |
| 282 | // ValidHead reports whether s names a head the way a version does. |
| 283 | func ValidHead(s string) bool { |
| 284 | if len(s) != len(HeadPrefix)+40 || s[:len(HeadPrefix)] != HeadPrefix { |
| 285 | return false |
| 286 | } |
| 287 | for _, c := range []byte(s[len(HeadPrefix):]) { |
| 288 | if (c < '0' || c > '9') && (c < 'a' || c > 'f') { |
| 289 | return false |
| 290 | } |
| 291 | } |
| 292 | return true |
| 293 | } |
| 294 | |
| 295 | // ValidTitle reports whether s may be a version's title: UTF-8, 1 to |
| 296 | // MaxTitle bytes, holding no control character. |
| 297 | func ValidTitle(s string) bool { |
| 298 | if len(s) < 1 || len(s) > MaxTitle || !utf8.ValidString(s) { |
| 299 | return false |
| 300 | } |
| 301 | for _, r := range s { |
| 302 | if unicode.IsControl(r) { |
| 303 | return false |
| 304 | } |
| 305 | } |
| 306 | return true |
| 307 | } |
| 308 | |
| 309 | // Title makes a version's title from a commit's subject. Each control |
| 310 | // character becomes a space, and bytes that are not UTF-8 become U+FFFD. |
| 311 | // The result is cut to MaxTitle bytes at a character boundary. A subject |
| 312 | // with nothing left is titled "(no subject)". |
| 313 | func Title(subject string) string { |
| 314 | var b strings.Builder |
| 315 | for _, r := range strings.ToValidUTF8(subject, "�") { |
| 316 | if unicode.IsControl(r) { |
| 317 | r = ' ' |
| 318 | } |
| 319 | if b.Len()+utf8.RuneLen(r) > MaxTitle { |
| 320 | break |
| 321 | } |
| 322 | b.WriteRune(r) |
| 323 | } |
| 324 | if t := strings.TrimSpace(b.String()); t != "" { |
| 325 | return t |
| 326 | } |
| 327 | return "(no subject)" |
| 328 | } |