internal/control/repo.go
1546 lines · 54530 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 "path"
9 "path/filepath"
10 "slices"
11 "strconv"
12 "strings"
13
14 "gitbay.org/gitbay/internal/backuplock"
15 "gitbay.org/gitbay/internal/gitutil"
16 "gitbay.org/gitbay/internal/leaks"
17 "gitbay.org/gitbay/internal/policy"
18 "gitbay.org/gitbay/internal/protocol"
19 "gitbay.org/gitbay/internal/store"
20)
21
22// RepoDir returns the on-disk path for a repository.
23func RepoDir(root, owner, name string) string {
24 return filepath.Join(root, "repos", owner, name+".git")
25}
26
27// HooksDir is the shared core.hooksPath directory.
28func HooksDir(root string) string { return filepath.Join(root, "hooks") }
29
30func init() {
31 register(Command{Path: []string{"repo", "create"},
32 Summary: "create a repository",
33 Usage: "repo create <owner/name> [--private]",
34 Flags: []Flag{
35 {"--private", "", "create it private", ""},
36 },
37 Examples: []string{"repo create krz/newthing --private"},
38 Run: runRepoCreate})
39 register(Command{Path: []string{"repo", "list"},
40 Summary: "list repositories you own or can access",
41 Usage: "repo list [--limit <n>] [--cursor <c>]",
42 Flags: []Flag{
43 {"--limit", "<n>", "rows per page", ""},
44 {"--cursor", "<c>", "continue from the previous page", ""},
45 },
46 Examples: []string{"repo list --limit 20"},
47 ReadOnly: true, Run: runRepoList})
48 register(Command{Path: []string{"repo", "show"},
49 Summary: "show repository details",
50 Usage: "repo show <owner/name>",
51 Examples: []string{"repo show krz/gitbay"},
52 ReadOnly: true, Run: runRepoShow})
53 register(Command{Path: []string{"repo", "transfer"},
54 NeedsRecentSignIn: true,
55 Summary: "move a repository to another owner",
56 Usage: "repo transfer <owner/name> <new-owner> (clone URLs change)",
57 Examples: []string{"repo transfer krz/gitbay krazywarez"},
58 Run: runRepoTransfer})
59 register(Command{Path: []string{"repo", "rename"},
60 NeedsRecentSignIn: true,
61 Summary: "rename a repository",
62 Usage: "repo rename <owner/name> <new-name> (clone URLs change)",
63 Examples: []string{"repo rename krz/gitbay forge"},
64 Run: runRepoRename})
65 register(Command{Path: []string{"repo", "delete"},
66 NeedsRecentSignIn: true,
67 Summary: "delete a repository",
68 Usage: "repo delete <owner/name> --yes",
69 Flags: []Flag{
70 {"--yes", "", "confirm the permanent delete", ""},
71 },
72 Examples: []string{"repo delete cmc/scratch --yes"},
73 Run: runRepoDelete})
74 register(Command{Path: []string{"repo", "access", "grant"},
75 NeedsRecentSignIn: true,
76 Summary: "grant access",
77 Usage: "repo access grant <owner/name> <user> read|write|admin",
78 Examples: []string{"repo access grant krz/gitbay cmc write"},
79 Run: runAccessGrant})
80 register(Command{Path: []string{"repo", "access", "revoke"},
81 Summary: "revoke access",
82 Usage: "repo access revoke <owner/name> <user>",
83 Examples: []string{"repo access revoke krz/gitbay cmc"},
84 Run: runAccessRevoke})
85 register(Command{Path: []string{"repo", "access", "list"},
86 Summary: "list who can reach the repository, with the role and where it comes from",
87 Usage: "repo access list <owner/name>",
88 Examples: []string{"repo access list krz/gitbay"},
89 ReadOnly: true, Run: runAccessList})
90 register(Command{Path: []string{"repo", "settings", "show"},
91 Summary: "show settings",
92 Usage: "repo settings show <owner/name>",
93 Examples: []string{"repo settings show krz/gitbay"},
94 ReadOnly: true, Run: runSettingsShow})
95 register(Command{Path: []string{"repo", "settings", "protect"},
96 Summary: "protect a branch",
97 Usage: "repo settings protect <owner/name> <branch>",
98 Examples: []string{"repo settings protect krz/gitbay main"},
99 Run: runProtect})
100 register(Command{Path: []string{"repo", "settings", "unprotect"},
101 Summary: "unprotect a branch",
102 Usage: "repo settings unprotect <owner/name> <branch>",
103 Examples: []string{"repo settings unprotect krz/gitbay main"},
104 Run: runUnprotect})
105 register(Command{Path: []string{"repo", "settings", "protect-tag"},
106 Summary: "protect tags matching a glob (created once, never moved or deleted)",
107 Usage: "repo settings protect-tag <owner/name> <glob>",
108 Examples: []string{"repo settings protect-tag krz/gitbay 'v*'"},
109 Run: runProtectTag})
110 register(Command{Path: []string{"repo", "settings", "unprotect-tag"},
111 Summary: "drop a protected-tag glob",
112 Usage: "repo settings unprotect-tag <owner/name> <glob>",
113 Examples: []string{"repo settings unprotect-tag krz/gitbay 'v*'"},
114 Run: runUnprotectTag})
115 register(Command{Path: []string{"repo", "settings", "description"},
116 Summary: "set the repository description",
117 Usage: "repo settings description <owner/name> <text> ('' clears)",
118 Examples: []string{`repo settings description krz/gitbay "a CLI-first git forge"`},
119 Run: runSetDescription})
120 register(Command{Path: []string{"repo", "settings", "visibility"},
121 Summary: "set repository visibility",
122 Usage: "repo settings visibility <owner/name> public|private",
123 Examples: []string{"repo settings visibility krz/gitbay public"},
124 // Making a repository public shows it to everyone.
125 NeedsRecentSignIn: true,
126 Run: runSetVisibility})
127 register(Command{Path: []string{"repo", "settings", "website"},
128 Summary: "set the repository website",
129 Usage: "repo settings website <owner/name> <url> ('' clears)",
130 Examples: []string{"repo settings website krz/gitbay https://gitbay.org"},
131 Run: runSetWebsite})
132 register(Command{Path: []string{"repo", "settings", "default-branch"},
133 Summary: "set the default branch",
134 Usage: "repo settings default-branch <owner/name> <branch>",
135 Examples: []string{"repo settings default-branch krz/gitbay main"},
136 Run: runSetDefaultBranch})
137 register(Command{Path: []string{"repo", "settings", "git-daemon"},
138 Summary: "expose over git://",
139 Usage: "repo settings git-daemon <owner/name> on|off",
140 Examples: []string{"repo settings git-daemon krz/gitbay on"},
141 Run: runGitDaemon})
142 register(Command{Path: []string{"repo", "archive"},
143 Summary: "archive a repository (read-only: pushes and issue/MR writes refused)",
144 Usage: "repo archive <owner/name>",
145 Examples: []string{"repo archive krz/gitbay"},
146 Run: runArchive})
147 register(Command{Path: []string{"repo", "unarchive"},
148 Summary: "unarchive a repository",
149 Usage: "repo unarchive <owner/name>",
150 Examples: []string{"repo unarchive krz/gitbay"},
151 Run: runUnarchive})
152 register(Command{Path: []string{"repo", "topics"},
153 Summary: "list topics",
154 Usage: "repo topics <owner/name>",
155 Examples: []string{"repo topics krz/gitbay"},
156 ReadOnly: true, Run: runTopicsList})
157 register(Command{Path: []string{"repo", "topics", "add"},
158 Summary: "add topics",
159 Usage: "repo topics add <owner/name> <topic>...",
160 Examples: []string{"repo topics add krz/gitbay git forge cli"},
161 Run: runTopicsAdd})
162 register(Command{Path: []string{"repo", "topics", "remove"},
163 Summary: "remove topics",
164 Usage: "repo topics remove <owner/name> <topic>...",
165 Examples: []string{"repo topics remove krz/gitbay cli"},
166 Run: runTopicsRemove})
167 register(Command{Path: []string{"repo", "search"},
168 Summary: "find repositories by name, description, or topic",
169 Usage: "repo search <query>",
170 Examples: []string{"repo search forge"},
171 ReadOnly: true, Run: runRepoSearch})
172 register(Command{Path: []string{"repo", "grep"},
173 Summary: "search file contents",
174 Usage: "repo grep <owner/name> <query> [--ref <ref>]",
175 Flags: []Flag{
176 {"--ref", "<ref>", "branch, tag or commit to search", "the default branch"},
177 },
178 Examples: []string{"repo grep krz/gitbay TODO"},
179 ReadOnly: true, Run: runRepoGrep})
180 register(Command{Path: []string{"repo", "diff"},
181 Summary: "the patch between two refs, from their merge base",
182 Usage: "repo diff <owner/name> <base> <head>",
183 Examples: []string{"repo diff krz/gitbay main cli-output-help"},
184 ReadOnly: true, Run: runRepoDiff})
185 register(Command{Path: []string{"repo", "pin"},
186 Summary: "pin a repository to your dashboard",
187 Usage: "repo pin <owner/name>",
188 Examples: []string{"repo pin krz/gitbay"},
189 Run: runRepoPin})
190 register(Command{Path: []string{"repo", "unpin"},
191 Summary: "unpin a repository",
192 Usage: "repo unpin <owner/name>",
193 Examples: []string{"repo unpin krz/gitbay"},
194 Run: runRepoUnpin})
195 register(Command{Path: []string{"repo", "bookmark"},
196 Summary: "bookmark a repository to come back to",
197 Usage: "repo bookmark <owner/name>",
198 Examples: []string{"repo bookmark krz/gitbay"},
199 Run: runRepoBookmark})
200 register(Command{Path: []string{"repo", "unbookmark"},
201 Summary: "remove a bookmark",
202 Usage: "repo unbookmark <owner/name>",
203 Examples: []string{"repo unbookmark krz/gitbay"},
204 Run: runRepoUnbookmark})
205 register(Command{Path: []string{"repo", "bookmarks"},
206 Summary: "list the repositories you have bookmarked",
207 Usage: "repo bookmarks",
208 Examples: []string{"repo bookmarks"},
209 ReadOnly: true, Run: runRepoBookmarks})
210}
211
212const (
213 minQueryLen = 2
214 maxQueryLen = 200
215 maxGrepMatches = 200
216)
217
218func validQuery(q string) error {
219 if len(q) < minQueryLen || len(q) > maxQueryLen {
220 return fmt.Errorf("query must be %d to %d characters", minQueryLen, maxQueryLen)
221 }
222 return nil
223}
224
225// refuseArchived blocks content writes (pushes are refused in the transport
226// layer) on archived repositories. Settings, access, and lifecycle commands
227// stay available so an archived repo can be managed and unarchived.
228func refuseArchived(c *Ctx, repo store.Repo) int {
229 if repo.Settings.Archived {
230 return c.fail(protocol.ExitDenied, "%s is archived and read-only; unarchive it first", repo.Path())
231 }
232 return -1
233}
234
235// resolveRepo loads a repo and checks the given permission for c.User.
236func resolveRepo(c *Ctx, path string, check func(store.User, store.Repo, string) bool) (store.Repo, int) {
237 repo, err := c.Store.RepoByPath(path)
238 if err != nil {
239 if errors.Is(err, store.ErrNotFound) {
240 // Same message whether it doesn't exist or is invisible.
241 return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
242 }
243 return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
244 }
245 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
246 if err != nil {
247 return repo, c.fail(protocol.ExitFailure, "checking access: %v", err)
248 }
249 if !check(c.User, repo, grant) {
250 if !policy.CanRead(c.User, repo, grant) {
251 // Invisible repos 404, per the enumeration rule.
252 return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
253 }
254 return repo, c.fail(protocol.ExitDenied, "permission denied on %s; ask its owner for access", path)
255 }
256 return repo, -1
257}
258
259func runRepoCreate(c *Ctx, args []string) int {
260 f, err := c.parseArgs(args, flagSpec{Values: []string{"--description"}, Bools: []string{"--private"}, MaxPos: 1, Usage: "repo create <owner/name> [--private] [--description <text>]"})
261 if err != nil {
262 return c.fail(protocol.ExitUsage, "%v", err)
263 }
264 visibility, path, description := "public", f.pos(0), f.Value("--description")
265 if f.Has("--private") {
266 visibility = "private"
267 }
268 owner, name, ok := strings.Cut(path, "/")
269 if !ok {
270 return c.usage()
271 }
272 if err := policyValidateRepoName(name); err != nil {
273 return c.failInput(err)
274 }
275 ownerKind, ownerID, code := resolveNewRepoOwner(c, owner)
276 if code >= 0 {
277 return code
278 }
279 repoCreateMu.Lock()
280 if code := checkRepoQuota(c, ownerKind, ownerID); code >= 0 {
281 repoCreateMu.Unlock()
282 return code
283 }
284 id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
285 repoCreateMu.Unlock()
286 if err != nil {
287 return c.fail(protocol.ExitFailure, "%v", err)
288 }
289 dir := RepoDir(c.Cfg.Server.Root, owner, name)
290 if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
291 c.Store.DeleteRepo(id)
292 return c.fail(protocol.ExitFailure, "initializing repository: %v", err)
293 }
294 if description != "" {
295 if err := gitutil.WriteDescription(dir, description); err != nil {
296 return c.fail(protocol.ExitFailure, "writing description: %v", err)
297 }
298 }
299 type out struct {
300 Path string `json:"path"`
301 Visibility string `json:"visibility"`
302 SSHURL string `json:"ssh_url"`
303 }
304 d := out{Path: path, Visibility: visibility, SSHURL: "ssh://git@" + hostOf(c.Cfg.Server.SiteURL) + "/" + path + ".git"}
305 return c.emit(d, func(w io.Writer) {
306 fmt.Fprintf(w, "created %s (%s)\nclone: git clone %s\n", d.Path, d.Visibility, d.SSHURL)
307 })
308}
309
310// resolveNewRepoOwner answers who a new repository belongs to: the
311// caller, or an organization they administer. The returned code is -1
312// when the owner is good, and the exit code to return otherwise.
313func resolveNewRepoOwner(c *Ctx, owner string) (kind string, id int64, code int) {
314 if owner == c.User.Username {
315 return "user", c.User.ID, -1
316 }
317 org, err := c.Store.OrgByName(owner)
318 if err != nil {
319 return "", 0, c.fail(protocol.ExitDenied, "cannot create repositories under %q: not you and not an organization you can see", owner)
320 }
321 role, err := c.Store.OrgRole(org.ID, c.User.ID)
322 if err != nil {
323 return "", 0, c.fail(protocol.ExitFailure, "%v", err)
324 }
325 if role != "admin" {
326 return "", 0, c.fail(protocol.ExitDenied, "only admins of %s can create repositories there", owner)
327 }
328 return "org", org.ID, -1
329}
330
331func policyValidateRepoName(name string) error { return policy.ValidateName(name) }
332
333func hostOf(siteURL string) string {
334 s := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")
335 return strings.TrimSuffix(s, "/")
336}
337
338func runRepoList(c *Ctx, args []string) int {
339 args, p, code := parsePageFlags(c, args, "repo", false)
340 if code >= 0 {
341 return code
342 }
343 if len(args) != 0 {
344 return c.usage()
345 }
346 repos, err := c.Store.ListReposForUser(c.User.ID, p.queryLimit(), p.key)
347 if err != nil {
348 return c.fail(protocol.ExitFailure, "%v", err)
349 }
350 repos, next := trimPage(p, repos, "repo", store.Repo.Path)
351 type out struct {
352 Path string `json:"path"`
353 Visibility string `json:"visibility"`
354 Description string `json:"description,omitempty"`
355 Archived bool `json:"archived,omitempty"`
356 }
357 var ds []out
358 for _, r := range repos {
359 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
360 ds = append(ds, out{r.Path(), r.Visibility, desc, r.Settings.Archived})
361 }
362 return c.emitPageView(p, ds, next, func(w io.Writer) {
363 tb := c.table(w, "PATH", "VISIBILITY", "DESCRIPTION")
364 for _, d := range ds {
365 cells := []cell{cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cFlex(d.Description)}
366 if d.Archived {
367 cells = c.note(cells, 1, "[archived]", "archived")
368 }
369 tb.row(cells...)
370 }
371 tb.flush()
372 }, func() screen {
373 rows := make([]row, len(ds))
374 for i, d := range ds {
375 state := d.Visibility
376 if d.Archived {
377 state += ", archived"
378 }
379 rows[i] = rowOf(cLink(d.Path, c.siteURL(d.Path)), cState(state), cFlex(d.Description))
380 }
381 s := listScreen("Repositories", rows)
382 if len(ds) > 0 {
383 s.actions = []action{{"Read", []string{"repo", "show", ds[0].Path}}}
384 }
385 return s
386 })
387}
388
389// repoMirrorOut is one mirror as repo show emits it, for admins.
390type repoMirrorOut struct {
391 Direction string `json:"direction"`
392 URL string `json:"url"`
393 Pending bool `json:"pending"`
394 LastSync string `json:"last_sync,omitempty"`
395 LastError string `json:"last_error,omitempty"`
396}
397
398// repoShowOut is what repo show emits.
399type repoShowOut struct {
400 Path string `json:"path"`
401 Description string `json:"description,omitempty"`
402 Website string `json:"website,omitempty"`
403 Visibility string `json:"visibility"`
404 DefaultBranch string `json:"default_branch"`
405 ProtectedBranches []string `json:"protected_branches,omitempty"`
406 Archived bool `json:"archived,omitempty"`
407 Topics []string `json:"topics,omitempty"`
408 Domains []string `json:"domains,omitempty"`
409 Mirrors []repoMirrorOut `json:"mirrors,omitempty"`
410 // ForkOf names the parent only when the caller can read it: a
411 // private parent is not confirmed to exist, here as anywhere.
412 ForkOf string `json:"fork_of,omitempty"`
413 // Watch and Bookmarked are the caller's own state, so a client
414 // can draw a toggle rather than two stateless buttons (#178).
415 Watch string `json:"watch,omitempty"` // watching, muted, or absent
416 Bookmarked bool `json:"bookmarked,omitempty"`
417}
418
419func runRepoShow(c *Ctx, args []string) int {
420 if len(args) != 1 {
421 return c.usage()
422 }
423 repo, code := resolveRepo(c, args[0], policy.CanRead)
424 if code >= 0 {
425 return code
426 }
427 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name))
428 topics, err := c.Store.ListTopics(repo.ID)
429 if err != nil {
430 return c.fail(protocol.ExitFailure, "%v", err)
431 }
432 var domains []string
433 if ds, err := c.Store.ListPageDomains(repo.ID); err == nil {
434 for _, pd := range ds {
435 if pd.Verified() {
436 domains = append(domains, pd.Domain)
437 }
438 }
439 }
440 d := repoShowOut{Path: repo.Path(), Description: desc, Website: repo.Settings.Website, Visibility: repo.Visibility,
441 DefaultBranch: repo.DefaultBranch, ProtectedBranches: repo.Settings.ProtectedBranches,
442 Archived: repo.Settings.Archived, Topics: topics, Domains: domains}
443 if repo.ForkOf != 0 {
444 if parent, err := c.Store.RepoByID(repo.ForkOf); err == nil {
445 if grant, err := c.Store.AccessRole(parent.ID, c.User.ID); err == nil && policy.CanRead(c.User, parent, grant) {
446 d.ForkOf = parent.Path()
447 }
448 }
449 }
450 if c.User.ID != 0 {
451 d.Watch = c.Store.RepoWatchState(repo.ID, c.User.ID)
452 d.Bookmarked = c.Store.IsBookmarked(c.User.ID, repo.ID)
453 }
454 // Mirror status is admin-only, like repo mirror list. The token never
455 // leaves the server.
456 if grant, err := c.Store.AccessRole(repo.ID, c.User.ID); err == nil && policy.CanAdmin(c.User, repo, grant) {
457 ms, err := c.Store.ListMirrors(repo.ID)
458 if err != nil {
459 return c.fail(protocol.ExitFailure, "%v", err)
460 }
461 for _, m := range ms {
462 d.Mirrors = append(d.Mirrors, repoMirrorOut{m.Direction, m.URL, m.Dirty, m.LastSync, m.LastError})
463 }
464 }
465 var glance repoGlance
466 var mrs []store.MR
467 var issues []store.Issue
468 var commits []CommitOut
469 if c.Term.Cols > 0 && !c.JSON {
470 glance = repoAtAGlance(c, repo)
471 mrs, _ = c.Store.ListMRs(repo.ID, "open", 5, 0)
472 issues, _ = c.Store.QueryIssues(repo.ID, store.IssueFilter{State: "open", Limit: 5})
473 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
474 if shas, err := gitutil.RevList(dir, "refs/heads/"+repo.DefaultBranch, 5); err == nil {
475 subjects := gitutil.Subjects(dir, shas)
476 for _, sha := range shas {
477 commits = append(commits, CommitOut{sha, subjects[sha]})
478 }
479 }
480 }
481 return c.emitView(d, func(w io.Writer) {
482 bookmarked, archived := "", ""
483 if d.Bookmarked {
484 bookmarked = "yes"
485 }
486 if d.Archived {
487 archived = "yes"
488 }
489 v := c.view(w)
490 v.title(d.Path, d.Description, d.Visibility)
491 v.fields(
492 "default branch", d.DefaultBranch,
493 "website", d.Website,
494 "topics", strings.Join(d.Topics, ", "),
495 "protected", strings.Join(d.ProtectedBranches, ", "),
496 "pages domains", strings.Join(d.Domains, ", "),
497 "fork of", d.ForkOf,
498 "watch", d.Watch,
499 "bookmarked", bookmarked,
500 "archived", archived,
501 "url", c.siteURL(d.Path),
502 )
503 if len(d.Mirrors) > 0 {
504 v.section("mirror")
505 tb := c.table(w, "DIRECTION", "URL", "LAST SYNC", "STATUS")
506 for _, m := range d.Mirrors {
507 status := "ok"
508 if m.Pending {
509 status = "pending"
510 }
511 if m.LastError != "" {
512 status = "error: " + m.LastError
513 }
514 tb.row(cText(m.Direction), cFlex(m.URL), cText(orDash(c.when(m.LastSync))), cState(status))
515 }
516 tb.flush()
517 }
518 }, func() screen { return repoShowScreen(c, d, glance, mrs, issues, commits) })
519}
520
521// repoGlance is what repo show adds at a terminal: how to clone it and
522// what is going on in it.
523type repoGlance struct {
524 clone, release, checks string
525 issuesN, mrsN int
526}
527
528// repoAtAGlance reads the glance fields. Each is left blank when it
529// cannot be read: they are a summary, not the command's result.
530func repoAtAGlance(c *Ctx, repo store.Repo) repoGlance {
531 host := c.Cfg.SiteHost()
532 if c.Cfg.SSH.Port != 22 {
533 host += ":" + strconv.Itoa(c.Cfg.SSH.Port)
534 }
535 g := repoGlance{clone: "ssh://git@" + host + "/" + repo.Path() + ".git"}
536 g.issuesN, g.mrsN = c.Store.OpenCounts(repo.ID)
537 if rs, err := c.Store.ListReleasesPage(repo.ID, 1, "", 0); err == nil && len(rs) > 0 {
538 g.release = rs[0].Tag + ", " + relAge(rs[0].CreatedAt, termNow())
539 }
540 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
541 if tip, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch); err == nil {
542 if sts, err := c.Store.ListCommitStatuses(repo.ID, tip); err == nil {
543 if m := checksMark(sts); m.s != "" {
544 g.checks = m.s + " on " + repo.DefaultBranch
545 }
546 }
547 }
548 return g
549}
550
551func runRepoTransfer(c *Ctx, args []string) int {
552 if len(args) != 2 {
553 return c.usage()
554 }
555 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
556 if code >= 0 {
557 return code
558 }
559 newOwner := args[1]
560 if newOwner == repo.OwnerName {
561 return c.fail(protocol.ExitUsage, "%s already owns this repository", newOwner)
562 }
563
564 // Target: yourself, or an org you admin — same rule as repo create.
565 newKind, newID := "", int64(0)
566 if newOwner == c.User.Username {
567 newKind, newID = "user", c.User.ID
568 } else if org, err := c.Store.OrgByName(newOwner); err == nil {
569 role, err := c.Store.OrgRole(org.ID, c.User.ID)
570 if err != nil {
571 return c.fail(protocol.ExitFailure, "%v", err)
572 }
573 if role != "admin" {
574 return c.fail(protocol.ExitDenied, "only admins of %s can receive repositories there", newOwner)
575 }
576 newKind, newID = "org", org.ID
577 } else {
578 return c.fail(protocol.ExitDenied, "cannot transfer to %q: not you and not an organization you can see", newOwner)
579 }
580
581 oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
582 newDir := RepoDir(c.Cfg.Server.Root, newOwner, repo.Name)
583 // The receiving owner's caps apply as if the repository were created
584 // there. The lock covers the move so two transfers cannot both pass.
585 repoCreateMu.Lock()
586 defer repoCreateMu.Unlock()
587 if code := checkRepoQuota(c, newKind, newID); code >= 0 {
588 return code
589 }
590 if code := checkBytesLeft(c, newKind, newID, newOwner, gitutil.DirSize(oldDir)); code >= 0 {
591 return code
592 }
593 if _, err := os.Stat(newDir); err == nil {
594 return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", newOwner, repo.Name)
595 }
596 release, lockCode := holdOffBackup(c)
597 if lockCode >= 0 {
598 return lockCode
599 }
600 defer release()
601 // The directory moves before the record changes: a move that fails
602 // leaves nothing to undo, whereas the record's change into an org
603 // folds labels and milestones into the org's rows, which a revert
604 // cannot unfold (#212). A record that then fails moves the directory
605 // back, and says so if even that fails, since the operator then has
606 // a row pointing at a directory that is not there.
607 if err := os.MkdirAll(filepath.Dir(newDir), 0o750); err != nil {
608 return c.fail(protocol.ExitFailure, "%v", err)
609 }
610 if err := os.Rename(oldDir, newDir); err != nil {
611 return c.fail(protocol.ExitFailure, "moving repository: %v", err)
612 }
613 if err := c.Store.TransferRepo(repo.ID, newKind, newID); err != nil {
614 if rerr := os.Rename(newDir, oldDir); rerr != nil {
615 return c.fail(protocol.ExitFailure, "%v; and moving the directory back failed: %v (the record still names %s but the directory is now %s)", err, rerr, repo.Path(), newOwner+"/"+repo.Name)
616 }
617 return c.failErr(err)
618 }
619 newPath := newOwner + "/" + repo.Name
620 return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
621 fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
622 })
623}
624
625func runRepoRename(c *Ctx, args []string) int {
626 if len(args) != 2 {
627 return c.usage()
628 }
629 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
630 if code >= 0 {
631 return code
632 }
633 newName := args[1]
634 if newName == repo.Name {
635 return c.fail(protocol.ExitUsage, "%s is already named %s", repo.Path(), newName)
636 }
637 if err := policyValidateRepoName(newName); err != nil {
638 return c.failInput(err)
639 }
640 oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
641 newDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, newName)
642 if _, err := os.Stat(newDir); err == nil {
643 return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", repo.OwnerName, newName)
644 }
645 release, lockCode := holdOffBackup(c)
646 if lockCode >= 0 {
647 return lockCode
648 }
649 defer release()
650 if err := c.Store.RenameRepo(repo.ID, newName); err != nil {
651 return c.failErr(err)
652 }
653 if err := os.Rename(oldDir, newDir); err != nil {
654 // Same rule as transfer: keep name and disk consistent, and say so
655 // if even the revert fails.
656 if rerr := c.Store.RenameRepo(repo.ID, repo.Name); rerr != nil {
657 return c.fail(protocol.ExitFailure, "moving repository: %v; and reverting the record failed: %v (the record now names %s/%s but the directory is still %s)", err, rerr, repo.OwnerName, newName, repo.Path())
658 }
659 return c.fail(protocol.ExitFailure, "moving repository: %v", err)
660 }
661 newPath := repo.OwnerName + "/" + newName
662 return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
663 fmt.Fprintf(w, "renamed %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
664 })
665}
666
667func runRepoDelete(c *Ctx, args []string) int {
668 var path string
669 var yes bool
670 for _, a := range args {
671 if a == "--yes" {
672 yes = true
673 } else if path == "" {
674 path = a
675 } else {
676 return c.usage()
677 }
678 }
679 if path == "" {
680 return c.usage()
681 }
682 repo, code := resolveRepo(c, path, policy.CanAdmin)
683 if code >= 0 {
684 return code
685 }
686 if !yes {
687 return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
688 }
689 return deleteRepo(c, repo)
690}
691
692// deleteRepo removes a repository the caller has already been cleared to
693// delete: the database row, then the directory.
694//
695// There is deliberately no repo.deleted event. events.repo_id and
696// webhooks.repo_id both cascade from repos, so recording one would delete
697// it, and every webhook that could have subscribed, in the same
698// statement. A repository's deletion is not observable through its own
699// webhooks; an instance that needs to hear about it wants the audit log
700// (#112).
701func deleteRepo(c *Ctx, repo store.Repo) int {
702 release, lockCode := holdOffBackup(c)
703 if lockCode >= 0 {
704 return lockCode
705 }
706 defer release()
707 if err := removeRepo(c.Store, c.Cfg.Server.Root, repo); err != nil {
708 return c.fail(protocol.ExitFailure, "%v", err)
709 }
710 return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
711 fmt.Fprintf(w, "deleted %s\n", repo.Path())
712 })
713}
714
715// removeRepo is deleteRepo's work without a request: the caller holds
716// off the backup.
717func removeRepo(st *store.Store, root string, repo store.Repo) error {
718 // Open MRs sourced from this repo keep working (targets own the
719 // objects) but must show that the source is gone.
720 if err := st.MarkSourceGoneForRepo(repo.ID); err != nil {
721 return err
722 }
723 if err := st.DeleteRepo(repo.ID); err != nil {
724 return err
725 }
726 if err := os.RemoveAll(RepoDir(root, repo.OwnerName, repo.Name)); err != nil {
727 return fmt.Errorf("database row removed but disk cleanup failed: %w", err)
728 }
729 return nil
730}
731
732// holdOffBackup keeps a full backup from starting while a repository
733// directory moves or goes, and refuses while one runs: the backup's
734// database snapshot names every repository its walk then archives
735// (#259). The caller defers the returned release.
736func holdOffBackup(c *Ctx) (func(), int) {
737 release, err := backuplock.TryShared(c.Cfg.Server.Root)
738 if err != nil {
739 return nil, c.fail(protocol.ExitFailure, "%v", err)
740 }
741 return release, -1
742}
743
744func runAccessGrant(c *Ctx, args []string) int {
745 if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
746 return c.usage()
747 }
748 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
749 if code >= 0 {
750 return code
751 }
752 target, err := c.Store.UserByUsername(args[1])
753 if err != nil {
754 return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
755 }
756 if target.Ghost {
757 return c.fail(protocol.ExitDenied, "%v", errGhost)
758 }
759 if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
760 return c.fail(protocol.ExitFailure, "%v", err)
761 }
762 return c.emit(map[string]string{"granted": args[2], "user": target.Username},
763 func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
764}
765
766func runAccessRevoke(c *Ctx, args []string) int {
767 if len(args) != 2 {
768 return c.usage()
769 }
770 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
771 if code >= 0 {
772 return code
773 }
774 target, err := c.Store.UserByUsername(args[1])
775 if err != nil {
776 return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
777 }
778 if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
779 if errors.Is(err, store.ErrNotFound) {
780 return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
781 }
782 return c.fail(protocol.ExitFailure, "%v", err)
783 }
784 return c.emit(map[string]string{"revoked": target.Username},
785 func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
786}
787
788func runAccessList(c *Ctx, args []string) int {
789 if len(args) != 1 {
790 return c.usage()
791 }
792 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
793 if code >= 0 {
794 return code
795 }
796 entries, err := c.Store.EffectiveAccess(repo.ID)
797 if err != nil {
798 return c.fail(protocol.ExitFailure, "%v", err)
799 }
800 type out struct {
801 User string `json:"user"`
802 Role string `json:"role"`
803 Source string `json:"source"`
804 }
805 var ds []out
806 for _, e := range entries {
807 ds = append(ds, out{e.Username, e.Role, e.Source})
808 }
809 return c.emitView(ds, func(w io.Writer) {
810 tb := c.table(w, "USER", "ROLE", "SOURCE")
811 for _, d := range ds {
812 tb.row(cRef(d.User), cState(d.Role), cText("via "+d.Source))
813 }
814 tb.flush()
815 }, func() screen {
816 rows := make([]row, len(ds))
817 for i, d := range ds {
818 rows[i] = rowOf(cRef(d.User), cState(d.Role), cMeta("via "+d.Source))
819 }
820 return listScreen("Access", rows,
821 action{"Access", []string{"repo", "access", "grant", repo.Path(), "<user>", "write"}},
822 action{"Access", []string{"repo", "access", "revoke", repo.Path(), "<user>"}},
823 )
824 })
825}
826
827func runSettingsShow(c *Ctx, args []string) int {
828 if len(args) != 1 {
829 return c.usage()
830 }
831 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
832 if code >= 0 {
833 return code
834 }
835 return c.emitView(repo.Settings, func(w io.Writer) {
836 v := c.view(w)
837 v.title(repo.Path(), "settings", "")
838 v.fields(
839 "protected branches", strings.Join(repo.Settings.ProtectedBranches, ", "),
840 "protected tags", strings.Join(repo.Settings.ProtectedTags, ", "),
841 "require mr", strconv.FormatBool(repo.Settings.RequireMR),
842 "require checks", strconv.FormatBool(repo.Settings.RequireChecks),
843 "required contexts", strings.Join(repo.Settings.RequiredContexts, ", "),
844 "require signed commits", strconv.FormatBool(repo.Settings.RequireSignedCommits),
845 "secret scan", leaks.Mode(repo.Settings.SecretScan),
846 "secret scan allow", strings.Join(repo.Settings.SecretScanAllow, ", "),
847 "security ignore", strings.Join(repo.Settings.SecurityIgnore, ", "),
848 "security exclude rules", strings.Join(repo.Settings.SecurityExcludeRules, ", "),
849 "git daemon", strconv.FormatBool(repo.Settings.GitDaemon),
850 "archived", strconv.FormatBool(repo.Settings.Archived),
851 )
852 }, func() screen {
853 set := repo.Settings
854 onOff := func(b bool) cell {
855 if b {
856 return cText("on")
857 }
858 return cMeta("off")
859 }
860 approvals := cMeta("off")
861 if set.RequireApprovals > 0 {
862 approvals = cText(strconv.Itoa(set.RequireApprovals))
863 }
864 list := func(xs []string) cell {
865 if len(xs) == 0 {
866 return cMeta("none")
867 }
868 return cText(strings.Join(xs, ", "))
869 }
870 mr := "on"
871 if set.RequireMR {
872 mr = "off"
873 }
874 s := screen{fields: []field{
875 {"Repo", []cell{cLink(repo.Path(), c.siteURL(repo.Path())), cMeta("settings")}},
876 {"Protected", []cell{list(set.ProtectedBranches)}},
877 {"Protected tags", []cell{list(set.ProtectedTags)}},
878 {"Require MR", []cell{onOff(set.RequireMR)}},
879 {"Require checks", []cell{onOff(set.RequireChecks)}},
880 {"Contexts", []cell{list(set.RequiredContexts)}},
881 {"Approvals", []cell{approvals}},
882 {"Resolved threads", []cell{onOff(set.RequireResolved)}},
883 {"Code owners", []cell{onOff(set.RequireCodeowners)}},
884 {"Signed commits", []cell{onOff(set.RequireSignedCommits)}},
885 {"Secret scan", []cell{cText(leaks.Mode(set.SecretScan))}},
886 {"Scan allows", []cell{list(set.SecretScanAllow)}},
887 {"Scan ignores", []cell{list(set.SecurityIgnore)}},
888 {"Rules off", []cell{list(set.SecurityExcludeRules)}},
889 {"Git daemon", []cell{onOff(set.GitDaemon)}},
890 {"Archived", []cell{onOff(set.Archived)}},
891 }, actions: []action{
892 {"Settings", []string{"repo", "settings", "protect", repo.Path(), "<branch>"}},
893 {"Settings", []string{"repo", "settings", "require-mr", repo.Path(), mr}},
894 }}
895 if set.Website != "" {
896 s.fields = append(s.fields, field{"Website", []cell{cText(set.Website)}})
897 }
898 return s
899 })
900}
901
902func runSetDescription(c *Ctx, args []string) int {
903 if len(args) != 2 {
904 return c.usage()
905 }
906 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
907 if code >= 0 {
908 return code
909 }
910 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
911 if err := gitutil.WriteDescription(dir, args[1]); err != nil {
912 return c.fail(protocol.ExitFailure, "%v", err)
913 }
914 return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
915 fmt.Fprintf(w, "description set on %s\n", repo.Path())
916 })
917}
918
919func runSetDefaultBranch(c *Ctx, args []string) int {
920 if len(args) != 2 {
921 return c.usage()
922 }
923 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
924 if code >= 0 {
925 return code
926 }
927 branch := args[1]
928 if strings.HasPrefix(branch, "-") {
929 return c.fail(protocol.ExitUsage, "a default branch may not start with '-'")
930 }
931 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
932 if _, err := gitutil.ResolveRef(dir, "refs/heads/"+branch); err != nil {
933 return c.fail(protocol.ExitFailure, "no branch named %q on %s", branch, repo.Path())
934 }
935 if err := gitutil.SetHead(dir, branch); err != nil {
936 return c.fail(protocol.ExitFailure, "%v", err)
937 }
938 if err := c.Store.UpdateDefaultBranch(repo.ID, branch); err != nil {
939 return c.fail(protocol.ExitFailure, "%v", err)
940 }
941 c.Store.RequestSymbolIndex(repo.ID, false)
942 return c.emit(map[string]string{"default_branch": branch}, func(w io.Writer) {
943 fmt.Fprintf(w, "default branch of %s is now %s\n", repo.Path(), branch)
944 })
945}
946
947func runSetWebsite(c *Ctx, args []string) int {
948 if len(args) != 2 {
949 return c.usage()
950 }
951 site := strings.TrimSpace(args[1])
952 if err := validateWebsite(site); err != nil {
953 return c.failInput(err)
954 }
955 if len(site) > 256 {
956 return c.fail(protocol.ExitUsage, "website URL too long (max 256)")
957 }
958 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
959 if code >= 0 {
960 return code
961 }
962 if _, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Website = site }); err != nil {
963 return c.fail(protocol.ExitFailure, "%v", err)
964 }
965 return c.emit(map[string]string{"website": site}, func(w io.Writer) {
966 if site == "" {
967 fmt.Fprintf(w, "website cleared on %s\n", repo.Path())
968 } else {
969 fmt.Fprintf(w, "website set on %s\n", repo.Path())
970 }
971 })
972}
973
974func runSetVisibility(c *Ctx, args []string) int {
975 if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
976 return c.usage()
977 }
978 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
979 if code >= 0 {
980 return code
981 }
982 return setRepoVisibility(c, repo, args[1])
983}
984
985// setRepoVisibility applies a visibility change the caller has already
986// been cleared to make.
987func setRepoVisibility(c *Ctx, repo store.Repo, visibility string) int {
988 if repo.Visibility == visibility {
989 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
990 fmt.Fprintf(w, "%s is already %s\n", repo.Path(), visibility)
991 })
992 }
993 if err := c.Store.SetRepoVisibility(repo.ID, visibility); err != nil {
994 return c.fail(protocol.ExitFailure, "%v", err)
995 }
996 // Going private takes the repository off every anonymous surface, so
997 // git:// exposure cannot outlive the change.
998 if visibility == "private" && repo.Settings.GitDaemon {
999 c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = false })
1000 }
1001 c.Store.Audit(c.User.ID, "repo.visibility", map[string]any{"repo": repo.ID, "visibility": visibility})
1002 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
1003 fmt.Fprintf(w, "%s is now %s\n", repo.Path(), visibility)
1004 })
1005}
1006
1007func runGitDaemon(c *Ctx, args []string) int {
1008 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
1009 return c.usage()
1010 }
1011 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1012 if code >= 0 {
1013 return code
1014 }
1015 on := args[1] == "on"
1016 if on && repo.Visibility != "public" {
1017 return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
1018 }
1019 if on && !c.Cfg.GitDaemon.Enabled {
1020 return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
1021 }
1022 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = on })
1023 if err != nil {
1024 return c.fail(protocol.ExitFailure, "%v", err)
1025 }
1026 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
1027}
1028
1029func runArchive(c *Ctx, args []string) int { return setArchived(c, args, true) }
1030func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
1031
1032func setArchived(c *Ctx, args []string, archived bool) int {
1033 if len(args) != 1 {
1034 return c.usage()
1035 }
1036 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1037 if code >= 0 {
1038 return code
1039 }
1040 return archiveRepo(c, repo, archived)
1041}
1042
1043// archiveRepo flips the archived flag on a repository the caller has
1044// already been cleared to manage.
1045func archiveRepo(c *Ctx, repo store.Repo, archived bool) int {
1046 verb := "archive"
1047 if !archived {
1048 verb = "unarchive"
1049 }
1050 if repo.Settings.Archived == archived {
1051 return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
1052 }
1053 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Archived = archived })
1054 if err != nil {
1055 return c.fail(protocol.ExitFailure, "%v", err)
1056 }
1057 c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
1058 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
1059}
1060
1061// topicsScreen is a repository's topics at a terminal, after a read or
1062// an edit.
1063func topicsScreen(repo store.Repo, topics []string) screen {
1064 rows := make([]row, len(topics))
1065 for i, t := range topics {
1066 rows[i] = rowOf(cRef(t))
1067 }
1068 return listScreen("Topics", rows,
1069 action{"Edit", []string{"repo", "topics", "add", repo.Path(), "<topic>"}},
1070 action{"Edit", []string{"repo", "topics", "remove", repo.Path(), "<topic>"}},
1071 )
1072}
1073
1074func runTopicsList(c *Ctx, args []string) int {
1075 if len(args) != 1 {
1076 return c.usage()
1077 }
1078 repo, code := resolveRepo(c, args[0], policy.CanRead)
1079 if code >= 0 {
1080 return code
1081 }
1082 topics, err := c.Store.ListTopics(repo.ID)
1083 if err != nil {
1084 return c.fail(protocol.ExitFailure, "%v", err)
1085 }
1086 return c.emitView(topics, func(w io.Writer) {
1087 tb := c.table(w, "TOPIC")
1088 for _, t := range topics {
1089 tb.row(cRef(t))
1090 }
1091 tb.flush()
1092 }, func() screen {
1093 return topicsScreen(repo, topics)
1094 })
1095}
1096
1097func runTopicsAdd(c *Ctx, args []string) int { return editTopics(c, args, true) }
1098func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
1099
1100func editTopics(c *Ctx, args []string, add bool) int {
1101 if len(args) < 2 {
1102 return c.usage()
1103 }
1104 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1105 if code >= 0 {
1106 return code
1107 }
1108 topics := args[1:]
1109 if add {
1110 for _, t := range topics {
1111 if err := policy.ValidateTopic(t); err != nil {
1112 return c.failInput(err)
1113 }
1114 }
1115 have, err := c.Store.ListTopics(repo.ID)
1116 if err != nil {
1117 return c.fail(protocol.ExitFailure, "%v", err)
1118 }
1119 added := 0
1120 for _, t := range topics {
1121 if !slices.Contains(have, t) {
1122 added++
1123 }
1124 }
1125 if len(have)+added > policy.MaxTopics {
1126 return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
1127 }
1128 for _, t := range topics {
1129 if err := c.Store.AddTopic(repo.ID, t); err != nil {
1130 return c.fail(protocol.ExitFailure, "%v", err)
1131 }
1132 }
1133 } else {
1134 for _, t := range topics {
1135 if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
1136 if errors.Is(err, store.ErrNotFound) {
1137 return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
1138 }
1139 return c.fail(protocol.ExitFailure, "%v", err)
1140 }
1141 }
1142 }
1143 now, err := c.Store.ListTopics(repo.ID)
1144 if err != nil {
1145 return c.fail(protocol.ExitFailure, "%v", err)
1146 }
1147 return c.emitView(now, func(w io.Writer) {
1148 tb := c.table(w, "TOPIC")
1149 for _, t := range now {
1150 tb.row(cRef(t))
1151 }
1152 tb.flush()
1153 }, func() screen {
1154 return topicsScreen(repo, now)
1155 })
1156}
1157
1158// runRepoSearch matches the query against name, owner/name, description,
1159// and topics of every repository the caller can see.
1160func runRepoSearch(c *Ctx, args []string) int {
1161 if len(args) != 1 {
1162 return c.usage()
1163 }
1164 if err := validQuery(args[0]); err != nil {
1165 return c.failInput(err)
1166 }
1167 q := strings.ToLower(args[0])
1168
1169 public, err := c.Store.ListPublicRepos()
1170 if err != nil {
1171 return c.fail(protocol.ExitFailure, "%v", err)
1172 }
1173 own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
1174 if err != nil {
1175 return c.fail(protocol.ExitFailure, "%v", err)
1176 }
1177 seen := map[int64]bool{}
1178 type out struct {
1179 Path string `json:"path"`
1180 Visibility string `json:"visibility"`
1181 Description string `json:"description,omitempty"`
1182 Topics []string `json:"topics,omitempty"`
1183 }
1184 var ds []out
1185 for _, r := range append(public, own...) {
1186 if seen[r.ID] {
1187 continue
1188 }
1189 seen[r.ID] = true
1190 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
1191 topics, _ := c.Store.ListTopics(r.ID)
1192 if !MatchesRepo(q, r.Path(), desc, topics) {
1193 continue
1194 }
1195 ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
1196 }
1197 return c.emitView(ds, func(w io.Writer) {
1198 tb := c.table(w, "PATH", "VISIBILITY", "DESCRIPTION")
1199 for _, d := range ds {
1200 tb.row(cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cFlex(d.Description))
1201 }
1202 tb.flush()
1203 }, func() screen {
1204 rows := make([]row, len(ds))
1205 for i, d := range ds {
1206 rows[i] = rowOf(cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cFlex(d.Description), cMeta(strings.Join(d.Topics, ", ")))
1207 }
1208 s := listScreen(fmt.Sprintf("Repositories matching %q", args[0]), rows)
1209 if len(ds) > 0 {
1210 s.actions = []action{{"Read", []string{"repo", "show", ds[0].Path}}}
1211 }
1212 return s
1213 })
1214}
1215
1216// MatchesRepo is the one rule for matching a repository against a text
1217// query: its path, its description, or any of its topics. The web's
1218// /explore filter and /search page call it too, so the three surfaces
1219// cannot answer the same query differently.
1220func MatchesRepo(q, path, desc string, topics []string) bool {
1221 q = strings.ToLower(q)
1222 if strings.Contains(strings.ToLower(path), q) ||
1223 strings.Contains(strings.ToLower(desc), q) {
1224 return true
1225 }
1226 for _, t := range topics {
1227 if strings.Contains(strings.ToLower(t), q) {
1228 return true
1229 }
1230 }
1231 return false
1232}
1233
1234func runRepoGrep(c *Ctx, args []string) int {
1235 f, err := c.parseArgs(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: "repo grep <owner/name> <query> [--ref <ref>]"})
1236 if err != nil {
1237 return c.fail(protocol.ExitUsage, "%v", err)
1238 }
1239 path, query, ref := f.pos(0), f.pos(1), f.Value("--ref")
1240 if path == "" || query == "" {
1241 return c.usage()
1242 }
1243 if err := validQuery(query); err != nil {
1244 return c.failInput(err)
1245 }
1246 repo, code := resolveRepo(c, path, policy.CanRead)
1247 if code >= 0 {
1248 return code
1249 }
1250 if ref == "" {
1251 ref = repo.DefaultBranch
1252 }
1253 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1254 if _, err := gitutil.ResolveRef(dir, ref); err != nil {
1255 return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
1256 }
1257 matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
1258 if err != nil {
1259 return c.fail(protocol.ExitFailure, "%v", err)
1260 }
1261 type out struct {
1262 Path string `json:"path"`
1263 Line int `json:"line"`
1264 Text string `json:"text"`
1265 }
1266 var ds []out
1267 for _, m := range matches {
1268 ds = append(ds, out{m.Path, m.Line, m.Text})
1269 }
1270 return c.emit(ds, func(w io.Writer) {
1271 for _, d := range ds {
1272 fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
1273 }
1274 })
1275}
1276
1277func runRepoPin(c *Ctx, args []string) int { return setPinned(c, args, true) }
1278func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
1279
1280func setPinned(c *Ctx, args []string, pin bool) int {
1281 return setRepoMark(c, args, pin, "pinned", "unpinned", c.Store.PinRepo, c.Store.UnpinRepo)
1282}
1283
1284// setRepoMark marks a repository the caller can read with mark, or clears
1285// it with unmark; done and undone are the words the output uses.
1286func setRepoMark(c *Ctx, args []string, on bool, done, undone string, mark, unmark func(userID, repoID int64) error) int {
1287 if len(args) != 1 {
1288 return c.usage()
1289 }
1290 repo, code := resolveRepo(c, args[0], policy.CanRead)
1291 if code >= 0 {
1292 return code
1293 }
1294 word := done
1295 if on {
1296 if err := mark(c.User.ID, repo.ID); err != nil {
1297 return c.fail(protocol.ExitFailure, "%v", err)
1298 }
1299 } else {
1300 word = undone
1301 if err := unmark(c.User.ID, repo.ID); err != nil {
1302 if errors.Is(err, store.ErrNotFound) {
1303 return c.fail(protocol.ExitNotFound, "%s is not %s", repo.Path(), done)
1304 }
1305 return c.fail(protocol.ExitFailure, "%v", err)
1306 }
1307 }
1308 return c.emit(map[string]string{word: repo.Path()}, func(w io.Writer) {
1309 fmt.Fprintf(w, "%s %s\n", word, repo.Path())
1310 })
1311}
1312
1313func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) }
1314func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
1315
1316// A bookmark needs only read access — bookmarking is something you do to
1317// someone else's repository, which is the whole point of it — and a
1318// private repository you cannot read is not found, as everywhere.
1319func setBookmarked(c *Ctx, args []string, on bool) int {
1320 return setRepoMark(c, args, on, "bookmarked", "unbookmarked", c.Store.BookmarkRepo, c.Store.UnbookmarkRepo)
1321}
1322
1323// BookmarkOut is one row of `repo bookmarks`: the repository and how many
1324// people have bookmarked it.
1325type BookmarkOut struct {
1326 Path string `json:"path"`
1327 Description string `json:"description,omitempty"`
1328 Visibility string `json:"visibility"`
1329 Bookmarks int `json:"bookmarks"`
1330}
1331
1332func runRepoBookmarks(c *Ctx, args []string) int {
1333 if len(args) != 0 {
1334 return c.usage()
1335 }
1336 repos, err := c.Store.ListBookmarks(c.User.ID)
1337 if err != nil {
1338 return c.fail(protocol.ExitFailure, "%v", err)
1339 }
1340 out := []BookmarkOut{}
1341 for _, r := range repos {
1342 // A repository bookmarked while public and since made private
1343 // stays in the table and drops out of the listing, the same way
1344 // it disappears from every other surface.
1345 grant, err := c.Store.AccessRole(r.ID, c.User.ID)
1346 if err != nil {
1347 return c.fail(protocol.ExitFailure, "%v", err)
1348 }
1349 if !policy.CanRead(c.User, r, grant) {
1350 continue
1351 }
1352 out = append(out, BookmarkOut{
1353 Path: r.Path(),
1354 Description: gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)),
1355 Visibility: r.Visibility,
1356 Bookmarks: c.Store.BookmarkCount(r.ID),
1357 })
1358 }
1359 return c.emitView(out, func(w io.Writer) {
1360 tb := c.table(w, "PATH", "COUNT", "DESCRIPTION")
1361 for _, b := range out {
1362 tb.row(cRef(b.Path), cNum(int64(b.Bookmarks)), cFlex(b.Description))
1363 }
1364 tb.flush()
1365 }, func() screen {
1366 rows := make([]row, len(out))
1367 for i, b := range out {
1368 n := fmt.Sprintf("%d bookmarks", b.Bookmarks)
1369 if b.Bookmarks == 1 {
1370 n = "1 bookmark"
1371 }
1372 rows[i] = rowOf(cLink(b.Path, c.siteURL(b.Path)), cState(b.Visibility), cFlex(b.Description), cMeta(n))
1373 }
1374 s := listScreen("Bookmarks", rows)
1375 if len(out) > 0 {
1376 s.actions = []action{{"Read", []string{"repo", "show", out[0].Path}}}
1377 }
1378 return s
1379 })
1380}
1381
1382func runProtectTag(c *Ctx, args []string) int { return setProtectTag(c, args, true) }
1383func runUnprotectTag(c *Ctx, args []string) int { return setProtectTag(c, args, false) }
1384
1385func setProtectTag(c *Ctx, args []string, protect bool) int {
1386 if len(args) != 2 {
1387 return c.usage()
1388 }
1389 glob := args[1]
1390 if _, err := path.Match(glob, "x"); err != nil || glob == "" {
1391 return c.fail(protocol.ExitUsage, "bad glob %q", glob)
1392 }
1393 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1394 if code >= 0 {
1395 return code
1396 }
1397 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1398 has := slices.Contains(s.ProtectedTags, glob)
1399 if protect && !has {
1400 s.ProtectedTags = append(s.ProtectedTags, glob)
1401 slices.Sort(s.ProtectedTags)
1402 }
1403 if !protect && has {
1404 s.ProtectedTags = slices.DeleteFunc(s.ProtectedTags, func(g string) bool { return g == glob })
1405 }
1406 })
1407 if err != nil {
1408 return c.fail(protocol.ExitFailure, "%v", err)
1409 }
1410 verb := "protected"
1411 if !protect {
1412 verb = "unprotected"
1413 }
1414 return c.emit(s, func(w io.Writer) {
1415 fmt.Fprintf(w, "tags %s %s on %s\n", glob, verb, repo.Path())
1416 })
1417}
1418
1419func runProtect(c *Ctx, args []string) int { return setProtect(c, args, true) }
1420func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
1421
1422func setProtect(c *Ctx, args []string, protect bool) int {
1423 if len(args) != 2 {
1424 return c.usage()
1425 }
1426 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1427 if code >= 0 {
1428 return code
1429 }
1430 branch := args[1]
1431 // The list is read and rewritten inside the update, so two admins
1432 // protecting different branches at once both land.
1433 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1434 has := slices.Contains(s.ProtectedBranches, branch)
1435 if protect && !has {
1436 s.ProtectedBranches = append(s.ProtectedBranches, branch)
1437 slices.Sort(s.ProtectedBranches)
1438 }
1439 if !protect && has {
1440 s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
1441 }
1442 })
1443 if err != nil {
1444 return c.fail(protocol.ExitFailure, "%v", err)
1445 }
1446 verb := "protected"
1447 if !protect {
1448 verb = "unprotected"
1449 }
1450 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
1451}
1452
1453// runRepoDiff is the compare view's command: what head adds on top of
1454// base, measured from their merge base the way a merge request diff is,
1455// so a base that moved on does not show up as removals (#118).
1456func runRepoDiff(c *Ctx, args []string) int {
1457 f, err := c.parseArgs(args, flagSpec{MaxPos: 3, Usage: "repo diff <owner/name> <base> <head>"})
1458 if err != nil || len(f.Pos) != 3 {
1459 return c.usage()
1460 }
1461 repo, code := resolveRepo(c, f.pos(0), policy.CanRead)
1462 if code >= 0 {
1463 return code
1464 }
1465 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1466 base, err := gitutil.ResolveRef(dir, f.pos(1))
1467 if err != nil {
1468 return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(1), repo.Path())
1469 }
1470 head, err := gitutil.ResolveRef(dir, f.pos(2))
1471 if err != nil {
1472 return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(2), repo.Path())
1473 }
1474 mergeBase, err := gitutil.MergeBase(dir, base, head)
1475 if err != nil {
1476 return c.fail(protocol.ExitUsage, "%v", err)
1477 }
1478 patch, truncated, err := gitutil.Diff(dir, mergeBase, head, 4<<20)
1479 if err != nil {
1480 return c.fail(protocol.ExitFailure, "%v", err)
1481 }
1482 if c.JSON {
1483 return c.emit(map[string]any{"base": base, "head": head, "merge_base": mergeBase, "patch": patch, "truncated": truncated}, nil)
1484 }
1485 fmt.Fprint(c.Stdout, c.Term.diff(patch))
1486 if truncated {
1487 fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB")
1488 }
1489 return protocol.ExitOK
1490}
1491
1492// repoShowScreen is repo show at a terminal: how to clone it, where the
1493// default branch stands, what is open, and the latest commits.
1494func repoShowScreen(c *Ctx, d repoShowOut, g repoGlance, mrs []store.MR, issues []store.Issue, commits []CommitOut) screen {
1495 s := screen{body: d.Description, format: "text"}
1496 name := []cell{cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility)}
1497 if d.Archived {
1498 name[1].s += ", archived"
1499 }
1500 s.fields = append(s.fields, field{"Repo", name})
1501 if g.clone != "" {
1502 s.fields = append(s.fields, field{"Clone", []cell{cText(g.clone)}})
1503 }
1504 head := []cell{cText(d.DefaultBranch)}
1505 if g.checks != "" {
1506 head = []cell{cText(d.DefaultBranch), cText(strings.TrimSuffix(g.checks, " on "+d.DefaultBranch))}
1507 }
1508 s.fields = append(s.fields, field{"Head", head})
1509 if g.release != "" {
1510 s.fields = append(s.fields, field{"Release", []cell{cText(g.release)}})
1511 }
1512 if len(d.Topics) > 0 {
1513 s.fields = append(s.fields, field{"Topics", []cell{cText(strings.Join(d.Topics, ", "))}})
1514 }
1515 if d.ForkOf != "" {
1516 s.fields = append(s.fields, field{"Fork of", []cell{cRef(d.ForkOf)}})
1517 }
1518 for _, m := range d.Mirrors {
1519 if m.LastError != "" {
1520 s.fields = append(s.fields, field{"Mirror", []cell{cGlyph("failed"), cText(m.Direction + " " + m.URL + ": " + m.LastError)}})
1521 }
1522 }
1523 if !c.Term.Links {
1524 s.fields = append(s.fields, field{"URL", []cell{cText(c.siteURL(d.Path))}})
1525 }
1526
1527 ms := section{title: "Open merge requests", n: g.mrsN, more: []string{"mr", "list", d.Path}}
1528 for _, m := range mrs {
1529 ms.rows = append(ms.rows, rowOf(cRef(fmt.Sprintf("!%d", m.Number)), cFlex(m.Title), cAge(m.UpdatedAt)))
1530 }
1531 is := section{title: "Open issues", n: g.issuesN, more: []string{"issue", "list", d.Path}}
1532 for _, i := range issues {
1533 is.rows = append(is.rows, rowOf(cRef(fmt.Sprintf("#%d", i.Number)), cFlex(i.Title), cAge(i.UpdatedAt)))
1534 }
1535 cs := section{title: "Recent commits", n: len(commits), more: []string{"repo", "log", d.Path}}
1536 for _, cm := range commits {
1537 cs.rows = append(cs.rows, rowOf(cRef(fmt.Sprintf("%.7s", cm.SHA)), cFlex(cm.Subject)))
1538 }
1539 s.sections = []section{ms, is, cs}
1540 s.actions = []action{
1541 {"Contribute", []string{"mr", "create", d.Path}},
1542 {"Contribute", []string{"issue", "create", d.Path}},
1543 {"Read", []string{"repo", "log", d.Path}},
1544 }
1545 return s
1546}