internal/control/milestone.go
333 lines · 10837 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "path"
8 "regexp"
9 "strings"
10
11 "gitbay.org/gitbay/internal/gitutil"
12 "gitbay.org/gitbay/internal/policy"
13 "gitbay.org/gitbay/internal/protocol"
14 "gitbay.org/gitbay/internal/store"
15)
16
17func init() {
18 register(Command{Path: []string{"milestone", "create"},
19 Summary: "create a milestone",
20 Usage: "milestone create <owner/name> <title> [--description <d>] [--due YYYY-MM-DD]",
21 Flags: []Flag{
22 {"--description", "<d>", "what the milestone covers", ""},
23 {"--due", "YYYY-MM-DD", "target date", ""},
24 },
25 Examples: []string{`milestone create krz/gitbay v1.31.0 --due 2026-10-01`},
26 Run: runMilestoneCreate})
27 register(Command{Path: []string{"milestone", "list"},
28 Summary: "list milestones with progress",
29 Usage: "milestone list <owner/name> [--state open|closed|all]",
30 Flags: []Flag{
31 {"--state", "open|closed|all", "which milestones", "open"},
32 },
33 Examples: []string{"milestone list krz/gitbay --state all"},
34 ReadOnly: true, Run: runMilestoneList})
35 register(Command{Path: []string{"milestone", "close"},
36 Summary: "close a milestone",
37 Usage: "milestone close <owner/name> <title>",
38 Examples: []string{"milestone close krz/gitbay v1.30.0"},
39 Run: runMilestoneClose})
40 register(Command{Path: []string{"milestone", "reopen"},
41 Summary: "reopen a milestone",
42 Usage: "milestone reopen <owner/name> <title>",
43 Examples: []string{"milestone reopen krz/gitbay v1.30.0"},
44 Run: runMilestoneReopen})
45 register(Command{Path: []string{"issue", "milestone"},
46 Summary: "set or clear an issue's milestone",
47 Usage: "issue milestone <owner/name> <n> <title|none>",
48 Examples: []string{"issue milestone krz/gitbay 42 v1.31.0"},
49 Run: runIssueMilestone})
50 register(Command{Path: []string{"mr", "milestone"},
51 Summary: "set or clear an MR's milestone",
52 Usage: "mr milestone <owner/name> <n> <title|none>",
53 Examples: []string{"mr milestone krz/gitbay 431 v1.31.0"},
54 Run: runMRMilestone})
55 register(Command{Path: []string{"issue", "templates"},
56 Summary: "list issue templates (.gitbay/issue-template*.md)",
57 Usage: "issue templates <owner/name>",
58 Examples: []string{"issue templates krz/gitbay"},
59 ReadOnly: true, Run: runIssueTemplates})
60}
61
62var duePat = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
63
64func runMilestoneCreate(c *Ctx, args []string) int {
65 f, err := c.parseArgs(args, flagSpec{Values: []string{"--description", "--due"}, MaxPos: 2,
66 Usage: "milestone create <owner/name> <title> [--description <d>] [--due YYYY-MM-DD]"})
67 if err != nil {
68 return c.fail(protocol.ExitUsage, "%v", err)
69 }
70 path, title, description, due := f.pos(0), f.pos(1), f.Value("--description"), f.Value("--due")
71 if path == "" || title == "" {
72 return c.usage()
73 }
74 if due != "" && !duePat.MatchString(due) {
75 return c.fail(protocol.ExitUsage, "--due must be YYYY-MM-DD")
76 }
77 repo, code := resolveRepo(c, path, policy.CanWrite)
78 if code >= 0 {
79 return code
80 }
81 if code := refuseArchived(c, repo); code >= 0 {
82 return code
83 }
84 if _, err := c.Store.CreateMilestone(repo, title, description, due); err != nil {
85 if errors.Is(err, store.ErrOrgScoped) {
86 return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "milestone", title, "create"))
87 }
88 return c.failErr(err)
89 }
90 return c.emit(map[string]string{"milestone": title}, func(w io.Writer) {
91 fmt.Fprintf(w, "created milestone %q on %s\n", title, repo.Path())
92 })
93}
94
95func runMilestoneList(c *Ctx, args []string) int {
96 f, err := c.parseArgs(args, flagSpec{Values: []string{"--state"}, MaxPos: 1, Usage: "milestone list <owner/name> [--state open|closed|all]"})
97 if err != nil {
98 return c.fail(protocol.ExitUsage, "%v", err)
99 }
100 state, path := "open", f.pos(0)
101 if f.Has("--state") {
102 state = f.Value("--state")
103 }
104 if path == "" || (state != "open" && state != "closed" && state != "all") {
105 return c.usage()
106 }
107 repo, code := resolveRepo(c, path, policy.CanRead)
108 if code >= 0 {
109 return code
110 }
111 readable, err := ReadableScope(c.Store, c.User, repo)
112 if err != nil {
113 return c.fail(protocol.ExitFailure, "%v", err)
114 }
115 ms, err := c.Store.ListMilestones(repo, state, readable)
116 if err != nil {
117 return c.fail(protocol.ExitFailure, "%v", err)
118 }
119 return emitMilestones(c, ms,
120 action{"Milestones", []string{"milestone", "create", repo.Path(), "<title>"}},
121 action{"Milestones", []string{"milestone", "list", repo.Path(), "--state", "all"}},
122 )
123}
124
125// emitMilestones renders a milestone list for the caller, JSON or plain.
126func emitMilestones(c *Ctx, ms []store.Milestone, actions ...action) int {
127 type out struct {
128 Title string `json:"title"`
129 Description string `json:"description,omitempty"`
130 Due string `json:"due,omitempty"`
131 State string `json:"state"`
132 Org bool `json:"org,omitempty"`
133 Open int `json:"open"`
134 Closed int `json:"closed"`
135 }
136 var ds []out
137 for _, m := range ms {
138 ds = append(ds, out{m.Title, m.Description, m.DueDate, m.State, m.OrgID != 0, m.OpenItems, m.ClosedItems})
139 }
140 return c.emitView(ds, func(w io.Writer) {
141 tb := c.table(w, "TITLE", "STATE", "DUE", "PROGRESS")
142 for _, d := range ds {
143 due := d.Due
144 if due == "" {
145 due = "-"
146 }
147 cells := []cell{cRef(d.Title), cState(d.State), cText("due " + due), cText(fmt.Sprintf("%d open, %d closed", d.Open, d.Closed))}
148 if d.Org {
149 cells = append(cells, cText("org"))
150 }
151 tb.row(cells...)
152 }
153 tb.flush()
154 }, func() screen {
155 rows := make([]row, len(ds))
156 for i, d := range ds {
157 lead, due := cGlyph(d.State), ""
158 if t, ok := parseStamp(d.Due + " 00:00:00"); ok {
159 due = "due " + relAge(d.Due+" 00:00:00", termNow())
160 if d.State == "open" && t.Before(termNow()) {
161 lead, due = cYou(), "overdue "+d.Due
162 }
163 }
164 progress := fmt.Sprintf("%d/%d closed", d.Closed, d.Open+d.Closed)
165 org := ""
166 if d.Org {
167 org = "org"
168 }
169 rows[i] = rowOf(cRef(d.Title), lead, cFlex(d.Description), cMeta(due, progress, org))
170 }
171 return listScreen("Milestones", rows, actions...)
172 })
173}
174
175func runMilestoneClose(c *Ctx, args []string) int { return setMilestoneState(c, args, "closed") }
176func runMilestoneReopen(c *Ctx, args []string) int { return setMilestoneState(c, args, "open") }
177
178func setMilestoneState(c *Ctx, args []string, state string) int {
179 verb := "close"
180 if state == "open" {
181 verb = "reopen"
182 }
183 if len(args) != 2 {
184 return c.usage()
185 }
186 repo, code := resolveRepo(c, args[0], policy.CanWrite)
187 if code >= 0 {
188 return code
189 }
190 if code := refuseArchived(c, repo); code >= 0 {
191 return code
192 }
193 m, err := c.Store.MilestoneByTitle(repo, args[1])
194 if err != nil {
195 return milestoneErr(c, repo, args[1], err)
196 }
197 if m.OrgID != 0 {
198 return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "milestone", m.Title, verb))
199 }
200 if err := c.Store.SetMilestoneState(m.ID, state); err != nil {
201 return c.fail(protocol.ExitFailure, "%v", err)
202 }
203 return c.emit(map[string]string{"milestone": m.Title, "state": state}, func(w io.Writer) {
204 fmt.Fprintf(w, "%sd milestone %q on %s\n", verb, m.Title, repo.Path())
205 })
206}
207
208func milestoneErr(c *Ctx, repo store.Repo, title string, err error) int {
209 if errors.Is(err, store.ErrNotFound) {
210 return c.fail(protocol.ExitNotFound, "no milestone %q in %s", title, repo.Path())
211 }
212 return c.fail(protocol.ExitFailure, "%v", err)
213}
214
215func runIssueMilestone(c *Ctx, args []string) int {
216 repo, issue, code := issueRef(c, args, policy.CanWrite)
217 if code >= 0 {
218 return code
219 }
220 return setItemMilestone(c, repo, args, "issue", issue.Number, func(id int64) error {
221 return c.Store.SetIssueMilestone(issue.ID, id)
222 })
223}
224
225func runMRMilestone(c *Ctx, args []string) int {
226 repo, mr, code := mrRef(c, args, policy.CanWrite)
227 if code >= 0 {
228 return code
229 }
230 return setItemMilestone(c, repo, args, "mr", mr.Number, func(id int64) error {
231 return c.Store.SetMRMilestone(mr.ID, id)
232 })
233}
234
235// recordItemMilestone sets milestone id (0 clears it) through set and
236// records the milestoned event naming title ("" when cleared).
237func recordItemMilestone(c *Ctx, repo store.Repo, noun string, number, id int64, title string, set func(int64) error) error {
238 if err := set(id); err != nil {
239 return err
240 }
241 c.Store.RecordEvent(repo.ID, c.User.ID, noun+".milestoned",
242 fmt.Sprintf(`{"number":%d,"milestone":%q}`, number, title))
243 return nil
244}
245
246// setItemMilestone sets the milestone args[2] titles through set. noun and
247// number name what it was set on, for the event.
248func setItemMilestone(c *Ctx, repo store.Repo, args []string, noun string, number int64, set func(int64) error) int {
249 if code := refuseArchived(c, repo); code >= 0 {
250 return code
251 }
252 if len(args) != 3 {
253 return c.usage()
254 }
255 title := args[2]
256 var id int64
257 if title != "none" {
258 m, err := c.Store.MilestoneByTitle(repo, title)
259 if err != nil {
260 return milestoneErr(c, repo, title, err)
261 }
262 id = m.ID
263 }
264 cleared := title
265 if cleared == "none" {
266 cleared = ""
267 }
268 if err := recordItemMilestone(c, repo, noun, number, id, cleared, set); err != nil {
269 return c.fail(protocol.ExitFailure, "%v", err)
270 }
271 if title == "none" {
272 return c.emit(map[string]string{"milestone": ""}, func(w io.Writer) {
273 fmt.Fprintln(w, "milestone cleared")
274 })
275 }
276 return c.emit(map[string]string{"milestone": title}, func(w io.Writer) {
277 fmt.Fprintf(w, "milestone set to %q\n", title)
278 })
279}
280
281// runIssueTemplates lists .gitbay/issue-template*.md at the default branch.
282func runIssueTemplates(c *Ctx, args []string) int {
283 if len(args) != 1 {
284 return c.usage()
285 }
286 repo, code := resolveRepo(c, args[0], policy.CanRead)
287 if code >= 0 {
288 return code
289 }
290 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
291 ts := IssueTemplates(dir, repo.DefaultBranch)
292 return c.emitView(ts, func(w io.Writer) {
293 tb := c.table(w, "NAME")
294 for _, t := range ts {
295 tb.row(cRef(t.Name))
296 }
297 tb.flush()
298 }, func() screen {
299 rows := make([]row, len(ts))
300 for i, tpl := range ts {
301 rows[i] = rowOf(cRef(tpl.Name))
302 }
303 return listScreen("Issue templates", rows,
304 action{"New", []string{"issue", "create", repo.Path(), "--title", "<title>"}},
305 )
306 })
307}
308
309type IssueTemplate struct {
310 Name string `json:"name"`
311 Body string `json:"body"`
312}
313
314// IssueTemplates reads .gitbay/issue-template*.md from ref. Missing
315// directory or unreadable files yield an empty list, never an error.
316func IssueTemplates(dir, ref string) []IssueTemplate {
317 entries, err := gitutil.ListTree(dir, ref, ".gitbay")
318 if err != nil {
319 return nil
320 }
321 var out []IssueTemplate
322 for _, e := range entries {
323 if e.Type != "blob" || !strings.HasPrefix(e.Name, "issue-template") || !strings.HasSuffix(e.Name, ".md") {
324 continue
325 }
326 raw, err := gitutil.ReadBlob(dir, ref, path.Join(".gitbay", e.Name), maxBodyBytes)
327 if err != nil {
328 continue
329 }
330 out = append(out, IssueTemplate{Name: e.Name, Body: string(raw)})
331 }
332 return out
333}