internal/control/profile.go
406 lines · 12671 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "sort"
8 "strings"
9 "time"
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{"profile", "show"},
19 Summary: "show a user's or org's profile",
20 Usage: "profile show [name]", ReadOnly: true, Run: runProfileShow})
21 register(Command{Path: []string{"profile", "set"},
22 Summary: "set your profile",
23 Usage: "profile set [--description <d>] [--website <url>] [--about <text>|--file -] [--about-format md|org] [--link <label|url>]... ('' clears)", ReadsStdin: true, Run: runProfileSet})
24 register(Command{Path: []string{"org", "profile"},
25 Summary: "show or set an org's profile",
26 Usage: "org profile <org> [--description <d>] [--website <url>] [--about <text>|--file -] [--about-format md|org] [--link <label|url>]...", ReadsStdin: true, Run: runOrgProfile})
27}
28
29// maxProfileLinks caps the free-form link list. A profile is a header,
30// not a linktree.
31const maxProfileLinks = 5
32
33// profileEdit is the set of profile fields a command may change. A nil
34// field is left alone; an empty value clears it.
35type profileEdit struct {
36 Description *string
37 Website *string
38 About *string
39 AboutFormat *string
40 Links *[]store.ProfileLink
41}
42
43func (e profileEdit) empty() bool {
44 return e.Description == nil && e.Website == nil && e.About == nil &&
45 e.AboutFormat == nil && e.Links == nil
46}
47
48// parseProfileFlags pulls the profile flags out of args. --about takes
49// inline text or reads stdin via --file -; --link repeats, and a single
50// empty --link clears the list.
51func parseProfileFlags(c *Ctx, args []string) (rest []string, e profileEdit, err error) {
52 about, file := "", ""
53 sawAbout := false
54 var links []store.ProfileLink
55 f, err := parseFlags(args, flagSpec{Values: []string{"--description", "--website", "--about", "--about-format", "--file"}, Multi: []string{"--link"}, MaxPos: -1})
56 if err != nil {
57 return nil, e, err
58 }
59 rest = f.Pos
60 for _, name := range []string{"--description", "--website", "--about-format"} {
61 if !f.Has(name) {
62 continue
63 }
64 v := f.Value(name)
65 switch name {
66 case "--description":
67 e.Description = &v
68 case "--website":
69 e.Website = &v
70 case "--about-format":
71 e.AboutFormat = &v
72 }
73 }
74 if f.Has("--about") {
75 about, sawAbout = f.Value("--about"), true
76 }
77 if f.Has("--file") {
78 file, sawAbout = f.Value("--file"), true
79 }
80 for _, v := range f.List("--link") {
81 if v == "" {
82 links = nil
83 e.Links = &links
84 continue
85 }
86 l, lerr := parseProfileLink(v)
87 if lerr != nil {
88 return nil, e, lerr
89 }
90 links = append(links, l)
91 e.Links = &links
92 }
93 if sawAbout {
94 body, berr := bodyFrom(c, about, file)
95 if berr != nil {
96 return nil, e, berr
97 }
98 e.About = &body
99 }
100 if len(links) > maxProfileLinks {
101 return nil, e, fmt.Errorf("at most %d links", maxProfileLinks)
102 }
103 return rest, e, nil
104}
105
106// parseProfileLink splits "label|url"; without a separator the whole
107// value is the URL.
108func parseProfileLink(v string) (store.ProfileLink, error) {
109 label, url, ok := strings.Cut(v, "|")
110 if !ok {
111 label, url = "", v
112 }
113 label = strings.TrimSpace(label)
114 if len(label) > 32 {
115 label = label[:32]
116 }
117 url = strings.TrimSpace(url)
118 if url == "" {
119 return store.ProfileLink{}, errors.New("a link needs a url")
120 }
121 if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
122 return store.ProfileLink{}, errors.New("link url must start with https:// or http://")
123 }
124 return store.ProfileLink{Label: label, URL: url}, nil
125}
126
127func validateWebsite(url string) error {
128 if url == "" || strings.HasPrefix(url, "https://") || strings.HasPrefix(url, "http://") {
129 return nil
130 }
131 return errors.New("website must start with https:// or http://")
132}
133
134func applyProfile(p store.Profile, e profileEdit) (store.Profile, error) {
135 if e.Description != nil {
136 d, _, _ := strings.Cut(strings.TrimSpace(*e.Description), "\n")
137 if len(d) > 256 {
138 d = d[:256]
139 }
140 p.Description = d
141 }
142 if e.Website != nil {
143 s := strings.TrimSpace(*e.Website)
144 if err := validateWebsite(s); err != nil {
145 return p, err
146 }
147 p.Website = s
148 }
149 if e.About != nil {
150 p.About = strings.TrimSpace(*e.About)
151 }
152 if e.AboutFormat != nil {
153 f := strings.TrimSpace(*e.AboutFormat)
154 if f != "md" && f != "org" {
155 return p, errors.New("about format must be md or org")
156 }
157 p.AboutFormat = f
158 }
159 if e.Links != nil {
160 p.Links = *e.Links
161 }
162 return p, nil
163}
164
165type ProfileOut struct {
166 Name string `json:"name"`
167 Kind string `json:"kind"`
168 Description string `json:"description,omitempty"`
169 Website string `json:"website,omitempty"`
170 // About is long-form markdown, rendered by the web between the
171 // header and the activity graph.
172 About string `json:"about,omitempty"`
173 AboutFormat string `json:"about_format,omitempty"`
174 Links []store.ProfileLink `json:"links,omitempty"`
175 // The rest is what a profile page shows: who they work with, what
176 // they own that you can see, and how active they have been. The web
177 // read these straight out of the store, which kept them off every
178 // other surface.
179 Orgs []ProfileMember `json:"orgs,omitempty"` // for a user
180 Members []ProfileMember `json:"members,omitempty"` // for an org
181 Repos []ProfileRepo `json:"repos"`
182 Activity []ActivityDay `json:"activity,omitempty"`
183 // ActivityTotal counts the same window the days cover.
184 ActivityTotal int `json:"activity_total"`
185}
186
187type ProfileMember struct {
188 Name string `json:"name"`
189 Role string `json:"role,omitempty"`
190}
191
192// ProfileRepo is one repository as a profile lists it. The listing
193// metadata — topics, license, last commit — is here because a profile is
194// a listing: a client that renders repositories without it is showing
195// less than the web does, which is why the web kept its own copy.
196type ProfileRepo struct {
197 Path string `json:"path"`
198 Visibility string `json:"visibility"`
199 Description string `json:"description,omitempty"`
200 DefaultBranch string `json:"default_branch"`
201 Topics []string `json:"topics,omitempty"`
202 License string `json:"license,omitempty"`
203 Updated string `json:"updated,omitempty"`
204 Archived bool `json:"archived,omitempty"`
205}
206
207// ActivityDay is one day's contribution count. Days with nothing are
208// omitted; a client fills the calendar it wants to draw.
209type ActivityDay struct {
210 Date string `json:"date"`
211 Count int `json:"count"`
212}
213
214// ActivityWindow is the span a profile reports: the start of the web's
215// 53-week calendar, so every surface shows the same year.
216func ActivityWindow() string {
217 today := time.Now().UTC()
218 end := today.AddDate(0, 0, int(time.Saturday-today.Weekday()))
219 return end.AddDate(0, 0, -53*7+1).Format("2006-01-02")
220}
221
222func emitProfile(c *Ctx, d ProfileOut) int {
223 return c.emit(d, func(w io.Writer) {
224 fmt.Fprintf(w, "%s (%s)\n", d.Name, d.Kind)
225 if d.Description != "" {
226 fmt.Fprintf(w, "%s\n", d.Description)
227 }
228 if d.Website != "" {
229 fmt.Fprintf(w, "%s\n", d.Website)
230 }
231 for _, l := range d.Links {
232 fmt.Fprintf(w, "link\t%s\t%s\n", l.Label, l.URL)
233 }
234 for _, m := range d.Orgs {
235 fmt.Fprintf(w, "org\t%s\t%s\n", m.Name, m.Role)
236 }
237 for _, m := range d.Members {
238 fmt.Fprintf(w, "member\t%s\t%s\n", m.Name, m.Role)
239 }
240 for _, r := range d.Repos {
241 fmt.Fprintf(w, "repo\t%s\t%s\t%s\n", r.Path, r.Visibility, r.Description)
242 }
243 if d.ActivityTotal > 0 {
244 fmt.Fprintf(w, "activity\t%d in the last year\n", d.ActivityTotal)
245 }
246 if d.About != "" {
247 fmt.Fprintf(w, "\n%s\n", d.About)
248 }
249 })
250}
251
252func runProfileShow(c *Ctx, args []string) int {
253 name := c.User.Username
254 if len(args) == 1 {
255 name = args[0]
256 } else if len(args) > 1 {
257 return c.fail(protocol.ExitUsage, "usage: profile show [name]")
258 }
259 kind, id := "", int64(0)
260 if u, err := c.Store.UserByUsername(name); err == nil {
261 kind, id = "user", u.ID
262 } else if o, err := c.Store.OrgByName(name); err == nil {
263 kind, id = "org", o.ID
264 } else {
265 return c.fail(protocol.ExitNotFound, "no user or organization %q", name)
266 }
267 p, err := c.Store.OwnerProfile(kind, id)
268 if err != nil {
269 return c.fail(protocol.ExitFailure, "%v", err)
270 }
271 d := ProfileOut{Name: name, Kind: kind, Description: p.Description, Website: p.Website,
272 About: p.About, AboutFormat: p.AboutFormat, Links: p.Links, Repos: []ProfileRepo{}}
273
274 // Who they work with. Both lists are public on a profile — the web
275 // has always shown them — and neither exposes anything a member
276 // listing would not.
277 if kind == "user" {
278 orgs, err := c.Store.ListOrgsForUser(id)
279 if err != nil {
280 return c.fail(protocol.ExitFailure, "%v", err)
281 }
282 for _, o := range orgs {
283 d.Orgs = append(d.Orgs, ProfileMember{Name: o.Username, Role: o.Role})
284 }
285 } else {
286 members, err := c.Store.OrgMembers(id)
287 if err != nil {
288 return c.fail(protocol.ExitFailure, "%v", err)
289 }
290 for _, m := range members {
291 d.Members = append(d.Members, ProfileMember{Name: m.Username, Role: m.Role})
292 }
293 }
294
295 // Only repositories this caller may read: a private repo must not
296 // surface on a profile any more than it does in a listing.
297 all, err := c.Store.ListReposForOwner(kind, id)
298 if err != nil {
299 return c.fail(protocol.ExitFailure, "%v", err)
300 }
301 for _, repo := range all {
302 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
303 if err != nil {
304 return c.fail(protocol.ExitFailure, "%v", err)
305 }
306 if !policy.CanRead(c.User, repo, grant) {
307 continue
308 }
309 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
310 topics, err := c.Store.ListTopics(repo.ID)
311 if err != nil {
312 return c.fail(protocol.ExitFailure, "%v", err)
313 }
314 d.Repos = append(d.Repos, ProfileRepo{
315 Path: repo.Path(),
316 Visibility: repo.Visibility,
317 Description: gitutil.ReadDescription(dir),
318 DefaultBranch: repo.DefaultBranch,
319 Topics: topics,
320 License: DetectLicense(dir, repo.DefaultBranch),
321 Updated: gitutil.LastCommitDate(dir, repo.DefaultBranch),
322 Archived: repo.Settings.Archived,
323 })
324 }
325
326 var counts map[string]int
327 if kind == "user" {
328 counts, err = c.Store.ActivityByDay(id, ActivityWindow())
329 } else {
330 counts, err = c.Store.OrgActivityByDay(id, ActivityWindow())
331 }
332 if err != nil {
333 return c.fail(protocol.ExitFailure, "%v", err)
334 }
335 days := make([]string, 0, len(counts))
336 for day := range counts {
337 days = append(days, day)
338 }
339 sort.Strings(days)
340 for _, day := range days {
341 d.Activity = append(d.Activity, ActivityDay{Date: day, Count: counts[day]})
342 d.ActivityTotal += counts[day]
343 }
344 return emitProfile(c, d)
345}
346
347func runProfileSet(c *Ctx, args []string) int {
348 rest, e, err := parseProfileFlags(c, args)
349 if err != nil {
350 return c.failInput(err)
351 }
352 if len(rest) != 0 {
353 return c.fail(protocol.ExitUsage,
354 "usage: profile set [--description <d>] [--website <url>] [--about <text>|--file -] [--about-format md|org] [--link <label|url>]...")
355 }
356 if e.empty() {
357 return c.fail(protocol.ExitUsage, "nothing to set: pass --description, --website, --about and/or --link")
358 }
359 p, err := c.Store.OwnerProfile("user", c.User.ID)
360 if err != nil {
361 return c.fail(protocol.ExitFailure, "%v", err)
362 }
363 p, err = applyProfile(p, e)
364 if err != nil {
365 return c.failInput(err)
366 }
367 if err := c.Store.SetOwnerProfile("user", c.User.ID, p); err != nil {
368 return c.fail(protocol.ExitFailure, "%v", err)
369 }
370 return emitProfile(c, ProfileOut{Name: c.User.Username, Kind: "user",
371 Description: p.Description, Website: p.Website, About: p.About,
372 AboutFormat: p.AboutFormat, Links: p.Links, Repos: []ProfileRepo{}})
373}
374
375func runOrgProfile(c *Ctx, args []string) int {
376 rest, e, err := parseProfileFlags(c, args)
377 if err != nil {
378 return c.failInput(err)
379 }
380 if len(rest) != 1 {
381 return c.fail(protocol.ExitUsage,
382 "usage: org profile <org> [--description <d>] [--website <url>] [--about <text>|--file -] [--about-format md|org] [--link <label|url>]...")
383 }
384 name := rest[0]
385 if e.empty() {
386 return runProfileShow(c, []string{name})
387 }
388 org, code := orgAdmin(c, name)
389 if code >= 0 {
390 return code
391 }
392 p, err := c.Store.OwnerProfile("org", org.ID)
393 if err != nil {
394 return c.fail(protocol.ExitFailure, "%v", err)
395 }
396 p, err = applyProfile(p, e)
397 if err != nil {
398 return c.failInput(err)
399 }
400 if err := c.Store.SetOwnerProfile("org", org.ID, p); err != nil {
401 return c.fail(protocol.ExitFailure, "%v", err)
402 }
403 return emitProfile(c, ProfileOut{Name: org.Name, Kind: "org",
404 Description: p.Description, Website: p.Website, About: p.About,
405 AboutFormat: p.AboutFormat, Links: p.Links, Repos: []ProfileRepo{}})
406}