Commit 505d2331c0

505d2331c0d6bebdbe653e432e06b353d1d65014

parent: 670fe13637

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 02:23 UTC

control: split dashboard and admin user show

runDashboard gathers its lists in dashboardData and writes text in
writeDashboard and writeQueues. runAdminUserShow's types move to the
package, with its data, text view and screen in their own functions.

Layout: unified · split

internal/control/admin.go +184 −169
@@ -210,225 +210,240 @@ func runAdminUserShow(c *Ctx, args []string) int {
210 return c.fail(protocol.ExitFailure, "%v", err) 210 return c.fail(protocol.ExitFailure, "%v", err)
211 } 211 }
212 212
213 type keyOut struct { 213 d, err := adminUserShowData(c, u, row)
214 Fingerprint string `json:"fingerprint"` 214 if err != nil {
215 Algo string `json:"algo"` 215 return c.fail(protocol.ExitFailure, "%v", err)
216 Scope string `json:"scope"`
217 Label string `json:"label"`
218 CreatedAt string `json:"created_at"`
219 LastUsedAt string `json:"last_used_at,omitempty"`
220 }
221 type emailOut struct {
222 Address string `json:"address"`
223 Verified bool `json:"verified"`
224 VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin
225 Primary bool `json:"primary"`
226 }
227 type pgpOut struct {
228 Fingerprint string `json:"fingerprint"`
229 ExpiresAt *time.Time `json:"expires_at,omitempty"`
230 RevokedAt *time.Time `json:"revoked_at,omitempty"`
231 }
232 type orgOut struct {
233 Org string `json:"org"`
234 Role string `json:"role"`
235 }
236 type tokenOut struct {
237 Name string `json:"name"`
238 Scope string `json:"scope"`
239 CreatedAt string `json:"created_at"`
240 ExpiresAt *time.Time `json:"expires_at,omitempty"`
241 LastUsedAt *time.Time `json:"last_used_at,omitempty"`
242 } 216 }
243 type out struct { 217 return c.emitView(d, func(w io.Writer) { writeAdminUserShow(c, w, d) },
244 adminUserOut 218 func() screen { return adminUserScreen(c, d) })
245 Keys []keyOut `json:"keys"` 219}
246 Emails []emailOut `json:"emails"` 220
247 PGPKeys []pgpOut `json:"pgp_keys"` 221type adminKeyOut struct {
248 Orgs []orgOut `json:"orgs"` 222 Fingerprint string `json:"fingerprint"`
249 Repos int64 `json:"repos"` 223 Algo string `json:"algo"`
250 RepoLimit int64 `json:"repo_limit"` // 0 unlimited 224 Scope string `json:"scope"`
251 ByteLimit int64 `json:"byte_limit"` // 0 unlimited 225 Label string `json:"label"`
252 APITokens []tokenOut `json:"api_tokens"` 226 CreatedAt string `json:"created_at"`
253 WebSessions int64 `json:"web_sessions"` 227 LastUsedAt string `json:"last_used_at,omitempty"`
254 DeleteAfter string `json:"delete_after,omitempty"` // a scheduled self-deletion 228}
255 } 229type adminEmailOut struct {
256 d := out{adminUserOut: adminUserRow(row), 230 Address string `json:"address"`
257 Keys: []keyOut{}, Emails: []emailOut{}, PGPKeys: []pgpOut{}, Orgs: []orgOut{}, APITokens: []tokenOut{}} 231 Verified bool `json:"verified"`
232 VerifiedBy string `json:"verified_by,omitempty"` // smtp | admin
233 Primary bool `json:"primary"`
234}
235type adminPGPOut struct {
236 Fingerprint string `json:"fingerprint"`
237 ExpiresAt *time.Time `json:"expires_at,omitempty"`
238 RevokedAt *time.Time `json:"revoked_at,omitempty"`
239}
240type adminOrgOut struct {
241 Org string `json:"org"`
242 Role string `json:"role"`
243}
244type adminTokenOut struct {
245 Name string `json:"name"`
246 Scope string `json:"scope"`
247 CreatedAt string `json:"created_at"`
248 ExpiresAt *time.Time `json:"expires_at,omitempty"`
249 LastUsedAt *time.Time `json:"last_used_at,omitempty"`
250}
251type adminUserShowOut struct {
252 adminUserOut
253 Keys []adminKeyOut `json:"keys"`
254 Emails []adminEmailOut `json:"emails"`
255 PGPKeys []adminPGPOut `json:"pgp_keys"`
256 Orgs []adminOrgOut `json:"orgs"`
257 Repos int64 `json:"repos"`
258 RepoLimit int64 `json:"repo_limit"` // 0 unlimited
259 ByteLimit int64 `json:"byte_limit"` // 0 unlimited
260 APITokens []adminTokenOut `json:"api_tokens"`
261 WebSessions int64 `json:"web_sessions"`
262 DeleteAfter string `json:"delete_after,omitempty"` // a scheduled self-deletion
263}
264
265// adminUserShowData is everything `admin user show` reports about a user.
266func adminUserShowData(c *Ctx, u store.User, row store.AdminUser) (adminUserShowOut, error) {
267 d := adminUserShowOut{adminUserOut: adminUserRow(row),
268 Keys: []adminKeyOut{}, Emails: []adminEmailOut{}, PGPKeys: []adminPGPOut{}, Orgs: []adminOrgOut{}, APITokens: []adminTokenOut{}}
258 269
259 keys, err := c.Store.ListSSHKeys(u.ID) 270 keys, err := c.Store.ListSSHKeys(u.ID)
260 if err != nil { 271 if err != nil {
261 return c.fail(protocol.ExitFailure, "%v", err) 272 return d, err
262 } 273 }
263 for _, k := range keys { 274 for _, k := range keys {
264 d.Keys = append(d.Keys, keyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt}) 275 d.Keys = append(d.Keys, adminKeyOut{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedAt, k.LastUsedAt})
265 } 276 }
266 emails, err := c.Store.ListEmails(u.ID) 277 emails, err := c.Store.ListEmails(u.ID)
267 if err != nil { 278 if err != nil {
268 return c.fail(protocol.ExitFailure, "%v", err) 279 return d, err
269 } 280 }
270 for _, e := range emails { 281 for _, e := range emails {
271 d.Emails = append(d.Emails, emailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary}) 282 d.Emails = append(d.Emails, adminEmailOut{e.Address, e.Verified, e.VerifiedBy, e.Primary})
272 } 283 }
273 pgp, err := c.Store.ListPGPKeys(u.ID) 284 pgp, err := c.Store.ListPGPKeys(u.ID)
274 if err != nil { 285 if err != nil {
275 return c.fail(protocol.ExitFailure, "%v", err) 286 return d, err
276 } 287 }
277 for _, k := range pgp { 288 for _, k := range pgp {
278 d.PGPKeys = append(d.PGPKeys, pgpOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt}) 289 d.PGPKeys = append(d.PGPKeys, adminPGPOut{k.Fingerprint, k.ExpiresAt, k.RevokedAt})
279 } 290 }
280 orgs, err := c.Store.ListOrgsForUser(u.ID) 291 orgs, err := c.Store.ListOrgsForUser(u.ID)
281 if err != nil { 292 if err != nil {
282 return c.fail(protocol.ExitFailure, "%v", err) 293 return d, err
283 } 294 }
284 for _, m := range orgs { 295 for _, m := range orgs {
285 d.Orgs = append(d.Orgs, orgOut{m.Username, m.Role}) 296 d.Orgs = append(d.Orgs, adminOrgOut{m.Username, m.Role})
286 } 297 }
287 if d.Repos, err = c.Store.OwnedRepoCount("user", u.ID); err != nil { 298 if d.Repos, err = c.Store.OwnedRepoCount("user", u.ID); err != nil {
288 return c.fail(protocol.ExitFailure, "%v", err) 299 return d, err
289 } 300 }
290 d.RepoLimit = RepoLimit(c.Store, limitsOf(c), "user", u.ID) 301 d.RepoLimit = RepoLimit(c.Store, limitsOf(c), "user", u.ID)
291 d.ByteLimit = ByteLimit(c.Store, limitsOf(c), "user", u.ID) 302 d.ByteLimit = ByteLimit(c.Store, limitsOf(c), "user", u.ID)
292 tokens, err := c.Store.ListAPITokens(u.ID) 303 tokens, err := c.Store.ListAPITokens(u.ID)
293 if err != nil { 304 if err != nil {
294 return c.fail(protocol.ExitFailure, "%v", err) 305 return d, err
295 } 306 }
296 for _, t := range tokens { 307 for _, t := range tokens {
297 d.APITokens = append(d.APITokens, tokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt}) 308 d.APITokens = append(d.APITokens, adminTokenOut{t.Name, t.Scope, t.CreatedAt, t.ExpiresAt, t.LastUsedAt})
298 } 309 }
299 if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil { 310 if d.WebSessions, err = c.Store.WebSessionCount(u.ID); err != nil {
300 return c.fail(protocol.ExitFailure, "%v", err) 311 return d, err
301 } 312 }
302 d.DeleteAfter = u.DeleteAfter 313 d.DeleteAfter = u.DeleteAfter
314 return d, nil
315}
303 316
304 return c.emitView(d, func(w io.Writer) { 317// writeAdminUserShow is `admin user show` as text.
305 admin := "" 318func writeAdminUserShow(c *Ctx, w io.Writer, d adminUserShowOut) {
306 if d.Admin { 319 admin := ""
307 admin = "yes" 320 if d.Admin {
308 } 321 admin = "yes"
309 v := c.view(w) 322 }
310 v.title(d.Username, "", d.State) 323 v := c.view(w)
311 v.fields( 324 v.title(d.Username, "", d.State)
312 "admin", admin, 325 v.fields(
313 "created", c.when(d.CreatedAt), 326 "admin", admin,
314 "last seen", c.when(d.LastSeen), 327 "created", c.when(d.CreatedAt),
315 "repos", fmt.Sprintf("%d", d.Repos), 328 "last seen", c.when(d.LastSeen),
316 "web sessions", fmt.Sprintf("%d", d.WebSessions), 329 "repos", fmt.Sprintf("%d", d.Repos),
317 "deletes at", c.when(d.DeleteAfter), 330 "web sessions", fmt.Sprintf("%d", d.WebSessions),
318 ) 331 "deletes at", c.when(d.DeleteAfter),
319 if len(d.Keys) > 0 { 332 )
320 v.section("keys") 333 if len(d.Keys) > 0 {
321 tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED") 334 v.section("keys")
322 for _, k := range d.Keys { 335 tk := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LAST USED")
323 tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt))
324 }
325 tk.flush()
326 }
327 if len(d.Emails) > 0 {
328 v.section("emails")
329 te := c.table(w, "ADDRESS", "STATE")
330 for _, e := range d.Emails {
331 state := "unverified"
332 if e.Verified {
333 state = "verified by " + e.VerifiedBy
334 }
335 cells := []cell{cRef(e.Address), cState(state)}
336 if e.Primary {
337 cells = c.note(cells, 1, "primary", "primary")
338 }
339 te.row(cells...)
340 }
341 te.flush()
342 }
343 if len(d.PGPKeys) > 0 {
344 v.section("pgp keys")
345 tp := c.table(w, "FINGERPRINT")
346 for _, k := range d.PGPKeys {
347 tp.row(cFlex(k.Fingerprint))
348 }
349 tp.flush()
350 }
351 if len(d.Orgs) > 0 {
352 v.section("orgs")
353 to := c.table(w, "ORG", "ROLE")
354 for _, o := range d.Orgs {
355 to.row(cRef(o.Org), cState(o.Role))
356 }
357 to.flush()
358 }
359 if len(d.APITokens) > 0 {
360 v.section("api tokens")
361 tt := c.table(w, "NAME", "SCOPE", "LAST USED")
362 for _, t := range d.APITokens {
363 used := ""
364 if t.LastUsedAt != nil {
365 used = t.LastUsedAt.UTC().Format(time.RFC3339Nano)
366 }
367 tt.row(cRef(t.Name), cState(t.Scope), cAge(used))
368 }
369 tt.flush()
370 }
371 }, func() screen {
372 s := screen{}
373 user := []cell{cRef(d.Username), cState(d.State)}
374 if d.Admin {
375 user = append(user, cMeta("admin"))
376 }
377 seen := "never seen"
378 if d.LastSeen != "" {
379 seen = "seen " + relAge(d.LastSeen, termNow())
380 }
381 s.fields = []field{
382 {"User", user},
383 {"Seen", []cell{cText(seen), cMeta("created " + relAge(d.CreatedAt, termNow()))}},
384 {"Repos", []cell{cText(strconv.FormatInt(d.Repos, 10))}},
385 {"Sessions", []cell{cText(strconv.FormatInt(d.WebSessions, 10))}},
386 }
387 keys := section{title: "Keys", n: len(d.Keys)}
388 for _, k := range d.Keys { 336 for _, k := range d.Keys {
389 keys.rows = append(keys.rows, rowOf(cFlexRef(k.Fingerprint), cState(k.Scope), cMeta(k.Algo, "used "+relAge(k.LastUsedAt, termNow())))) 337 tk.row(cFlex(k.Fingerprint), cText(k.Algo), cState(k.Scope), cAge(k.LastUsedAt))
390 } 338 }
391 emails := section{title: "Emails", n: len(d.Emails)} 339 tk.flush()
340 }
341 if len(d.Emails) > 0 {
342 v.section("emails")
343 te := c.table(w, "ADDRESS", "STATE")
392 for _, e := range d.Emails { 344 for _, e := range d.Emails {
393 state, primary := "unverified", "" 345 state := "unverified"
394 if e.Verified { 346 if e.Verified {
395 state = "verified" 347 state = "verified by " + e.VerifiedBy
396 } 348 }
349 cells := []cell{cRef(e.Address), cState(state)}
397 if e.Primary { 350 if e.Primary {
398 primary = "primary" 351 cells = c.note(cells, 1, "primary", "primary")
399 } 352 }
400 emails.rows = append(emails.rows, rowOf(cRef(e.Address), cState(state), cMeta(primary, e.VerifiedBy))) 353 te.row(cells...)
401 } 354 }
402 pgp := section{title: "PGP keys", n: len(d.PGPKeys)} 355 te.flush()
356 }
357 if len(d.PGPKeys) > 0 {
358 v.section("pgp keys")
359 tp := c.table(w, "FINGERPRINT")
403 for _, k := range d.PGPKeys { 360 for _, k := range d.PGPKeys {
404 pgp.rows = append(pgp.rows, rowOf(cFlexRef(k.Fingerprint))) 361 tp.row(cFlex(k.Fingerprint))
405 } 362 }
406 orgs := section{title: "Orgs", n: len(d.Orgs)} 363 tp.flush()
364 }
365 if len(d.Orgs) > 0 {
366 v.section("orgs")
367 to := c.table(w, "ORG", "ROLE")
407 for _, o := range d.Orgs { 368 for _, o := range d.Orgs {
408 orgs.rows = append(orgs.rows, rowOf(cLink(o.Org, c.siteURL(o.Org)), cState(o.Role))) 369 to.row(cRef(o.Org), cState(o.Role))
409 } 370 }
410 tokens := section{title: "API tokens", n: len(d.APITokens)} 371 to.flush()
411 for _, tk := range d.APITokens { 372 }
373 if len(d.APITokens) > 0 {
374 v.section("api tokens")
375 tt := c.table(w, "NAME", "SCOPE", "LAST USED")
376 for _, t := range d.APITokens {
412 used := "" 377 used := ""
413 if tk.LastUsedAt != nil { 378 if t.LastUsedAt != nil {
414 used = "used " + relAge(tk.LastUsedAt.UTC().Format(time.RFC3339Nano), termNow()) 379 used = t.LastUsedAt.UTC().Format(time.RFC3339Nano)
415 } 380 }
416 tokens.rows = append(tokens.rows, rowOf(cRef(tk.Name), cState(tk.Scope), cMeta(used))) 381 tt.row(cRef(t.Name), cState(t.Scope), cAge(used))
417 }
418 s.sections = []section{keys, emails, pgp, orgs, tokens}
419 role, state := "promote", "disable"
420 if d.Admin {
421 role = "demote"
422 }
423 if d.State == "disabled" {
424 state = "enable"
425 } 382 }
426 s.actions = []action{ 383 tt.flush()
427 {"Manage", []string{"admin", "user", role, d.Username}}, 384 }
428 {"Manage", []string{"admin", "user", state, d.Username}}, 385}
429 } 386
430 return s 387func adminUserScreen(c *Ctx, d adminUserShowOut) screen {
431 }) 388 s := screen{}
389 user := []cell{cRef(d.Username), cState(d.State)}
390 if d.Admin {
391 user = append(user, cMeta("admin"))
392 }
393 seen := "never seen"
394 if d.LastSeen != "" {
395 seen = "seen " + relAge(d.LastSeen, termNow())
396 }
397 s.fields = []field{
398 {"User", user},
399 {"Seen", []cell{cText(seen), cMeta("created " + relAge(d.CreatedAt, termNow()))}},
400 {"Repos", []cell{cText(strconv.FormatInt(d.Repos, 10))}},
401 {"Sessions", []cell{cText(strconv.FormatInt(d.WebSessions, 10))}},
402 }
403 keys := section{title: "Keys", n: len(d.Keys)}
404 for _, k := range d.Keys {
405 keys.rows = append(keys.rows, rowOf(cFlexRef(k.Fingerprint), cState(k.Scope), cMeta(k.Algo, "used "+relAge(k.LastUsedAt, termNow()))))
406 }
407 emails := section{title: "Emails", n: len(d.Emails)}
408 for _, e := range d.Emails {
409 state, primary := "unverified", ""
410 if e.Verified {
411 state = "verified"
412 }
413 if e.Primary {
414 primary = "primary"
415 }
416 emails.rows = append(emails.rows, rowOf(cRef(e.Address), cState(state), cMeta(primary, e.VerifiedBy)))
417 }
418 pgp := section{title: "PGP keys", n: len(d.PGPKeys)}
419 for _, k := range d.PGPKeys {
420 pgp.rows = append(pgp.rows, rowOf(cFlexRef(k.Fingerprint)))
421 }
422 orgs := section{title: "Orgs", n: len(d.Orgs)}
423 for _, o := range d.Orgs {
424 orgs.rows = append(orgs.rows, rowOf(cLink(o.Org, c.siteURL(o.Org)), cState(o.Role)))
425 }
426 tokens := section{title: "API tokens", n: len(d.APITokens)}
427 for _, tk := range d.APITokens {
428 used := ""
429 if tk.LastUsedAt != nil {
430 used = "used " + relAge(tk.LastUsedAt.UTC().Format(time.RFC3339Nano), termNow())
431 }
432 tokens.rows = append(tokens.rows, rowOf(cRef(tk.Name), cState(tk.Scope), cMeta(used)))
433 }
434 s.sections = []section{keys, emails, pgp, orgs, tokens}
435 role, state := "promote", "disable"
436 if d.Admin {
437 role = "demote"
438 }
439 if d.State == "disabled" {
440 state = "enable"
441 }
442 s.actions = []action{
443 {"Manage", []string{"admin", "user", role, d.Username}},
444 {"Manage", []string{"admin", "user", state, d.Username}},
445 }
446 return s
432} 447}
433 448
434func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) } 449func runAdminUserPromote(c *Ctx, args []string) int { return setAdmin(c, args, true) }
internal/control/dashboard.go +176 −160
@@ -101,215 +101,231 @@ func runDashboard(c *Ctx, args []string) int {
101 if len(args) != 0 { 101 if len(args) != 0 {
102 return c.usage() 102 return c.usage()
103 } 103 }
104 d, events, err := dashboardData(c)
105 if err != nil {
106 return c.fail(protocol.ExitFailure, "%v", err)
107 }
108 lines := FeedLines(events)
109 return c.emitView(d, func(w io.Writer) { writeDashboard(c, w, d, lines) },
110 func() screen { return dashboardScreen(c, d, lines) })
111}
112
113// dashboardData is the signed-in user's dashboard, with the events its
114// activity was made from.
115func dashboardData(c *Ctx) (DashboardOut, []store.FeedEvent, error) {
104 d := DashboardOut{ 116 d := DashboardOut{
105 Reviews: []DashboardItem{}, Assigned: []DashboardItem{}, MRs: []DashboardItem{}, 117 Reviews: []DashboardItem{}, Assigned: []DashboardItem{}, MRs: []DashboardItem{},
106 Issues: []DashboardItem{}, Pinned: []PinnedOut{}, Activity: []FeedOut{}, Builds: []DashboardBuild{}, 118 Issues: []DashboardItem{}, Pinned: []PinnedOut{}, Activity: []FeedOut{}, Builds: []DashboardBuild{},
107 } 119 }
108 120 var err error
109 pinned, err := c.Store.PinnedRepos(c.User.ID) 121 if d.Pinned, err = pinnedOutputs(c); err != nil {
110 if err != nil { 122 return d, nil, err
111 return c.fail(protocol.ExitFailure, "%v", err) 123 }
112 } 124 lists := []struct {
113 for _, r := range pinned { 125 into *[]DashboardItem
114 grant, err := c.Store.AccessRole(r.ID, c.User.ID) 126 fetch func(int64) ([]store.DashboardItem, error)
127 }{
128 {&d.MRs, c.Store.DashboardMRs},
129 {&d.Reviews, c.Store.ReviewQueue},
130 {&d.Assigned, c.Store.AssignedIssues},
131 {&d.Issues, c.Store.DashboardIssues},
132 }
133 for _, l := range lists {
134 items, err := l.fetch(c.User.ID)
115 if err != nil { 135 if err != nil {
116 return c.fail(protocol.ExitFailure, "%v", err) 136 return d, nil, err
117 } 137 }
118 if !policy.CanRead(c.User, r, grant) { 138 for _, m := range items {
119 continue 139 *l.into = append(*l.into, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued})
120 } 140 }
121 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
122 d.Pinned = append(d.Pinned, PinnedOut{r.Path(), r.Visibility, desc, r.Settings.Archived})
123 }
124
125 mrs, err := c.Store.DashboardMRs(c.User.ID)
126 if err != nil {
127 return c.fail(protocol.ExitFailure, "%v", err)
128 }
129 for _, m := range mrs {
130 d.MRs = append(d.MRs, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued})
131 }
132
133 reviews, err := c.Store.ReviewQueue(c.User.ID)
134 if err != nil {
135 return c.fail(protocol.ExitFailure, "%v", err)
136 }
137 for _, m := range reviews {
138 d.Reviews = append(d.Reviews, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued})
139 }
140
141 assigned, err := c.Store.AssignedIssues(c.User.ID)
142 if err != nil {
143 return c.fail(protocol.ExitFailure, "%v", err)
144 }
145 for _, i := range assigned {
146 d.Assigned = append(d.Assigned, DashboardItem{i.RepoPath, i.Number, i.Title, i.Author, i.State, i.UpdatedAt, i.Queued})
147 }
148
149 issues, err := c.Store.DashboardIssues(c.User.ID)
150 if err != nil {
151 return c.fail(protocol.ExitFailure, "%v", err)
152 }
153 for _, i := range issues {
154 d.Issues = append(d.Issues, DashboardItem{i.RepoPath, i.Number, i.Title, i.Author, i.State, i.UpdatedAt, i.Queued})
155 } 141 }
156 142
157 events, err := c.Store.RecentEvents(c.User.ID, 20, 0) 143 events, err := c.Store.RecentEvents(c.User.ID, 20, 0)
158 if err != nil { 144 if err != nil {
159 return c.fail(protocol.ExitFailure, "%v", err) 145 return d, nil, err
160 } 146 }
161 d.Activity = feedOutputs(events) 147 d.Activity = feedOutputs(events)
162 148
163 builds, err := c.Store.RecentBuilds(c.User.ID, 20) 149 builds, err := c.Store.RecentBuilds(c.User.ID, 20)
164 if err != nil { 150 if err != nil {
165 return c.fail(protocol.ExitFailure, "%v", err) 151 return d, nil, err
166 } 152 }
167 for _, b := range builds { 153 for _, b := range builds {
168 d.Builds = append(d.Builds, DashboardBuild{b.RepoPath, b.Number, b.Job, b.Status, b.SHA, b.Ref, b.CreatedAt, b.FinishedAt}) 154 d.Builds = append(d.Builds, DashboardBuild{b.RepoPath, b.Number, b.Job, b.Status, b.SHA, b.Ref, b.CreatedAt, b.FinishedAt})
169 } 155 }
170 if d.Queries, err = PinnedQueries(c.Store, c.User); err != nil { 156 if d.Queries, err = PinnedQueries(c.Store, c.User); err != nil {
171 return c.fail(protocol.ExitFailure, "%v", err) 157 return d, nil, err
172 } 158 }
173 d.Unread = c.Store.UnreadNotices(c.User.ID) 159 d.Unread = c.Store.UnreadNotices(c.User.ID)
174 if c.User.IsAdmin { 160 if c.User.IsAdmin {
175 d.Server = &ServerOut{Commit: buildinfo.String()} 161 d.Server = &ServerOut{Commit: buildinfo.String()}
176 q, err := c.Store.QueueStatus() 162 q, err := c.Store.QueueStatus()
177 if err != nil { 163 if err != nil {
178 return c.fail(protocol.ExitFailure, "%v", err) 164 return d, nil, err
179 } 165 }
180 d.Queues = &q 166 d.Queues = &q
181 } 167 }
168 return d, events, nil
169}
182 170
183 lines := FeedLines(events) 171// pinnedOutputs is the user's pinned repositories they can still read.
184 return c.emitView(d, func(w io.Writer) { 172func pinnedOutputs(c *Ctx) ([]PinnedOut, error) {
185 heading := func(title string) { fmt.Fprintln(w, title) } 173 pinned, err := c.Store.PinnedRepos(c.User.ID)
186 section := func(title string, rows [][]cell) { 174 if err != nil {
187 heading(title) 175 return nil, err
188 if len(rows) == 0 { 176 }
189 fmt.Fprintln(w, " none") 177 out := []PinnedOut{}
190 return 178 for _, r := range pinned {
191 } 179 grant, err := c.Store.AccessRole(r.ID, c.User.ID)
192 for _, r := range rows { 180 if err != nil {
193 parts := make([]string, len(r)) 181 return nil, err
194 for i, cl := range r {
195 parts[i] = cl.s
196 if cl.kind == kindAge {
197 parts[i] = stamp(cl.s)
198 }
199 }
200 fmt.Fprintf(w, " %s\n", strings.Join(parts, "\t"))
201 }
202 } 182 }
203 itemRows := func(items []DashboardItem, marker string) [][]cell { 183 if !policy.CanRead(c.User, r, grant) {
204 rows := make([][]cell, len(items)) 184 continue
205 for i, item := range items {
206 page := "issues"
207 if marker == "!" {
208 page = "mrs"
209 }
210 ref := cLink(fmt.Sprintf("%s%s%d", item.Repo, marker, item.Number), c.siteURL(item.Repo, page, strconv.FormatInt(item.Number, 10)))
211 rows[i] = []cell{ref, cFlex(item.Title), cText(item.Author)}
212 }
213 return rows
214 } 185 }
186 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
187 out = append(out, PinnedOut{r.Path(), r.Visibility, desc, r.Settings.Archived})
188 }
189 return out, nil
190}
215 191
216 if d.Unread > 0 { 192// writeDashboard is `dashboard` as text: one section per list, then the
217 fmt.Fprintf(w, "unread notifications: %d\n", d.Unread) 193// server's build and queues for an admin.
218 } 194func writeDashboard(c *Ctx, w io.Writer, d DashboardOut, lines []FeedLine) {
219 section("waiting on your review:", itemRows(d.Reviews, "!")) 195 section := func(title string, rows [][]cell) { writeDashboardSection(w, title, rows) }
220 section("assigned to you:", itemRows(d.Assigned, "#")) 196 itemRows := func(items []DashboardItem, marker string) [][]cell {
221 section("open merge requests:", itemRows(d.MRs, "!")) 197 rows := make([][]cell, len(items))
222 section("open issues:", itemRows(d.Issues, "#")) 198 for i, item := range items {
223 for _, q := range d.Queries { 199 page := "issues"
224 rows := make([][]cell, 0, len(q.Items)) 200 if marker == "!" {
225 for _, it := range q.Items { 201 page = "mrs"
226 rows = append(rows, []cell{cRef(it.Ref()), cFlex(it.Title), cText(it.Author)})
227 }
228 title := fmt.Sprintf("query %s (%d):", q.Name, q.Count)
229 if q.Error != "" {
230 title = fmt.Sprintf("query %s: %s", q.Name, q.Error)
231 } 202 }
232 section(title, rows) 203 ref := cLink(fmt.Sprintf("%s%s%d", item.Repo, marker, item.Number), c.siteURL(item.Repo, page, strconv.FormatInt(item.Number, 10)))
204 rows[i] = []cell{ref, cFlex(item.Title), cText(item.Author)}
233 } 205 }
206 return rows
207 }
234 208
235 pinnedRows := make([][]cell, len(d.Pinned)) 209 if d.Unread > 0 {
236 for i, p := range d.Pinned { 210 fmt.Fprintf(w, "unread notifications: %d\n", d.Unread)
237 cells := []cell{cLink(p.Path, c.siteURL(p.Path)), cState(p.Visibility), cFlex(p.Description)} 211 }
238 if p.Archived { 212 section("waiting on your review:", itemRows(d.Reviews, "!"))
239 cells = c.note(cells, 1, "[archived]", "archived") 213 section("assigned to you:", itemRows(d.Assigned, "#"))
240 } 214 section("open merge requests:", itemRows(d.MRs, "!"))
241 pinnedRows[i] = cells 215 section("open issues:", itemRows(d.Issues, "#"))
216 for _, q := range d.Queries {
217 rows := make([][]cell, 0, len(q.Items))
218 for _, it := range q.Items {
219 rows = append(rows, []cell{cRef(it.Ref()), cFlex(it.Title), cText(it.Author)})
242 } 220 }
243 section("pinned:", pinnedRows) 221 title := fmt.Sprintf("query %s (%d):", q.Name, q.Count)
244 222 if q.Error != "" {
245 activityRows := make([][]cell, len(lines)) 223 title = fmt.Sprintf("query %s: %s", q.Name, q.Error)
246 for i, l := range lines {
247 activityRows[i] = []cell{cAge(l.When), cFlex(l.Sentence())}
248 } 224 }
249 section("recent activity:", activityRows) 225 section(title, rows)
226 }
250 227
251 buildRows := make([][]cell, len(d.Builds)) 228 pinnedRows := make([][]cell, len(d.Pinned))
252 for i, b := range d.Builds { 229 for i, p := range d.Pinned {
253 buildRows[i] = []cell{cLink(b.Repo, c.siteURL(b.Repo, "builds", strconv.FormatInt(b.Number, 10))), cNum(b.Number), cText(b.Job), cState(b.Status), cRef(fmt.Sprintf("%.10s", b.SHA)), cText(b.Ref)} 230 cells := []cell{cLink(p.Path, c.siteURL(p.Path)), cState(p.Visibility), cFlex(p.Description)}
231 if p.Archived {
232 cells = c.note(cells, 1, "[archived]", "archived")
254 } 233 }
255 section("builds:", buildRows) 234 pinnedRows[i] = cells
235 }
236 section("pinned:", pinnedRows)
256 237
257 if d.Server != nil { 238 activityRows := make([][]cell, len(lines))
258 heading("server:") 239 for i, l := range lines {
259 fmt.Fprintf(w, " build %s\n", d.Server.Commit) 240 activityRows[i] = []cell{cAge(l.When), cFlex(l.Sentence())}
260 } 241 }
261 if q := d.Queues; q != nil { 242 section("recent activity:", activityRows)
262 heading("queues:")
263 243
264 fmt.Fprintf(w, " webhooks\tpending %d\tretrying %d\tfailed %d\n", q.Webhooks.Pending, q.Webhooks.Retrying, q.Webhooks.Failed) 244 buildRows := make([][]cell, len(d.Builds))
265 twh := c.table(w, "REPO", "URL", "ATTEMPTS", "ERROR") 245 for i, b := range d.Builds {
266 for _, it := range q.Webhooks.Items { 246 buildRows[i] = []cell{cLink(b.Repo, c.siteURL(b.Repo, "builds", strconv.FormatInt(b.Number, 10))), cNum(b.Number), cText(b.Job), cState(b.Status), cRef(fmt.Sprintf("%.10s", b.SHA)), cText(b.Ref)}
267 twh.row(cRef(" "+it.Repo), cText(it.URL), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) 247 }
268 } 248 section("builds:", buildRows)
269 twh.flush()
270 249
271 fmt.Fprintf(w, " mail\tpending %d\tretrying %d\tfailed %d\n", q.Mail.Pending, q.Mail.Retrying, q.Mail.Failed) 250 if d.Server != nil {
272 tma := c.table(w, "RECIPIENT", "SUBJECT", "ATTEMPTS", "ERROR") 251 fmt.Fprintln(w, "server:")
273 for _, it := range q.Mail.Items { 252 fmt.Fprintf(w, " build %s\n", d.Server.Commit)
274 tma.row(cRef(" "+it.Recipient), cText(it.Subject), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) 253 }
275 } 254 if d.Queues != nil {
276 tma.flush() 255 writeQueues(c, w, *d.Queues)
256 }
257}
277 258
278 // The device id, not the token: a token is never echoed. 259// writeDashboardSection is a titled list of tab-separated rows, or "none".
279 fmt.Fprintf(w, " push\tpending %d\tretrying %d\tfailed %d\n", q.Push.Pending, q.Push.Retrying, q.Push.Failed) 260func writeDashboardSection(w io.Writer, title string, rows [][]cell) {
280 tpu := c.table(w, "DEVICE", "TITLE", "ATTEMPTS", "ERROR") 261 fmt.Fprintln(w, title)
281 for _, it := range q.Push.Items { 262 if len(rows) == 0 {
282 tpu.row(cRef(fmt.Sprintf(" device %d", it.DeviceID)), cText(it.Title), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError)) 263 fmt.Fprintln(w, " none")
264 return
265 }
266 for _, r := range rows {
267 parts := make([]string, len(r))
268 for i, cl := range r {
269 parts[i] = cl.s
270 if cl.kind == kindAge {
271 parts[i] = stamp(cl.s)
283 } 272 }
284 tpu.flush() 273 }
274 fmt.Fprintf(w, " %s\n", strings.Join(parts, "\t"))
275 }
276}
285 277
286 fmt.Fprintf(w, " mirrors\tdirty %d\terrors %d\n", q.Mirrors.Dirty, q.Mirrors.Errors) 278// writeQueues is each background queue's counts and stuck items.
287 tmi := c.table(w, "REPO", "DIRECTION", "URL", "ERROR") 279func writeQueues(c *Ctx, w io.Writer, q store.Queues) {
288 for _, it := range q.Mirrors.Items { 280 fmt.Fprintln(w, "queues:")
289 tmi.row(cRef(" "+it.Repo), cText(it.Direction), cText(it.URL), cText(it.LastError))
290 }
291 tmi.flush()
292
293 fmt.Fprintf(w, " builds\tpending %d\trunning %d\n", q.Builds.Pending, q.Builds.Running)
294 tbq := c.table(w, "REPO", "#", "JOB", "STATUS")
295 for _, it := range q.Builds.Items {
296 since := it.StartedAt
297 if it.Status == "pending" {
298 since = it.CreatedAt
299 }
300 since = stamp(since)
301 tbq.row(cRef(" "+it.Repo), cNum(it.Number), cText(it.Job), cText(fmt.Sprintf("%s since %s", it.Status, since)))
302 }
303 tbq.flush()
304 281
305 fmt.Fprintf(w, " deps\terrors %d\n", q.Deps.Errors) 282 fmt.Fprintf(w, " webhooks\tpending %d\tretrying %d\tfailed %d\n", q.Webhooks.Pending, q.Webhooks.Retrying, q.Webhooks.Failed)
306 tde := c.table(w, "REPO", "ERROR") 283 twh := c.table(w, "REPO", "URL", "ATTEMPTS", "ERROR")
307 for _, it := range q.Deps.Items { 284 for _, it := range q.Webhooks.Items {
308 tde.row(cRef(" "+it.Repo), cText(it.LastError)) 285 twh.row(cRef(" "+it.Repo), cText(it.URL), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
309 } 286 }
310 tde.flush() 287 twh.flush()
288
289 fmt.Fprintf(w, " mail\tpending %d\tretrying %d\tfailed %d\n", q.Mail.Pending, q.Mail.Retrying, q.Mail.Failed)
290 tma := c.table(w, "RECIPIENT", "SUBJECT", "ATTEMPTS", "ERROR")
291 for _, it := range q.Mail.Items {
292 tma.row(cRef(" "+it.Recipient), cText(it.Subject), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
293 }
294 tma.flush()
295
296 // The device id, not the token: a token is never echoed.
297 fmt.Fprintf(w, " push\tpending %d\tretrying %d\tfailed %d\n", q.Push.Pending, q.Push.Retrying, q.Push.Failed)
298 tpu := c.table(w, "DEVICE", "TITLE", "ATTEMPTS", "ERROR")
299 for _, it := range q.Push.Items {
300 tpu.row(cRef(fmt.Sprintf(" device %d", it.DeviceID)), cText(it.Title), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
301 }
302 tpu.flush()
303
304 fmt.Fprintf(w, " mirrors\tdirty %d\terrors %d\n", q.Mirrors.Dirty, q.Mirrors.Errors)
305 tmi := c.table(w, "REPO", "DIRECTION", "URL", "ERROR")
306 for _, it := range q.Mirrors.Items {
307 tmi.row(cRef(" "+it.Repo), cText(it.Direction), cText(it.URL), cText(it.LastError))
308 }
309 tmi.flush()
310
311 fmt.Fprintf(w, " builds\tpending %d\trunning %d\n", q.Builds.Pending, q.Builds.Running)
312 tbq := c.table(w, "REPO", "#", "JOB", "STATUS")
313 for _, it := range q.Builds.Items {
314 since := it.StartedAt
315 if it.Status == "pending" {
316 since = it.CreatedAt
311 } 317 }
312 }, func() screen { return dashboardScreen(c, d, lines) }) 318 since = stamp(since)
319 tbq.row(cRef(" "+it.Repo), cNum(it.Number), cText(it.Job), cText(fmt.Sprintf("%s since %s", it.Status, since)))
320 }
321 tbq.flush()
322
323 fmt.Fprintf(w, " deps\terrors %d\n", q.Deps.Errors)
324 tde := c.table(w, "REPO", "ERROR")
325 for _, it := range q.Deps.Items {
326 tde.row(cRef(" "+it.Repo), cText(it.LastError))
327 }
328 tde.flush()
313} 329}
314 330
315// feedDefaultLimit caps a bare `feed` call; pagination reaches further 331// feedDefaultLimit caps a bare `feed` call; pagination reaches further