internal/control/repo.go
1183 lines · 42956 bytes
1package control
2
3import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 "path"
9 "path/filepath"
10 "slices"
11 "strings"
12
13 "gitbay.org/gitbay/internal/gitutil"
14 "gitbay.org/gitbay/internal/policy"
15 "gitbay.org/gitbay/internal/protocol"
16 "gitbay.org/gitbay/internal/store"
17)
18
19// RepoDir returns the on-disk path for a repository.
20func RepoDir(root, owner, name string) string {
21 return filepath.Join(root, "repos", owner, name+".git")
22}
23
24// HooksDir is the shared core.hooksPath directory.
25func HooksDir(root string) string { return filepath.Join(root, "hooks") }
26
27func init() {
28 register(Command{Path: []string{"repo", "create"},
29 Summary: "create a repository",
30 Usage: "repo create <owner/name> [--private]", Run: runRepoCreate})
31 register(Command{Path: []string{"repo", "list"},
32 Summary: "list repositories you own or can access",
33 Usage: "repo list [--limit <n>] [--cursor <c>]", ReadOnly: true, Run: runRepoList})
34 register(Command{Path: []string{"repo", "show"},
35 Summary: "show repository details",
36 Usage: "repo show <owner/name>", ReadOnly: true, Run: runRepoShow})
37 register(Command{Path: []string{"repo", "transfer"},
38 Summary: "move a repository to another owner",
39 Usage: "repo transfer <owner/name> <new-owner> (clone URLs change)", Run: runRepoTransfer})
40 register(Command{Path: []string{"repo", "rename"},
41 Summary: "rename a repository",
42 Usage: "repo rename <owner/name> <new-name> (clone URLs change)", Run: runRepoRename})
43 register(Command{Path: []string{"repo", "delete"},
44 Summary: "delete a repository",
45 Usage: "repo delete <owner/name> --yes", Run: runRepoDelete})
46 register(Command{Path: []string{"repo", "access", "grant"},
47 Summary: "grant access",
48 Usage: "repo access grant <owner/name> <user> read|write|admin", Run: runAccessGrant})
49 register(Command{Path: []string{"repo", "access", "revoke"},
50 Summary: "revoke access",
51 Usage: "repo access revoke <owner/name> <user>", Run: runAccessRevoke})
52 register(Command{Path: []string{"repo", "access", "list"},
53 Summary: "list who can reach the repository, with the role and where it comes from",
54 Usage: "repo access list <owner/name>", ReadOnly: true, Run: runAccessList})
55 register(Command{Path: []string{"repo", "settings", "show"},
56 Summary: "show settings",
57 Usage: "repo settings show <owner/name>", ReadOnly: true, Run: runSettingsShow})
58 register(Command{Path: []string{"repo", "settings", "protect"},
59 Summary: "protect a branch",
60 Usage: "repo settings protect <owner/name> <branch>", Run: runProtect})
61 register(Command{Path: []string{"repo", "settings", "unprotect"},
62 Summary: "unprotect a branch",
63 Usage: "repo settings unprotect <owner/name> <branch>", Run: runUnprotect})
64 register(Command{Path: []string{"repo", "settings", "protect-tag"},
65 Summary: "protect tags matching a glob (created once, never moved or deleted)",
66 Usage: "repo settings protect-tag <owner/name> <glob>", Run: runProtectTag})
67 register(Command{Path: []string{"repo", "settings", "unprotect-tag"},
68 Summary: "drop a protected-tag glob",
69 Usage: "repo settings unprotect-tag <owner/name> <glob>", Run: runUnprotectTag})
70 register(Command{Path: []string{"repo", "settings", "description"},
71 Summary: "set the repository description",
72 Usage: "repo settings description <owner/name> <text> ('' clears)", Run: runSetDescription})
73 register(Command{Path: []string{"repo", "settings", "visibility"},
74 Summary: "set repository visibility",
75 Usage: "repo settings visibility <owner/name> public|private", Run: runSetVisibility})
76 register(Command{Path: []string{"repo", "settings", "website"},
77 Summary: "set the repository website",
78 Usage: "repo settings website <owner/name> <url> ('' clears)", Run: runSetWebsite})
79 register(Command{Path: []string{"repo", "settings", "default-branch"},
80 Summary: "set the default branch",
81 Usage: "repo settings default-branch <owner/name> <branch>", Run: runSetDefaultBranch})
82 register(Command{Path: []string{"repo", "settings", "git-daemon"},
83 Summary: "expose over git://",
84 Usage: "repo settings git-daemon <owner/name> on|off", Run: runGitDaemon})
85 register(Command{Path: []string{"repo", "archive"},
86 Summary: "archive a repository (read-only: pushes and issue/MR writes refused)",
87 Usage: "repo archive <owner/name>", Run: runArchive})
88 register(Command{Path: []string{"repo", "unarchive"},
89 Summary: "unarchive a repository",
90 Usage: "repo unarchive <owner/name>", Run: runUnarchive})
91 register(Command{Path: []string{"repo", "topics"},
92 Summary: "list topics",
93 Usage: "repo topics <owner/name>", ReadOnly: true, Run: runTopicsList})
94 register(Command{Path: []string{"repo", "topics", "add"},
95 Summary: "add topics",
96 Usage: "repo topics add <owner/name> <topic>...", Run: runTopicsAdd})
97 register(Command{Path: []string{"repo", "topics", "remove"},
98 Summary: "remove topics",
99 Usage: "repo topics remove <owner/name> <topic>...", Run: runTopicsRemove})
100 register(Command{Path: []string{"repo", "search"},
101 Summary: "find repositories by name, description, or topic",
102 Usage: "repo search <query>", ReadOnly: true, Run: runRepoSearch})
103 register(Command{Path: []string{"repo", "grep"},
104 Summary: "search file contents",
105 Usage: "repo grep <owner/name> <query> [--ref <ref>]", ReadOnly: true, Run: runRepoGrep})
106 register(Command{Path: []string{"repo", "diff"},
107 Summary: "the patch between two refs, from their merge base",
108 Usage: "repo diff <owner/name> <base> <head>", ReadOnly: true, Run: runRepoDiff})
109 register(Command{Path: []string{"repo", "pin"},
110 Summary: "pin a repository to your dashboard",
111 Usage: "repo pin <owner/name>", Run: runRepoPin})
112 register(Command{Path: []string{"repo", "unpin"},
113 Summary: "unpin a repository",
114 Usage: "repo unpin <owner/name>", Run: runRepoUnpin})
115 register(Command{Path: []string{"repo", "bookmark"},
116 Summary: "bookmark a repository to come back to",
117 Usage: "repo bookmark <owner/name>", Run: runRepoBookmark})
118 register(Command{Path: []string{"repo", "unbookmark"},
119 Summary: "remove a bookmark",
120 Usage: "repo unbookmark <owner/name>", Run: runRepoUnbookmark})
121 register(Command{Path: []string{"repo", "bookmarks"},
122 Summary: "list the repositories you have bookmarked",
123 Usage: "repo bookmarks", ReadOnly: true, Run: runRepoBookmarks})
124}
125
126const (
127 minQueryLen = 2
128 maxQueryLen = 200
129 maxGrepMatches = 200
130)
131
132func validQuery(q string) error {
133 if len(q) < minQueryLen || len(q) > maxQueryLen {
134 return fmt.Errorf("query must be %d to %d characters", minQueryLen, maxQueryLen)
135 }
136 return nil
137}
138
139// refuseArchived blocks content writes (pushes are refused in the transport
140// layer) on archived repositories. Settings, access, and lifecycle commands
141// stay available so an archived repo can be managed and unarchived.
142func refuseArchived(c *Ctx, repo store.Repo) int {
143 if repo.Settings.Archived {
144 return c.fail(protocol.ExitDenied, "%s is archived and read-only", repo.Path())
145 }
146 return -1
147}
148
149// resolveRepo loads a repo and checks the given permission for c.User.
150func resolveRepo(c *Ctx, path string, check func(store.User, store.Repo, string) bool) (store.Repo, int) {
151 repo, err := c.Store.RepoByPath(path)
152 if err != nil {
153 if errors.Is(err, store.ErrNotFound) {
154 // Same message whether it doesn't exist or is invisible.
155 return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
156 }
157 return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
158 }
159 grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
160 if err != nil {
161 return repo, c.fail(protocol.ExitFailure, "checking access: %v", err)
162 }
163 if !check(c.User, repo, grant) {
164 if !policy.CanRead(c.User, repo, grant) {
165 // Invisible repos 404, per the enumeration rule.
166 return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
167 }
168 return repo, c.fail(protocol.ExitDenied, "permission denied on %s", path)
169 }
170 return repo, -1
171}
172
173func runRepoCreate(c *Ctx, args []string) int {
174 f, err := parseFlags(args, flagSpec{Values: []string{"--description"}, Bools: []string{"--private"}, MaxPos: 1, Usage: "repo create <owner/name> [--private] [--description <text>]"})
175 if err != nil {
176 return c.fail(protocol.ExitUsage, "%v", err)
177 }
178 visibility, path, description := "public", f.pos(0), f.Value("--description")
179 if f.Has("--private") {
180 visibility = "private"
181 }
182 owner, name, ok := strings.Cut(path, "/")
183 if !ok {
184 return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
185 }
186 if err := policyValidateRepoName(name); err != nil {
187 return c.failInput(err)
188 }
189 ownerKind, ownerID := "user", c.User.ID
190 if owner != c.User.Username {
191 org, err := c.Store.OrgByName(owner)
192 if err != nil {
193 return c.fail(protocol.ExitDenied, "cannot create repositories under %q: not you and not an organization you can see", owner)
194 }
195 role, err := c.Store.OrgRole(org.ID, c.User.ID)
196 if err != nil {
197 return c.fail(protocol.ExitFailure, "%v", err)
198 }
199 if role != "admin" {
200 return c.fail(protocol.ExitDenied, "only admins of %s can create repositories there", owner)
201 }
202 ownerKind, ownerID = "org", org.ID
203 }
204 repoCreateMu.Lock()
205 if ownerKind == "user" {
206 if code := checkRepoQuota(c); code >= 0 {
207 repoCreateMu.Unlock()
208 return code
209 }
210 }
211 id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
212 repoCreateMu.Unlock()
213 if err != nil {
214 return c.fail(protocol.ExitFailure, "%v", err)
215 }
216 dir := RepoDir(c.Cfg.Server.Root, owner, name)
217 if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
218 c.Store.DeleteRepo(id)
219 return c.fail(protocol.ExitFailure, "initializing repository: %v", err)
220 }
221 if description != "" {
222 if err := gitutil.WriteDescription(dir, description); err != nil {
223 return c.fail(protocol.ExitFailure, "writing description: %v", err)
224 }
225 }
226 type out struct {
227 Path string `json:"path"`
228 Visibility string `json:"visibility"`
229 SSHURL string `json:"ssh_url"`
230 }
231 d := out{Path: path, Visibility: visibility, SSHURL: "ssh://git@" + hostOf(c.Cfg.Server.SiteURL) + "/" + path + ".git"}
232 return c.emit(d, func(w io.Writer) {
233 fmt.Fprintf(w, "created %s (%s)\nclone: git clone %s\n", d.Path, d.Visibility, d.SSHURL)
234 })
235}
236
237func policyValidateRepoName(name string) error { return policy.ValidateName(name) }
238
239func hostOf(siteURL string) string {
240 s := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")
241 return strings.TrimSuffix(s, "/")
242}
243
244func runRepoList(c *Ctx, args []string) int {
245 args, p, code := parsePageFlags(c, args, "repo", false)
246 if code >= 0 {
247 return code
248 }
249 if len(args) != 0 {
250 return c.fail(protocol.ExitUsage, "usage: repo list [--limit <n>] [--cursor <c>]")
251 }
252 repos, err := c.Store.ListReposForUser(c.User.ID, p.queryLimit(), p.key)
253 if err != nil {
254 return c.fail(protocol.ExitFailure, "%v", err)
255 }
256 repos, next := trimPage(p, repos, "repo", store.Repo.Path)
257 type out struct {
258 Path string `json:"path"`
259 Visibility string `json:"visibility"`
260 Description string `json:"description,omitempty"`
261 Archived bool `json:"archived,omitempty"`
262 }
263 var ds []out
264 for _, r := range repos {
265 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
266 ds = append(ds, out{r.Path(), r.Visibility, desc, r.Settings.Archived})
267 }
268 return c.emitPage(p, ds, next, func(w io.Writer) {
269 for _, d := range ds {
270 mark := ""
271 if d.Archived {
272 mark = "\t[archived]"
273 }
274 fmt.Fprintf(w, "%s\t%s\t%s%s\n", d.Path, d.Visibility, d.Description, mark)
275 }
276 })
277}
278
279func runRepoShow(c *Ctx, args []string) int {
280 if len(args) != 1 {
281 return c.fail(protocol.ExitUsage, "usage: repo show <owner/name>")
282 }
283 repo, code := resolveRepo(c, args[0], policy.CanRead)
284 if code >= 0 {
285 return code
286 }
287 type mirrorOut struct {
288 Direction string `json:"direction"`
289 URL string `json:"url"`
290 Pending bool `json:"pending"`
291 LastSync string `json:"last_sync,omitempty"`
292 LastError string `json:"last_error,omitempty"`
293 }
294 type out struct {
295 Path string `json:"path"`
296 Description string `json:"description,omitempty"`
297 Website string `json:"website,omitempty"`
298 Visibility string `json:"visibility"`
299 DefaultBranch string `json:"default_branch"`
300 ProtectedBranches []string `json:"protected_branches,omitempty"`
301 Archived bool `json:"archived,omitempty"`
302 Topics []string `json:"topics,omitempty"`
303 Domains []string `json:"domains,omitempty"`
304 Mirrors []mirrorOut `json:"mirrors,omitempty"`
305 // ForkOf names the parent only when the caller can read it: a
306 // private parent is not confirmed to exist, here as anywhere.
307 ForkOf string `json:"fork_of,omitempty"`
308 // Watch and Bookmarked are the caller's own state, so a client
309 // can draw a toggle rather than two stateless buttons (#178).
310 Watch string `json:"watch,omitempty"` // watching, muted, or absent
311 Bookmarked bool `json:"bookmarked,omitempty"`
312 }
313 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name))
314 topics, err := c.Store.ListTopics(repo.ID)
315 if err != nil {
316 return c.fail(protocol.ExitFailure, "%v", err)
317 }
318 var domains []string
319 if ds, err := c.Store.ListPageDomains(repo.ID); err == nil {
320 for _, pd := range ds {
321 if pd.Verified() {
322 domains = append(domains, pd.Domain)
323 }
324 }
325 }
326 d := out{Path: repo.Path(), Description: desc, Website: repo.Settings.Website, Visibility: repo.Visibility,
327 DefaultBranch: repo.DefaultBranch, ProtectedBranches: repo.Settings.ProtectedBranches,
328 Archived: repo.Settings.Archived, Topics: topics, Domains: domains}
329 if repo.ForkOf != 0 {
330 if parent, err := c.Store.RepoByID(repo.ForkOf); err == nil {
331 if grant, err := c.Store.AccessRole(parent.ID, c.User.ID); err == nil && policy.CanRead(c.User, parent, grant) {
332 d.ForkOf = parent.Path()
333 }
334 }
335 }
336 if c.User.ID != 0 {
337 d.Watch = c.Store.RepoWatchState(repo.ID, c.User.ID)
338 d.Bookmarked = c.Store.IsBookmarked(c.User.ID, repo.ID)
339 }
340 // Mirror status is admin-only, like repo mirror list. The token never
341 // leaves the server.
342 if grant, err := c.Store.AccessRole(repo.ID, c.User.ID); err == nil && policy.CanAdmin(c.User, repo, grant) {
343 ms, err := c.Store.ListMirrors(repo.ID)
344 if err != nil {
345 return c.fail(protocol.ExitFailure, "%v", err)
346 }
347 for _, m := range ms {
348 d.Mirrors = append(d.Mirrors, mirrorOut{m.Direction, m.URL, m.Dirty, m.LastSync, m.LastError})
349 }
350 }
351 return c.emit(d, func(w io.Writer) {
352 line := fmt.Sprintf("%s\t%s\tdefault: %s", d.Path, d.Visibility, d.DefaultBranch)
353 if d.Archived {
354 line += "\t[archived]"
355 }
356 fmt.Fprintln(w, line)
357 if d.Description != "" {
358 fmt.Fprintf(w, "%s\n", d.Description)
359 }
360 if d.Website != "" {
361 fmt.Fprintf(w, "website: %s\n", d.Website)
362 }
363 if len(d.Topics) > 0 {
364 fmt.Fprintf(w, "topics: %s\n", strings.Join(d.Topics, ", "))
365 }
366 if len(d.ProtectedBranches) > 0 {
367 fmt.Fprintf(w, "protected: %s\n", strings.Join(d.ProtectedBranches, ", "))
368 }
369 if len(d.Domains) > 0 {
370 fmt.Fprintf(w, "pages domains: %s\n", strings.Join(d.Domains, ", "))
371 }
372 if d.ForkOf != "" {
373 fmt.Fprintf(w, "fork of: %s\n", d.ForkOf)
374 }
375 if d.Watch != "" {
376 fmt.Fprintf(w, "watch: %s\n", d.Watch)
377 }
378 if d.Bookmarked {
379 fmt.Fprintln(w, "bookmarked")
380 }
381 for _, m := range d.Mirrors {
382 status := "ok"
383 if m.Pending {
384 status = "pending"
385 }
386 if m.LastError != "" {
387 status = "error: " + m.LastError
388 }
389 fmt.Fprintf(w, "mirror: %s %s\tlast %s\t%s\n", m.Direction, m.URL, orDash(m.LastSync), status)
390 }
391 })
392}
393
394func runRepoTransfer(c *Ctx, args []string) int {
395 if len(args) != 2 {
396 return c.fail(protocol.ExitUsage, "usage: repo transfer <owner/name> <new-owner>")
397 }
398 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
399 if code >= 0 {
400 return code
401 }
402 newOwner := args[1]
403 if newOwner == repo.OwnerName {
404 return c.fail(protocol.ExitUsage, "%s already owns this repository", newOwner)
405 }
406
407 // Target: yourself, or an org you admin — same rule as repo create.
408 newKind, newID := "", int64(0)
409 if newOwner == c.User.Username {
410 newKind, newID = "user", c.User.ID
411 } else if org, err := c.Store.OrgByName(newOwner); err == nil {
412 role, err := c.Store.OrgRole(org.ID, c.User.ID)
413 if err != nil {
414 return c.fail(protocol.ExitFailure, "%v", err)
415 }
416 if role != "admin" {
417 return c.fail(protocol.ExitDenied, "only admins of %s can receive repositories there", newOwner)
418 }
419 newKind, newID = "org", org.ID
420 } else {
421 return c.fail(protocol.ExitDenied, "cannot transfer to %q: not you and not an organization you can see", newOwner)
422 }
423
424 oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
425 newDir := RepoDir(c.Cfg.Server.Root, newOwner, repo.Name)
426 if _, err := os.Stat(newDir); err == nil {
427 return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", newOwner, repo.Name)
428 }
429 // The directory moves before the record changes: a move that fails
430 // leaves nothing to undo, whereas the record's change into an org
431 // folds labels and milestones into the org's rows, which a revert
432 // cannot unfold (#212). A record that then fails moves the directory
433 // back, and says so if even that fails, since the operator then has
434 // a row pointing at a directory that is not there.
435 if err := os.MkdirAll(filepath.Dir(newDir), 0o750); err != nil {
436 return c.fail(protocol.ExitFailure, "%v", err)
437 }
438 if err := os.Rename(oldDir, newDir); err != nil {
439 return c.fail(protocol.ExitFailure, "moving repository: %v", err)
440 }
441 if err := c.Store.TransferRepo(repo.ID, newKind, newID); err != nil {
442 if rerr := os.Rename(newDir, oldDir); rerr != nil {
443 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)
444 }
445 return c.failErr(err)
446 }
447 newPath := newOwner + "/" + repo.Name
448 return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
449 fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
450 })
451}
452
453func runRepoRename(c *Ctx, args []string) int {
454 if len(args) != 2 {
455 return c.fail(protocol.ExitUsage, "usage: repo rename <owner/name> <new-name>")
456 }
457 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
458 if code >= 0 {
459 return code
460 }
461 newName := args[1]
462 if newName == repo.Name {
463 return c.fail(protocol.ExitUsage, "%s is already named %s", repo.Path(), newName)
464 }
465 if err := policyValidateRepoName(newName); err != nil {
466 return c.failInput(err)
467 }
468 oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
469 newDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, newName)
470 if _, err := os.Stat(newDir); err == nil {
471 return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", repo.OwnerName, newName)
472 }
473 if err := c.Store.RenameRepo(repo.ID, newName); err != nil {
474 return c.failErr(err)
475 }
476 if err := os.Rename(oldDir, newDir); err != nil {
477 // Same rule as transfer: keep name and disk consistent, and say so
478 // if even the revert fails.
479 if rerr := c.Store.RenameRepo(repo.ID, repo.Name); rerr != nil {
480 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())
481 }
482 return c.fail(protocol.ExitFailure, "moving repository: %v", err)
483 }
484 newPath := repo.OwnerName + "/" + newName
485 return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
486 fmt.Fprintf(w, "renamed %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
487 })
488}
489
490func runRepoDelete(c *Ctx, args []string) int {
491 var path string
492 var yes bool
493 for _, a := range args {
494 if a == "--yes" {
495 yes = true
496 } else if path == "" {
497 path = a
498 } else {
499 return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
500 }
501 }
502 if path == "" {
503 return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
504 }
505 repo, code := resolveRepo(c, path, policy.CanAdmin)
506 if code >= 0 {
507 return code
508 }
509 if !yes {
510 return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
511 }
512 return deleteRepo(c, repo)
513}
514
515// deleteRepo removes a repository the caller has already been cleared to
516// delete: the database row, then the directory.
517//
518// There is deliberately no repo.deleted event. events.repo_id and
519// webhooks.repo_id both cascade from repos, so recording one would delete
520// it, and every webhook that could have subscribed, in the same
521// statement. A repository's deletion is not observable through its own
522// webhooks; an instance that needs to hear about it wants the audit log
523// (#112).
524func deleteRepo(c *Ctx, repo store.Repo) int {
525 // Open MRs sourced from this repo keep working (targets own the
526 // objects) but must show that the source is gone.
527 if err := c.Store.MarkSourceGoneForRepo(repo.ID); err != nil {
528 return c.fail(protocol.ExitFailure, "%v", err)
529 }
530 if err := c.Store.DeleteRepo(repo.ID); err != nil {
531 return c.fail(protocol.ExitFailure, "%v", err)
532 }
533 if err := os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)); err != nil {
534 return c.fail(protocol.ExitFailure, "database row removed but disk cleanup failed: %v", err)
535 }
536 return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
537 fmt.Fprintf(w, "deleted %s\n", repo.Path())
538 })
539}
540
541func runAccessGrant(c *Ctx, args []string) int {
542 if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
543 return c.fail(protocol.ExitUsage, "usage: repo access grant <owner/name> <user> read|write|admin")
544 }
545 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
546 if code >= 0 {
547 return code
548 }
549 target, err := c.Store.UserByUsername(args[1])
550 if err != nil {
551 return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
552 }
553 if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
554 return c.fail(protocol.ExitFailure, "%v", err)
555 }
556 return c.emit(map[string]string{"granted": args[2], "user": target.Username},
557 func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
558}
559
560func runAccessRevoke(c *Ctx, args []string) int {
561 if len(args) != 2 {
562 return c.fail(protocol.ExitUsage, "usage: repo access revoke <owner/name> <user>")
563 }
564 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
565 if code >= 0 {
566 return code
567 }
568 target, err := c.Store.UserByUsername(args[1])
569 if err != nil {
570 return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
571 }
572 if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
573 if errors.Is(err, store.ErrNotFound) {
574 return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
575 }
576 return c.fail(protocol.ExitFailure, "%v", err)
577 }
578 return c.emit(map[string]string{"revoked": target.Username},
579 func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
580}
581
582func runAccessList(c *Ctx, args []string) int {
583 if len(args) != 1 {
584 return c.fail(protocol.ExitUsage, "usage: repo access list <owner/name>")
585 }
586 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
587 if code >= 0 {
588 return code
589 }
590 entries, err := c.Store.EffectiveAccess(repo.ID)
591 if err != nil {
592 return c.fail(protocol.ExitFailure, "%v", err)
593 }
594 type out struct {
595 User string `json:"user"`
596 Role string `json:"role"`
597 Source string `json:"source"`
598 }
599 var ds []out
600 for _, e := range entries {
601 ds = append(ds, out{e.Username, e.Role, e.Source})
602 }
603 return c.emit(ds, func(w io.Writer) {
604 for _, d := range ds {
605 fmt.Fprintf(w, "%s\t%s\tvia %s\n", d.User, d.Role, d.Source)
606 }
607 })
608}
609
610func runSettingsShow(c *Ctx, args []string) int {
611 if len(args) != 1 {
612 return c.fail(protocol.ExitUsage, "usage: repo settings show <owner/name>")
613 }
614 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
615 if code >= 0 {
616 return code
617 }
618 return c.emit(repo.Settings, func(w io.Writer) {
619 fmt.Fprintf(w, "protected_branches: %s\nprotected_tags: %s\nrequire_mr: %v\nrequire_signed_commits: %v\ngit_daemon: %v\narchived: %v\n",
620 strings.Join(repo.Settings.ProtectedBranches, ", "), strings.Join(repo.Settings.ProtectedTags, ", "), repo.Settings.RequireMR, repo.Settings.RequireSignedCommits, repo.Settings.GitDaemon, repo.Settings.Archived)
621 })
622}
623
624func runSetDescription(c *Ctx, args []string) int {
625 if len(args) != 2 {
626 return c.fail(protocol.ExitUsage, "usage: repo settings description <owner/name> <text>")
627 }
628 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
629 if code >= 0 {
630 return code
631 }
632 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
633 if err := gitutil.WriteDescription(dir, args[1]); err != nil {
634 return c.fail(protocol.ExitFailure, "%v", err)
635 }
636 return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
637 fmt.Fprintf(w, "description set on %s\n", repo.Path())
638 })
639}
640
641func runSetDefaultBranch(c *Ctx, args []string) int {
642 if len(args) != 2 {
643 return c.fail(protocol.ExitUsage, "usage: repo settings default-branch <owner/name> <branch>")
644 }
645 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
646 if code >= 0 {
647 return code
648 }
649 branch := args[1]
650 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
651 if _, err := gitutil.ResolveRef(dir, "refs/heads/"+branch); err != nil {
652 return c.fail(protocol.ExitFailure, "no branch named %q on %s", branch, repo.Path())
653 }
654 if err := gitutil.SetHead(dir, branch); err != nil {
655 return c.fail(protocol.ExitFailure, "%v", err)
656 }
657 if err := c.Store.UpdateDefaultBranch(repo.ID, branch); err != nil {
658 return c.fail(protocol.ExitFailure, "%v", err)
659 }
660 return c.emit(map[string]string{"default_branch": branch}, func(w io.Writer) {
661 fmt.Fprintf(w, "default branch of %s is now %s\n", repo.Path(), branch)
662 })
663}
664
665func runSetWebsite(c *Ctx, args []string) int {
666 if len(args) != 2 {
667 return c.fail(protocol.ExitUsage, "usage: repo settings website <owner/name> <url>")
668 }
669 site := strings.TrimSpace(args[1])
670 if err := validateWebsite(site); err != nil {
671 return c.failInput(err)
672 }
673 if len(site) > 256 {
674 return c.fail(protocol.ExitUsage, "website URL too long (max 256)")
675 }
676 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
677 if code >= 0 {
678 return code
679 }
680 if _, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Website = site }); err != nil {
681 return c.fail(protocol.ExitFailure, "%v", err)
682 }
683 return c.emit(map[string]string{"website": site}, func(w io.Writer) {
684 if site == "" {
685 fmt.Fprintf(w, "website cleared on %s\n", repo.Path())
686 } else {
687 fmt.Fprintf(w, "website set on %s\n", repo.Path())
688 }
689 })
690}
691
692func runSetVisibility(c *Ctx, args []string) int {
693 if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
694 return c.fail(protocol.ExitUsage, "usage: repo settings visibility <owner/name> public|private")
695 }
696 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
697 if code >= 0 {
698 return code
699 }
700 return setRepoVisibility(c, repo, args[1])
701}
702
703// setRepoVisibility applies a visibility change the caller has already
704// been cleared to make.
705func setRepoVisibility(c *Ctx, repo store.Repo, visibility string) int {
706 if repo.Visibility == visibility {
707 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
708 fmt.Fprintf(w, "%s is already %s\n", repo.Path(), visibility)
709 })
710 }
711 if err := c.Store.SetRepoVisibility(repo.ID, visibility); err != nil {
712 return c.fail(protocol.ExitFailure, "%v", err)
713 }
714 // Going private takes the repository off every anonymous surface, so
715 // git:// exposure cannot outlive the change.
716 if visibility == "private" && repo.Settings.GitDaemon {
717 c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = false })
718 }
719 c.Store.Audit(c.User.ID, "repo.visibility", map[string]any{"repo": repo.ID, "visibility": visibility})
720 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
721 fmt.Fprintf(w, "%s is now %s\n", repo.Path(), visibility)
722 })
723}
724
725func runGitDaemon(c *Ctx, args []string) int {
726 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
727 return c.fail(protocol.ExitUsage, "usage: repo settings git-daemon <owner/name> on|off")
728 }
729 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
730 if code >= 0 {
731 return code
732 }
733 on := args[1] == "on"
734 if on && repo.Visibility != "public" {
735 return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
736 }
737 if on && !c.Cfg.GitDaemon.Enabled {
738 return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
739 }
740 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = on })
741 if err != nil {
742 return c.fail(protocol.ExitFailure, "%v", err)
743 }
744 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
745}
746
747func runArchive(c *Ctx, args []string) int { return setArchived(c, args, true) }
748func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
749
750func setArchived(c *Ctx, args []string, archived bool) int {
751 verb := "archive"
752 if !archived {
753 verb = "unarchive"
754 }
755 if len(args) != 1 {
756 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
757 }
758 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
759 if code >= 0 {
760 return code
761 }
762 return archiveRepo(c, repo, archived)
763}
764
765// archiveRepo flips the archived flag on a repository the caller has
766// already been cleared to manage.
767func archiveRepo(c *Ctx, repo store.Repo, archived bool) int {
768 verb := "archive"
769 if !archived {
770 verb = "unarchive"
771 }
772 if repo.Settings.Archived == archived {
773 return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
774 }
775 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Archived = archived })
776 if err != nil {
777 return c.fail(protocol.ExitFailure, "%v", err)
778 }
779 c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
780 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
781}
782
783func runTopicsList(c *Ctx, args []string) int {
784 if len(args) != 1 {
785 return c.fail(protocol.ExitUsage, "usage: repo topics <owner/name>")
786 }
787 repo, code := resolveRepo(c, args[0], policy.CanRead)
788 if code >= 0 {
789 return code
790 }
791 topics, err := c.Store.ListTopics(repo.ID)
792 if err != nil {
793 return c.fail(protocol.ExitFailure, "%v", err)
794 }
795 return c.emit(topics, func(w io.Writer) {
796 for _, t := range topics {
797 fmt.Fprintln(w, t)
798 }
799 })
800}
801
802func runTopicsAdd(c *Ctx, args []string) int { return editTopics(c, args, true) }
803func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
804
805func editTopics(c *Ctx, args []string, add bool) int {
806 verb := "add"
807 if !add {
808 verb = "remove"
809 }
810 if len(args) < 2 {
811 return c.fail(protocol.ExitUsage, "usage: repo topics %s <owner/name> <topic>...", verb)
812 }
813 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
814 if code >= 0 {
815 return code
816 }
817 topics := args[1:]
818 if add {
819 for _, t := range topics {
820 if err := policy.ValidateTopic(t); err != nil {
821 return c.failInput(err)
822 }
823 }
824 have, err := c.Store.ListTopics(repo.ID)
825 if err != nil {
826 return c.fail(protocol.ExitFailure, "%v", err)
827 }
828 added := 0
829 for _, t := range topics {
830 if !slices.Contains(have, t) {
831 added++
832 }
833 }
834 if len(have)+added > policy.MaxTopics {
835 return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
836 }
837 for _, t := range topics {
838 if err := c.Store.AddTopic(repo.ID, t); err != nil {
839 return c.fail(protocol.ExitFailure, "%v", err)
840 }
841 }
842 } else {
843 for _, t := range topics {
844 if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
845 if errors.Is(err, store.ErrNotFound) {
846 return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
847 }
848 return c.fail(protocol.ExitFailure, "%v", err)
849 }
850 }
851 }
852 now, err := c.Store.ListTopics(repo.ID)
853 if err != nil {
854 return c.fail(protocol.ExitFailure, "%v", err)
855 }
856 return c.emit(now, func(w io.Writer) {
857 fmt.Fprintf(w, "topics on %s: %s\n", repo.Path(), strings.Join(now, ", "))
858 })
859}
860
861// runRepoSearch matches the query against name, owner/name, description,
862// and topics of every repository the caller can see.
863func runRepoSearch(c *Ctx, args []string) int {
864 if len(args) != 1 {
865 return c.fail(protocol.ExitUsage, "usage: repo search <query>")
866 }
867 if err := validQuery(args[0]); err != nil {
868 return c.failInput(err)
869 }
870 q := strings.ToLower(args[0])
871
872 public, err := c.Store.ListPublicRepos()
873 if err != nil {
874 return c.fail(protocol.ExitFailure, "%v", err)
875 }
876 own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
877 if err != nil {
878 return c.fail(protocol.ExitFailure, "%v", err)
879 }
880 seen := map[int64]bool{}
881 type out struct {
882 Path string `json:"path"`
883 Visibility string `json:"visibility"`
884 Description string `json:"description,omitempty"`
885 Topics []string `json:"topics,omitempty"`
886 }
887 var ds []out
888 for _, r := range append(public, own...) {
889 if seen[r.ID] {
890 continue
891 }
892 seen[r.ID] = true
893 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
894 topics, _ := c.Store.ListTopics(r.ID)
895 if !MatchesRepo(q, r.Path(), desc, topics) {
896 continue
897 }
898 ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
899 }
900 return c.emit(ds, func(w io.Writer) {
901 for _, d := range ds {
902 fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
903 }
904 })
905}
906
907// MatchesRepo is the one rule for matching a repository against a text
908// query: its path, its description, or any of its topics. The web's
909// /explore filter and /search page call it too, so the three surfaces
910// cannot answer the same query differently.
911func MatchesRepo(q, path, desc string, topics []string) bool {
912 q = strings.ToLower(q)
913 if strings.Contains(strings.ToLower(path), q) ||
914 strings.Contains(strings.ToLower(desc), q) {
915 return true
916 }
917 for _, t := range topics {
918 if strings.Contains(strings.ToLower(t), q) {
919 return true
920 }
921 }
922 return false
923}
924
925func runRepoGrep(c *Ctx, args []string) int {
926 f, err := parseFlags(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: "repo grep <owner/name> <query> [--ref <ref>]"})
927 if err != nil {
928 return c.fail(protocol.ExitUsage, "%v", err)
929 }
930 path, query, ref := f.pos(0), f.pos(1), f.Value("--ref")
931 if path == "" || query == "" {
932 return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
933 }
934 if err := validQuery(query); err != nil {
935 return c.failInput(err)
936 }
937 repo, code := resolveRepo(c, path, policy.CanRead)
938 if code >= 0 {
939 return code
940 }
941 if ref == "" {
942 ref = repo.DefaultBranch
943 }
944 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
945 if _, err := gitutil.ResolveRef(dir, ref); err != nil {
946 return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
947 }
948 matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
949 if err != nil {
950 return c.fail(protocol.ExitFailure, "%v", err)
951 }
952 type out struct {
953 Path string `json:"path"`
954 Line int `json:"line"`
955 Text string `json:"text"`
956 }
957 var ds []out
958 for _, m := range matches {
959 ds = append(ds, out{m.Path, m.Line, m.Text})
960 }
961 return c.emit(ds, func(w io.Writer) {
962 for _, d := range ds {
963 fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
964 }
965 })
966}
967
968func runRepoPin(c *Ctx, args []string) int { return setPinned(c, args, true) }
969func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
970
971func setPinned(c *Ctx, args []string, pin bool) int {
972 verb := "pin"
973 if !pin {
974 verb = "unpin"
975 }
976 if len(args) != 1 {
977 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
978 }
979 repo, code := resolveRepo(c, args[0], policy.CanRead)
980 if code >= 0 {
981 return code
982 }
983 if pin {
984 if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
985 return c.fail(protocol.ExitFailure, "%v", err)
986 }
987 } else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
988 if errors.Is(err, store.ErrNotFound) {
989 return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
990 }
991 return c.fail(protocol.ExitFailure, "%v", err)
992 }
993 return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
994 fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
995 })
996}
997
998func runRepoBookmark(c *Ctx, args []string) int { return setBookmarked(c, args, true) }
999func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
1000
1001// setBookmarked mirrors setPinned. A bookmark needs only read access —
1002// bookmarking is something you do to someone else's repository, which is
1003// the whole point of it — and a private repository you cannot read is
1004// not found, as everywhere.
1005func setBookmarked(c *Ctx, args []string, on bool) int {
1006 verb := "bookmark"
1007 if !on {
1008 verb = "unbookmark"
1009 }
1010 if len(args) != 1 {
1011 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
1012 }
1013 repo, code := resolveRepo(c, args[0], policy.CanRead)
1014 if code >= 0 {
1015 return code
1016 }
1017 if on {
1018 if err := c.Store.BookmarkRepo(c.User.ID, repo.ID); err != nil {
1019 return c.fail(protocol.ExitFailure, "%v", err)
1020 }
1021 } else if err := c.Store.UnbookmarkRepo(c.User.ID, repo.ID); err != nil {
1022 if errors.Is(err, store.ErrNotFound) {
1023 return c.fail(protocol.ExitNotFound, "%s is not bookmarked", repo.Path())
1024 }
1025 return c.fail(protocol.ExitFailure, "%v", err)
1026 }
1027 return c.emit(map[string]string{verb + "ed": repo.Path()}, func(w io.Writer) {
1028 fmt.Fprintf(w, "%sed %s\n", verb, repo.Path())
1029 })
1030}
1031
1032// BookmarkOut is one row of `repo bookmarks`: the repository and how many
1033// people have bookmarked it.
1034type BookmarkOut struct {
1035 Path string `json:"path"`
1036 Description string `json:"description,omitempty"`
1037 Visibility string `json:"visibility"`
1038 Bookmarks int `json:"bookmarks"`
1039}
1040
1041func runRepoBookmarks(c *Ctx, args []string) int {
1042 if len(args) != 0 {
1043 return c.fail(protocol.ExitUsage, "usage: repo bookmarks")
1044 }
1045 repos, err := c.Store.ListBookmarks(c.User.ID)
1046 if err != nil {
1047 return c.fail(protocol.ExitFailure, "%v", err)
1048 }
1049 out := []BookmarkOut{}
1050 for _, r := range repos {
1051 // A repository bookmarked while public and since made private
1052 // stays in the table and drops out of the listing, the same way
1053 // it disappears from every other surface.
1054 grant, err := c.Store.AccessRole(r.ID, c.User.ID)
1055 if err != nil {
1056 return c.fail(protocol.ExitFailure, "%v", err)
1057 }
1058 if !policy.CanRead(c.User, r, grant) {
1059 continue
1060 }
1061 out = append(out, BookmarkOut{
1062 Path: r.Path(),
1063 Description: gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)),
1064 Visibility: r.Visibility,
1065 Bookmarks: c.Store.BookmarkCount(r.ID),
1066 })
1067 }
1068 return c.emit(out, func(w io.Writer) {
1069 for _, b := range out {
1070 fmt.Fprintf(w, "%s\t%d\t%s\n", b.Path, b.Bookmarks, b.Description)
1071 }
1072 })
1073}
1074
1075func runProtectTag(c *Ctx, args []string) int { return setProtectTag(c, args, true) }
1076func runUnprotectTag(c *Ctx, args []string) int { return setProtectTag(c, args, false) }
1077
1078func setProtectTag(c *Ctx, args []string, protect bool) int {
1079 if len(args) != 2 {
1080 return c.fail(protocol.ExitUsage, "usage: repo settings protect-tag|unprotect-tag <owner/name> <glob>")
1081 }
1082 glob := args[1]
1083 if _, err := path.Match(glob, "x"); err != nil || glob == "" {
1084 return c.fail(protocol.ExitUsage, "bad glob %q", glob)
1085 }
1086 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1087 if code >= 0 {
1088 return code
1089 }
1090 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1091 has := slices.Contains(s.ProtectedTags, glob)
1092 if protect && !has {
1093 s.ProtectedTags = append(s.ProtectedTags, glob)
1094 slices.Sort(s.ProtectedTags)
1095 }
1096 if !protect && has {
1097 s.ProtectedTags = slices.DeleteFunc(s.ProtectedTags, func(g string) bool { return g == glob })
1098 }
1099 })
1100 if err != nil {
1101 return c.fail(protocol.ExitFailure, "%v", err)
1102 }
1103 verb := "protected"
1104 if !protect {
1105 verb = "unprotected"
1106 }
1107 return c.emit(s, func(w io.Writer) {
1108 fmt.Fprintf(w, "tags %s %s on %s\n", glob, verb, repo.Path())
1109 })
1110}
1111
1112func runProtect(c *Ctx, args []string) int { return setProtect(c, args, true) }
1113func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
1114
1115func setProtect(c *Ctx, args []string, protect bool) int {
1116 if len(args) != 2 {
1117 return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
1118 }
1119 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1120 if code >= 0 {
1121 return code
1122 }
1123 branch := args[1]
1124 // The list is read and rewritten inside the update, so two admins
1125 // protecting different branches at once both land.
1126 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1127 has := slices.Contains(s.ProtectedBranches, branch)
1128 if protect && !has {
1129 s.ProtectedBranches = append(s.ProtectedBranches, branch)
1130 slices.Sort(s.ProtectedBranches)
1131 }
1132 if !protect && has {
1133 s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
1134 }
1135 })
1136 if err != nil {
1137 return c.fail(protocol.ExitFailure, "%v", err)
1138 }
1139 verb := "protected"
1140 if !protect {
1141 verb = "unprotected"
1142 }
1143 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
1144}
1145
1146// runRepoDiff is the compare view's command: what head adds on top of
1147// base, measured from their merge base the way a merge request diff is,
1148// so a base that moved on does not show up as removals (#118).
1149func runRepoDiff(c *Ctx, args []string) int {
1150 f, err := parseFlags(args, flagSpec{MaxPos: 3, Usage: "repo diff <owner/name> <base> <head>"})
1151 if err != nil || len(f.Pos) != 3 {
1152 return c.fail(protocol.ExitUsage, "usage: repo diff <owner/name> <base> <head>")
1153 }
1154 repo, code := resolveRepo(c, f.pos(0), policy.CanRead)
1155 if code >= 0 {
1156 return code
1157 }
1158 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1159 base, err := gitutil.ResolveRef(dir, f.pos(1))
1160 if err != nil {
1161 return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(1), repo.Path())
1162 }
1163 head, err := gitutil.ResolveRef(dir, f.pos(2))
1164 if err != nil {
1165 return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(2), repo.Path())
1166 }
1167 mergeBase, err := gitutil.MergeBase(dir, base, head)
1168 if err != nil {
1169 return c.fail(protocol.ExitUsage, "%v", err)
1170 }
1171 patch, truncated, err := gitutil.Diff(dir, mergeBase, head, 4<<20)
1172 if err != nil {
1173 return c.fail(protocol.ExitFailure, "%v", err)
1174 }
1175 if c.JSON {
1176 return c.emit(map[string]any{"base": base, "head": head, "merge_base": mergeBase, "patch": patch, "truncated": truncated}, nil)
1177 }
1178 fmt.Fprint(c.Stdout, patch)
1179 if truncated {
1180 fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB")
1181 }
1182 return protocol.ExitOK
1183}