internal/control/release.go
593 lines · 19373 bytes
19 symbols in this file
1package control
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 "regexp"
12 "strconv"
13 "strings"
14
15 "gitbay.org/gitbay/internal/gitutil"
16 "gitbay.org/gitbay/internal/policy"
17 "gitbay.org/gitbay/internal/protocol"
18 "gitbay.org/gitbay/internal/store"
19)
20
21func init() {
22 register(Command{Path: []string{"release", "create"},
23 Summary: "create a release on a tag",
24 Usage: "release create <owner/name> <tag> [--title <t>] [--notes <n> | --file -] [--format md|org]",
25 Flags: []Flag{
26 {"--title", "<t>", "the release's title", "the tag"},
27 {"--notes", "<n>", "the release notes", ""},
28 {"--file", "-", "read the release notes from stdin", ""},
29 {"--format", "md|org", "the notes' markup", "md"},
30 },
31 Examples: []string{
32 `release create krz/gitbay v1.31.0 --title "v1.31.0" --notes "flag help"`,
33 "release create krz/gitbay v1.31.0 --file - < notes.md",
34 },
35 ReadsStdin: true, Run: runReleaseCreate})
36 register(Command{Path: []string{"release", "edit"},
37 Summary: "update a release's title and notes",
38 Usage: "release edit <owner/name> <tag> [--title <t>] [--notes <n> | --file -] [--format md|org]",
39 Flags: []Flag{
40 {"--title", "<t>", "the release's new title", ""},
41 {"--notes", "<n>", "the release's new notes", ""},
42 {"--file", "-", "read the new release notes from stdin", ""},
43 {"--format", "md|org", "the notes' markup", ""},
44 },
45 Examples: []string{`release edit krz/gitbay v1.31.0 --title "v1.31.0"`},
46 ReadsStdin: true, Run: runReleaseEdit})
47 register(Command{Path: []string{"release", "list"},
48 Summary: "list releases",
49 Usage: "release list <owner/name> [--limit <n>] [--cursor <c>]",
50 Flags: []Flag{
51 {"--limit", "<n>", "rows per page", ""},
52 {"--cursor", "<c>", "continue from the previous page", ""},
53 },
54 Examples: []string{"release list krz/gitbay --limit 10"},
55 ReadOnly: true, Run: runReleaseList})
56 register(Command{Path: []string{"release", "show"},
57 Summary: "show a release with assets",
58 Usage: "release show <owner/name> <tag>",
59 Examples: []string{"release show krz/gitbay v1.30.0"},
60 ReadOnly: true, Run: runReleaseShow})
61 register(Command{Path: []string{"release", "notes"},
62 Summary: "draft notes: one line per merge request since the previous release",
63 Usage: "release notes <owner/name> <ref> [--since <tag>]",
64 Flags: []Flag{
65 {"--since", "<tag>", "the start of the range", "the previous release's tag"},
66 },
67 Examples: []string{
68 "release notes krz/gitbay main",
69 "release notes krz/gitbay v1.44.0 --since v1.43.0",
70 },
71 ReadOnly: true, Run: runReleaseNotes})
72 register(Command{Path: []string{"release", "delete"},
73 Summary: "delete a release and its assets",
74 Usage: "release delete <owner/name> <tag> --yes",
75 Flags: []Flag{
76 {"--yes", "", "confirm the permanent delete", ""},
77 },
78 Examples: []string{"release delete krz/gitbay v1.30.0 --yes"},
79 Run: runReleaseDelete})
80 register(Command{Path: []string{"release", "asset", "add"},
81 Summary: "upload an asset from stdin",
82 Usage: "release asset add <owner/name> <tag> <filename> < file",
83 Examples: []string{"release asset add krz/gitbay v1.30.0 gitbay-darwin-arm64 < gitbay-darwin-arm64"},
84 ReadsStdin: true, Run: runAssetAdd})
85 register(Command{Path: []string{"release", "asset", "get"},
86 Summary: "write an asset to stdout",
87 Usage: "release asset get <owner/name> <tag> <filename> > file",
88 Examples: []string{"release asset get krz/gitbay v1.30.0 gitbay-darwin-arm64 > gitbay-darwin-arm64"},
89 ReadOnly: true, Run: runAssetGet})
90 register(Command{Path: []string{"release", "asset", "remove"},
91 Summary: "remove an asset",
92 Usage: "release asset remove <owner/name> <tag> <filename>",
93 Examples: []string{"release asset remove krz/gitbay v1.30.0 gitbay-darwin-arm64"},
94 Run: runAssetRemove})
95}
96
97var assetNamePat = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,199}$`)
98
99// assetDir holds a release's uploaded files inside the bare repo directory,
100// so backup, transfer, and delete all carry them automatically.
101func assetDir(root string, repo store.Repo, releaseID int64) string {
102 return filepath.Join(RepoDir(root, repo.OwnerName, repo.Name), "gitbay-releases", strconv.FormatInt(releaseID, 10))
103}
104
105// releaseRef loads a release for "<owner/name> <tag>" with the permission.
106func releaseRef(c *Ctx, args []string, perm func(store.User, store.Repo, string) bool) (store.Repo, store.Release, int) {
107 if len(args) < 2 {
108 return store.Repo{}, store.Release{}, c.usageWith("expected <owner/name> <tag>")
109 }
110 repo, code := resolveRepo(c, args[0], perm)
111 if code >= 0 {
112 return repo, store.Release{}, code
113 }
114 rel, err := c.Store.ReleaseByTag(repo.ID, args[1])
115 if errors.Is(err, store.ErrNotFound) {
116 return repo, rel, c.fail(protocol.ExitNotFound, "no release for tag %q in %s", args[1], repo.Path())
117 }
118 if err != nil {
119 return repo, rel, c.fail(protocol.ExitFailure, "%v", err)
120 }
121 return repo, rel, -1
122}
123
124func runReleaseCreate(c *Ctx, args []string) int {
125 f, err := c.parseArgs(args, flagSpec{Values: []string{"--title", "--notes", "--file", "--format"}, MaxPos: 2, Usage: c.Cmd.Usage})
126 if err != nil {
127 return c.fail(protocol.ExitUsage, "%v", err)
128 }
129 path, tag := f.pos(0), f.pos(1)
130 title, notes, file, format := f.Value("--title"), f.Value("--notes"), f.Value("--file"), f.Value("--format")
131 if path == "" || tag == "" {
132 return c.usage()
133 }
134 fmtName, err := markupFormat(format)
135 if err != nil {
136 return c.failInput(err)
137 }
138 if fmtName == "" {
139 fmtName = "md"
140 }
141 repo, code := resolveRepo(c, path, policy.CanWrite)
142 if code >= 0 {
143 return code
144 }
145 if code := refuseArchived(c, repo); code >= 0 {
146 return code
147 }
148 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
149 if _, err := gitutil.ResolveRef(dir, "refs/tags/"+tag); err != nil {
150 return c.fail(protocol.ExitNotFound, "no tag %q in %s — push the tag first", tag, repo.Path())
151 }
152 body, err := bodyFrom(c, notes, file)
153 if err != nil {
154 return c.failInput(err)
155 }
156 if title == "" {
157 title = tag
158 }
159 if _, err := c.Store.CreateRelease(repo.ID, tag, title, body, c.User.ID, fmtName); err != nil {
160 return c.failErr(err)
161 }
162 c.Store.RecordEvent(repo.ID, c.User.ID, "release.created", fmt.Sprintf(`{"tag":%q}`, tag))
163 return c.emit(map[string]string{"tag": tag, "title": title}, func(w io.Writer) {
164 fmt.Fprintf(w, "created release %s on %s\n", tag, repo.Path())
165 if c.Term.Cols > 0 {
166 fmt.Fprintln(w, c.siteURL(repo.Path(), "releases"))
167 }
168 })
169}
170
171type assetOut struct {
172 Name string `json:"name"`
173 Size int64 `json:"size"`
174 SHA256 string `json:"sha256"`
175}
176
177type releaseOut struct {
178 Tag string `json:"tag"`
179 Title string `json:"title"`
180 Notes string `json:"notes,omitempty"`
181 NotesFormat string `json:"notes_format,omitempty"`
182 Author string `json:"author,omitempty"`
183 CreatedAt string `json:"created_at"`
184 Assets []assetOut `json:"assets,omitempty"`
185}
186
187func releaseToOut(r store.Release, withNotes bool) releaseOut {
188 o := releaseOut{Tag: r.Tag, Title: r.Title, Author: r.Author, CreatedAt: r.CreatedAt}
189 if withNotes {
190 o.Notes = r.Notes
191 o.NotesFormat = r.NotesFormat
192 }
193 for _, a := range r.Assets {
194 o.Assets = append(o.Assets, assetOut{a.Name, a.Size, a.SHA256})
195 }
196 return o
197}
198
199func runReleaseEdit(c *Ctx, args []string) int {
200 f, err := c.parseArgs(args, flagSpec{Values: []string{"--title", "--notes", "--file", "--format"}, MaxPos: 2, Usage: c.Cmd.Usage})
201 if err != nil {
202 return c.fail(protocol.ExitUsage, "%v", err)
203 }
204 path, tag := f.pos(0), f.pos(1)
205 title, notes, file, format := f.Value("--title"), f.Value("--notes"), f.Value("--file"), f.Value("--format")
206 setTitle, setNotes := f.Has("--title"), f.Has("--notes") || f.Has("--file")
207 fmtName, err := markupFormat(format)
208 if err != nil {
209 return c.failInput(err)
210 }
211 if path == "" || tag == "" || (!setTitle && !setNotes && fmtName == "") {
212 return c.usage()
213 }
214 repo, code := resolveRepo(c, path, policy.CanWrite)
215 if code >= 0 {
216 return code
217 }
218 if code := refuseArchived(c, repo); code >= 0 {
219 return code
220 }
221 rel, err := c.Store.ReleaseByTag(repo.ID, tag)
222 if err != nil {
223 return c.fail(protocol.ExitNotFound, "no release %q in %s", tag, repo.Path())
224 }
225 // Absent flags keep what the release already says.
226 if !setTitle {
227 title = rel.Title
228 } else if title == "" {
229 title = tag
230 }
231 body := rel.Notes
232 if setNotes {
233 if body, err = bodyFrom(c, notes, file); err != nil {
234 return c.failInput(err)
235 }
236 }
237 if fmtName == "" {
238 fmtName = rel.NotesFormat
239 }
240 if err := c.Store.UpdateRelease(repo.ID, tag, title, body, fmtName); err != nil {
241 return c.fail(protocol.ExitFailure, "%v", err)
242 }
243 return c.emit(map[string]string{"tag": tag, "title": title}, func(w io.Writer) {
244 fmt.Fprintf(w, "updated release %s\n", tag)
245 })
246}
247
248// splitReleaseCursor pulls "<created_at>|<id>" apart. The id is what a
249// deleted release loses, so the created_at half carries the sort
250// position even when the row the cursor names is gone.
251func splitReleaseCursor(key string) (created string, id int64, ok bool) {
252 i := strings.LastIndex(key, "|")
253 if i < 0 {
254 return "", 0, false
255 }
256 created = key[:i]
257 n, err := strconv.ParseInt(key[i+1:], 10, 64)
258 if err != nil || created == "" {
259 return "", 0, false
260 }
261 return created, n, true
262}
263
264func runReleaseList(c *Ctx, args []string) int {
265 rest, p, code := parsePageFlags(c, args, "release", false)
266 if code >= 0 {
267 return code
268 }
269 if len(rest) != 1 {
270 return c.usage()
271 }
272 repo, code := resolveRepo(c, rest[0], policy.CanRead)
273 if code >= 0 {
274 return code
275 }
276 var afterCreated string
277 var afterID int64
278 if p.key != "" {
279 var ok bool
280 afterCreated, afterID, ok = splitReleaseCursor(p.key)
281 if !ok {
282 return c.fail(protocol.ExitUsage, "bad cursor")
283 }
284 }
285 rels, err := c.Store.ListReleasesPage(repo.ID, p.queryLimit(), afterCreated, afterID)
286 if err != nil {
287 return c.fail(protocol.ExitFailure, "%v", err)
288 }
289 rels, next := trimPage(p, rels, "release", func(r store.Release) string {
290 return r.CreatedAt + "|" + strconv.FormatInt(r.ID, 10)
291 })
292 var ds []releaseOut
293 for _, r := range rels {
294 ds = append(ds, releaseToOut(r, false))
295 }
296 return c.emitPageView(p, ds, next, func(w io.Writer) {
297 tb := c.table(w, "TAG", "TITLE", "ASSETS")
298 for _, d := range ds {
299 title := d.Title
300 if title == d.Tag {
301 title = ""
302 }
303 tb.row(cRef(d.Tag), cFlex(title), cText(fmt.Sprintf("%d asset(s)", len(d.Assets))))
304 }
305 tb.flush()
306 }, func() screen {
307 rows := make([]row, len(ds))
308 for i, d := range ds {
309 // "v1.2.0 — the forge speaks first" reads as its subtitle
310 // beside the tag.
311 title := strings.TrimPrefix(strings.TrimPrefix(d.Title, d.Tag), " — ")
312 assets := ""
313 switch n := len(d.Assets); n {
314 case 0:
315 case 1:
316 assets = "1 asset"
317 default:
318 assets = fmt.Sprintf("%d assets", n)
319 }
320 rows[i] = rowOf(cLink(d.Tag, c.siteURL(repo.Path(), "releases")), cFlex(title), cMeta(assets, relAge(d.CreatedAt, termNow())))
321 }
322 s := listScreen("Releases", rows)
323 if len(ds) > 0 {
324 s.actions = []action{{"Read", []string{"release", "show", repo.Path(), ds[0].Tag}}}
325 }
326 return s
327 })
328}
329
330func runReleaseShow(c *Ctx, args []string) int {
331 repo, rel, code := releaseRef(c, args, policy.CanRead)
332 if code >= 0 {
333 return code
334 }
335 d := releaseToOut(rel, true)
336 return c.emitView(d, func(w io.Writer) {
337 title := d.Title
338 if title == d.Tag {
339 title = ""
340 }
341 v := c.view(w)
342 v.title(d.Tag, title, "")
343 v.fields(
344 "author", d.Author+", "+c.when(d.CreatedAt),
345 )
346 v.body(d.Notes, d.NotesFormat)
347 if len(d.Assets) > 0 {
348 v.section("assets")
349 tb := c.table(w, "NAME", "SIZE", "SHA256")
350 for _, a := range d.Assets {
351 tb.row(cRef(a.Name), cSize(a.Size), cFlex(a.SHA256))
352 }
353 tb.flush()
354 }
355 }, func() screen {
356 assets := section{title: "Assets", n: len(d.Assets)}
357 for _, a := range d.Assets {
358 assets.rows = append(assets.rows, rowOf(cRef(a.Name), cSize(a.Size), cMeta(a.SHA256[:min(12, len(a.SHA256))])))
359 }
360 s := screen{body: d.Notes, format: d.NotesFormat, sections: []section{assets}, fields: []field{
361 {"Release", []cell{cLink(d.Tag, c.siteURL(repo.Path(), "releases")), cText(d.Title)}},
362 {"Author", []cell{cText(d.Author), cAge(d.CreatedAt)}},
363 }}
364 if len(d.Assets) > 0 {
365 s.actions = append(s.actions, action{"Get", []string{"release", "asset", "get", repo.Path(), d.Tag, d.Assets[0].Name}})
366 }
367 s.actions = append(s.actions, action{"Edit", []string{"release", "edit", repo.Path(), d.Tag, "--title", "<title>"}})
368 return s
369 })
370}
371
372func runReleaseDelete(c *Ctx, args []string) int {
373 var rest []string
374 var yes bool
375 for _, a := range args {
376 if a == "--yes" {
377 yes = true
378 } else {
379 rest = append(rest, a)
380 }
381 }
382 repo, rel, code := releaseRef(c, rest, policy.CanAdmin)
383 if code >= 0 {
384 return code
385 }
386 if !yes {
387 return c.fail(protocol.ExitUsage, "release delete is permanent (assets included); re-run with --yes")
388 }
389 if err := c.Store.DeleteRelease(rel.ID); err != nil {
390 return c.fail(protocol.ExitFailure, "%v", err)
391 }
392 os.RemoveAll(assetDir(c.Cfg.Server.Root, repo, rel.ID))
393 c.Store.RecordEvent(repo.ID, c.User.ID, "release.deleted", fmt.Sprintf(`{"tag":%q}`, rel.Tag))
394 return c.emit(map[string]string{"deleted": rel.Tag}, func(w io.Writer) {
395 fmt.Fprintf(w, "deleted release %s\n", rel.Tag)
396 })
397}
398
399func runAssetAdd(c *Ctx, args []string) int {
400 if len(args) != 3 {
401 return c.usage()
402 }
403 repo, rel, code := releaseRef(c, args[:2], policy.CanWrite)
404 if code >= 0 {
405 return code
406 }
407 if code := refuseArchived(c, repo); code >= 0 {
408 return code
409 }
410 name := args[2]
411 if !assetNamePat.MatchString(name) {
412 return c.fail(protocol.ExitUsage, "invalid asset name %q: letters, digits, '._+-'; must not start with '.'", name)
413 }
414 dir := assetDir(c.Cfg.Server.Root, repo, rel.ID)
415 if err := os.MkdirAll(dir, 0o750); err != nil {
416 return c.fail(protocol.ExitFailure, "%v", err)
417 }
418 tmp, err := os.CreateTemp(dir, ".upload-*")
419 if err != nil {
420 return c.fail(protocol.ExitFailure, "%v", err)
421 }
422 defer os.Remove(tmp.Name())
423 h := sha256.New()
424 limit := c.Cfg.Limits.MaxAssetBytes
425 n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(c.Stdin, limit+1))
426 if err != nil {
427 return c.fail(protocol.ExitFailure, "reading asset: %v", err)
428 }
429 if n > limit {
430 return c.fail(protocol.ExitUsage, "asset exceeds max_asset_bytes (%d)", limit)
431 }
432 if n == 0 {
433 return c.fail(protocol.ExitUsage, "empty asset: pipe the file on stdin")
434 }
435 if err := tmp.Close(); err != nil {
436 return c.fail(protocol.ExitFailure, "%v", err)
437 }
438 sum := hex.EncodeToString(h.Sum(nil))
439 if err := c.Store.AddReleaseAsset(rel.ID, name, n, sum); err != nil {
440 return c.failErr(err)
441 }
442 if err := os.Rename(tmp.Name(), filepath.Join(dir, name)); err != nil {
443 c.Store.RemoveReleaseAsset(rel.ID, name)
444 return c.fail(protocol.ExitFailure, "%v", err)
445 }
446 return c.emit(assetOut{name, n, sum}, func(w io.Writer) {
447 fmt.Fprintf(w, "uploaded %s (%d bytes, sha256 %s)\n", name, n, sum)
448 })
449}
450
451func runAssetGet(c *Ctx, args []string) int {
452 if len(args) != 3 {
453 return c.usage()
454 }
455 repo, rel, code := releaseRef(c, args[:2], policy.CanRead)
456 if code >= 0 {
457 return code
458 }
459 name := args[2]
460 if !assetNamePat.MatchString(name) {
461 return c.fail(protocol.ExitNotFound, "no asset %q", name)
462 }
463 f, err := os.Open(filepath.Join(assetDir(c.Cfg.Server.Root, repo, rel.ID), name))
464 if err != nil {
465 return c.fail(protocol.ExitNotFound, "no asset %q on release %s", name, rel.Tag)
466 }
467 defer f.Close()
468 if _, err := io.Copy(c.Stdout, f); err != nil {
469 return protocol.ExitFailure
470 }
471 return protocol.ExitOK
472}
473
474func runAssetRemove(c *Ctx, args []string) int {
475 if len(args) != 3 {
476 return c.usage()
477 }
478 repo, rel, code := releaseRef(c, args[:2], policy.CanWrite)
479 if code >= 0 {
480 return code
481 }
482 if code := refuseArchived(c, repo); code >= 0 {
483 return code
484 }
485 name := args[2]
486 if err := c.Store.RemoveReleaseAsset(rel.ID, name); err != nil {
487 if errors.Is(err, store.ErrNotFound) {
488 return c.fail(protocol.ExitNotFound, "no asset %q on release %s", name, rel.Tag)
489 }
490 return c.fail(protocol.ExitFailure, "%v", err)
491 }
492 if assetNamePat.MatchString(name) {
493 os.Remove(filepath.Join(assetDir(c.Cfg.Server.Root, repo, rel.ID), name))
494 }
495 return c.emit(map[string]string{"removed": name}, func(w io.Writer) {
496 fmt.Fprintf(w, "removed %s\n", name)
497 })
498}
499
500type releaseNoteItem struct {
501 Number int64 `json:"number"`
502 Title string `json:"title"`
503 Author string `json:"author"`
504 MergedAt string `json:"merged_at"`
505}
506
507type releaseNotesOut struct {
508 Since string `json:"since"` // the tag the range starts after; "" for all of history
509 Items []releaseNoteItem `json:"items"`
510}
511
512// runReleaseNotes lists the merge requests landed in <since>..<ref>,
513// oldest first. A merge request is in the range when the commit it
514// landed as is; one merged before merged_sha existed is matched on its
515// head, which is right for fast-forward and merge-commit merges and
516// misses old squashes and rebases. Without --since the range starts at
517// the most recent release other than the ref's own, so regenerating a
518// released tag's notes gives the same answer as drafting them did.
519func runReleaseNotes(c *Ctx, args []string) int {
520 f, err := c.parseArgs(args, flagSpec{Values: []string{"--since"}, MaxPos: 2, Usage: c.Cmd.Usage})
521 if err != nil {
522 return c.fail(protocol.ExitUsage, "%v", err)
523 }
524 path, ref, since := f.pos(0), f.pos(1), f.Value("--since")
525 if path == "" || ref == "" {
526 return c.usage()
527 }
528 repo, code := resolveRepo(c, path, policy.CanRead)
529 if code >= 0 {
530 return code
531 }
532 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
533 refSHA, err := gitutil.ResolveRef(dir, ref)
534 if err != nil {
535 return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
536 }
537 if since == "" {
538 rels, err := c.Store.ListReleases(repo.ID)
539 if err != nil {
540 return c.fail(protocol.ExitFailure, "%v", err)
541 }
542 for _, rel := range rels {
543 if rel.Tag != ref {
544 since = rel.Tag
545 break
546 }
547 }
548 }
549 var shas []string
550 if since == "" {
551 shas, err = gitutil.RevList(dir, refSHA, -1) // a negative max-count is no limit
552 } else {
553 var sinceSHA string
554 if sinceSHA, err = gitutil.ResolveRef(dir, since); err != nil {
555 return c.fail(protocol.ExitNotFound, "no tag %q in %s", since, repo.Path())
556 }
557 shas, err = gitutil.RevListRange(dir, sinceSHA, refSHA)
558 }
559 if err != nil {
560 return c.fail(protocol.ExitFailure, "%v", err)
561 }
562 mrs, err := c.Store.QueryMRs(repo.ID, store.MRFilter{State: "merged"})
563 if err != nil {
564 return c.fail(protocol.ExitFailure, "%v", err)
565 }
566 landed := map[string]store.MR{}
567 for _, mr := range mrs {
568 sha := mr.MergedSHA
569 if sha == "" {
570 sha = mr.HeadSHA
571 }
572 landed[sha] = mr
573 }
574 out := releaseNotesOut{Since: since, Items: []releaseNoteItem{}}
575 for i := len(shas) - 1; i >= 0; i-- {
576 if mr, ok := landed[shas[i]]; ok {
577 out.Items = append(out.Items, releaseNoteItem{mr.Number, mr.Title, mr.Author, mr.MergedAt})
578 }
579 }
580 if len(out.Items) == 0 && !c.JSON {
581 if since == "" {
582 fmt.Fprintf(c.Stderr, "no merge requests landed on %s\n", ref)
583 } else {
584 fmt.Fprintf(c.Stderr, "no merge requests landed between %s and %s\n", since, ref)
585 }
586 return protocol.ExitOK
587 }
588 return c.emit(out, func(w io.Writer) {
589 for _, it := range out.Items {
590 fmt.Fprintf(w, "- %s (!%d) by @%s\n", it.Title, it.Number, it.Author)
591 }
592 })
593}