internal/control/repo.go

da232bfde4952959944a074ccec455f38eab3b66
gitbay/internal/control/repo.go history · blame · raw

1177 lines · 41132 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; unarchive it first", 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; ask its owner for access", 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 500		}
 501	}
 502	if path == "" {
 503		return c.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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.usage()
 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	if len(args) != 1 {
 752		return c.usage()
 753	}
 754	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 755	if code >= 0 {
 756		return code
 757	}
 758	return archiveRepo(c, repo, archived)
 759}
 760
 761// archiveRepo flips the archived flag on a repository the caller has
 762// already been cleared to manage.
 763func archiveRepo(c *Ctx, repo store.Repo, archived bool) int {
 764	verb := "archive"
 765	if !archived {
 766		verb = "unarchive"
 767	}
 768	if repo.Settings.Archived == archived {
 769		return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
 770	}
 771	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Archived = archived })
 772	if err != nil {
 773		return c.fail(protocol.ExitFailure, "%v", err)
 774	}
 775	c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
 776	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
 777}
 778
 779func runTopicsList(c *Ctx, args []string) int {
 780	if len(args) != 1 {
 781		return c.usage()
 782	}
 783	repo, code := resolveRepo(c, args[0], policy.CanRead)
 784	if code >= 0 {
 785		return code
 786	}
 787	topics, err := c.Store.ListTopics(repo.ID)
 788	if err != nil {
 789		return c.fail(protocol.ExitFailure, "%v", err)
 790	}
 791	return c.emit(topics, func(w io.Writer) {
 792		for _, t := range topics {
 793			fmt.Fprintln(w, t)
 794		}
 795	})
 796}
 797
 798func runTopicsAdd(c *Ctx, args []string) int    { return editTopics(c, args, true) }
 799func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
 800
 801func editTopics(c *Ctx, args []string, add bool) int {
 802	if len(args) < 2 {
 803		return c.usage()
 804	}
 805	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 806	if code >= 0 {
 807		return code
 808	}
 809	topics := args[1:]
 810	if add {
 811		for _, t := range topics {
 812			if err := policy.ValidateTopic(t); err != nil {
 813				return c.failInput(err)
 814			}
 815		}
 816		have, err := c.Store.ListTopics(repo.ID)
 817		if err != nil {
 818			return c.fail(protocol.ExitFailure, "%v", err)
 819		}
 820		added := 0
 821		for _, t := range topics {
 822			if !slices.Contains(have, t) {
 823				added++
 824			}
 825		}
 826		if len(have)+added > policy.MaxTopics {
 827			return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
 828		}
 829		for _, t := range topics {
 830			if err := c.Store.AddTopic(repo.ID, t); err != nil {
 831				return c.fail(protocol.ExitFailure, "%v", err)
 832			}
 833		}
 834	} else {
 835		for _, t := range topics {
 836			if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
 837				if errors.Is(err, store.ErrNotFound) {
 838					return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
 839				}
 840				return c.fail(protocol.ExitFailure, "%v", err)
 841			}
 842		}
 843	}
 844	now, err := c.Store.ListTopics(repo.ID)
 845	if err != nil {
 846		return c.fail(protocol.ExitFailure, "%v", err)
 847	}
 848	return c.emit(now, func(w io.Writer) {
 849		for _, t := range now {
 850			fmt.Fprintln(w, t)
 851		}
 852	})
 853}
 854
 855// runRepoSearch matches the query against name, owner/name, description,
 856// and topics of every repository the caller can see.
 857func runRepoSearch(c *Ctx, args []string) int {
 858	if len(args) != 1 {
 859		return c.usage()
 860	}
 861	if err := validQuery(args[0]); err != nil {
 862		return c.failInput(err)
 863	}
 864	q := strings.ToLower(args[0])
 865
 866	public, err := c.Store.ListPublicRepos()
 867	if err != nil {
 868		return c.fail(protocol.ExitFailure, "%v", err)
 869	}
 870	own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
 871	if err != nil {
 872		return c.fail(protocol.ExitFailure, "%v", err)
 873	}
 874	seen := map[int64]bool{}
 875	type out struct {
 876		Path        string   `json:"path"`
 877		Visibility  string   `json:"visibility"`
 878		Description string   `json:"description,omitempty"`
 879		Topics      []string `json:"topics,omitempty"`
 880	}
 881	var ds []out
 882	for _, r := range append(public, own...) {
 883		if seen[r.ID] {
 884			continue
 885		}
 886		seen[r.ID] = true
 887		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
 888		topics, _ := c.Store.ListTopics(r.ID)
 889		if !MatchesRepo(q, r.Path(), desc, topics) {
 890			continue
 891		}
 892		ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
 893	}
 894	return c.emit(ds, func(w io.Writer) {
 895		for _, d := range ds {
 896			fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
 897		}
 898	})
 899}
 900
 901// MatchesRepo is the one rule for matching a repository against a text
 902// query: its path, its description, or any of its topics. The web's
 903// /explore filter and /search page call it too, so the three surfaces
 904// cannot answer the same query differently.
 905func MatchesRepo(q, path, desc string, topics []string) bool {
 906	q = strings.ToLower(q)
 907	if strings.Contains(strings.ToLower(path), q) ||
 908		strings.Contains(strings.ToLower(desc), q) {
 909		return true
 910	}
 911	for _, t := range topics {
 912		if strings.Contains(strings.ToLower(t), q) {
 913			return true
 914		}
 915	}
 916	return false
 917}
 918
 919func runRepoGrep(c *Ctx, args []string) int {
 920	f, err := parseFlags(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: "repo grep <owner/name> <query> [--ref <ref>]"})
 921	if err != nil {
 922		return c.fail(protocol.ExitUsage, "%v", err)
 923	}
 924	path, query, ref := f.pos(0), f.pos(1), f.Value("--ref")
 925	if path == "" || query == "" {
 926		return c.usage()
 927	}
 928	if err := validQuery(query); err != nil {
 929		return c.failInput(err)
 930	}
 931	repo, code := resolveRepo(c, path, policy.CanRead)
 932	if code >= 0 {
 933		return code
 934	}
 935	if ref == "" {
 936		ref = repo.DefaultBranch
 937	}
 938	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 939	if _, err := gitutil.ResolveRef(dir, ref); err != nil {
 940		return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
 941	}
 942	matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
 943	if err != nil {
 944		return c.fail(protocol.ExitFailure, "%v", err)
 945	}
 946	type out struct {
 947		Path string `json:"path"`
 948		Line int    `json:"line"`
 949		Text string `json:"text"`
 950	}
 951	var ds []out
 952	for _, m := range matches {
 953		ds = append(ds, out{m.Path, m.Line, m.Text})
 954	}
 955	return c.emit(ds, func(w io.Writer) {
 956		for _, d := range ds {
 957			fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
 958		}
 959	})
 960}
 961
 962func runRepoPin(c *Ctx, args []string) int   { return setPinned(c, args, true) }
 963func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
 964
 965func setPinned(c *Ctx, args []string, pin bool) int {
 966	verb := "pin"
 967	if !pin {
 968		verb = "unpin"
 969	}
 970	if len(args) != 1 {
 971		return c.usage()
 972	}
 973	repo, code := resolveRepo(c, args[0], policy.CanRead)
 974	if code >= 0 {
 975		return code
 976	}
 977	if pin {
 978		if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
 979			return c.fail(protocol.ExitFailure, "%v", err)
 980		}
 981	} else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
 982		if errors.Is(err, store.ErrNotFound) {
 983			return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
 984		}
 985		return c.fail(protocol.ExitFailure, "%v", err)
 986	}
 987	return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
 988		fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
 989	})
 990}
 991
 992func runRepoBookmark(c *Ctx, args []string) int   { return setBookmarked(c, args, true) }
 993func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
 994
 995// setBookmarked mirrors setPinned. A bookmark needs only read access —
 996// bookmarking is something you do to someone else's repository, which is
 997// the whole point of it — and a private repository you cannot read is
 998// not found, as everywhere.
 999func setBookmarked(c *Ctx, args []string, on bool) int {
1000	verb := "bookmark"
1001	if !on {
1002		verb = "unbookmark"
1003	}
1004	if len(args) != 1 {
1005		return c.usage()
1006	}
1007	repo, code := resolveRepo(c, args[0], policy.CanRead)
1008	if code >= 0 {
1009		return code
1010	}
1011	if on {
1012		if err := c.Store.BookmarkRepo(c.User.ID, repo.ID); err != nil {
1013			return c.fail(protocol.ExitFailure, "%v", err)
1014		}
1015	} else if err := c.Store.UnbookmarkRepo(c.User.ID, repo.ID); err != nil {
1016		if errors.Is(err, store.ErrNotFound) {
1017			return c.fail(protocol.ExitNotFound, "%s is not bookmarked", repo.Path())
1018		}
1019		return c.fail(protocol.ExitFailure, "%v", err)
1020	}
1021	return c.emit(map[string]string{verb + "ed": repo.Path()}, func(w io.Writer) {
1022		fmt.Fprintf(w, "%sed %s\n", verb, repo.Path())
1023	})
1024}
1025
1026// BookmarkOut is one row of `repo bookmarks`: the repository and how many
1027// people have bookmarked it.
1028type BookmarkOut struct {
1029	Path        string `json:"path"`
1030	Description string `json:"description,omitempty"`
1031	Visibility  string `json:"visibility"`
1032	Bookmarks   int    `json:"bookmarks"`
1033}
1034
1035func runRepoBookmarks(c *Ctx, args []string) int {
1036	if len(args) != 0 {
1037		return c.usage()
1038	}
1039	repos, err := c.Store.ListBookmarks(c.User.ID)
1040	if err != nil {
1041		return c.fail(protocol.ExitFailure, "%v", err)
1042	}
1043	out := []BookmarkOut{}
1044	for _, r := range repos {
1045		// A repository bookmarked while public and since made private
1046		// stays in the table and drops out of the listing, the same way
1047		// it disappears from every other surface.
1048		grant, err := c.Store.AccessRole(r.ID, c.User.ID)
1049		if err != nil {
1050			return c.fail(protocol.ExitFailure, "%v", err)
1051		}
1052		if !policy.CanRead(c.User, r, grant) {
1053			continue
1054		}
1055		out = append(out, BookmarkOut{
1056			Path:        r.Path(),
1057			Description: gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)),
1058			Visibility:  r.Visibility,
1059			Bookmarks:   c.Store.BookmarkCount(r.ID),
1060		})
1061	}
1062	return c.emit(out, func(w io.Writer) {
1063		for _, b := range out {
1064			fmt.Fprintf(w, "%s\t%d\t%s\n", b.Path, b.Bookmarks, b.Description)
1065		}
1066	})
1067}
1068
1069func runProtectTag(c *Ctx, args []string) int   { return setProtectTag(c, args, true) }
1070func runUnprotectTag(c *Ctx, args []string) int { return setProtectTag(c, args, false) }
1071
1072func setProtectTag(c *Ctx, args []string, protect bool) int {
1073	if len(args) != 2 {
1074		return c.usage()
1075	}
1076	glob := args[1]
1077	if _, err := path.Match(glob, "x"); err != nil || glob == "" {
1078		return c.fail(protocol.ExitUsage, "bad glob %q", glob)
1079	}
1080	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1081	if code >= 0 {
1082		return code
1083	}
1084	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1085		has := slices.Contains(s.ProtectedTags, glob)
1086		if protect && !has {
1087			s.ProtectedTags = append(s.ProtectedTags, glob)
1088			slices.Sort(s.ProtectedTags)
1089		}
1090		if !protect && has {
1091			s.ProtectedTags = slices.DeleteFunc(s.ProtectedTags, func(g string) bool { return g == glob })
1092		}
1093	})
1094	if err != nil {
1095		return c.fail(protocol.ExitFailure, "%v", err)
1096	}
1097	verb := "protected"
1098	if !protect {
1099		verb = "unprotected"
1100	}
1101	return c.emit(s, func(w io.Writer) {
1102		fmt.Fprintf(w, "tags %s %s on %s\n", glob, verb, repo.Path())
1103	})
1104}
1105
1106func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
1107func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
1108
1109func setProtect(c *Ctx, args []string, protect bool) int {
1110	if len(args) != 2 {
1111		return c.usage()
1112	}
1113	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1114	if code >= 0 {
1115		return code
1116	}
1117	branch := args[1]
1118	// The list is read and rewritten inside the update, so two admins
1119	// protecting different branches at once both land.
1120	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1121		has := slices.Contains(s.ProtectedBranches, branch)
1122		if protect && !has {
1123			s.ProtectedBranches = append(s.ProtectedBranches, branch)
1124			slices.Sort(s.ProtectedBranches)
1125		}
1126		if !protect && has {
1127			s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
1128		}
1129	})
1130	if err != nil {
1131		return c.fail(protocol.ExitFailure, "%v", err)
1132	}
1133	verb := "protected"
1134	if !protect {
1135		verb = "unprotected"
1136	}
1137	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
1138}
1139
1140// runRepoDiff is the compare view's command: what head adds on top of
1141// base, measured from their merge base the way a merge request diff is,
1142// so a base that moved on does not show up as removals (#118).
1143func runRepoDiff(c *Ctx, args []string) int {
1144	f, err := parseFlags(args, flagSpec{MaxPos: 3, Usage: "repo diff <owner/name> <base> <head>"})
1145	if err != nil || len(f.Pos) != 3 {
1146		return c.usage()
1147	}
1148	repo, code := resolveRepo(c, f.pos(0), policy.CanRead)
1149	if code >= 0 {
1150		return code
1151	}
1152	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1153	base, err := gitutil.ResolveRef(dir, f.pos(1))
1154	if err != nil {
1155		return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(1), repo.Path())
1156	}
1157	head, err := gitutil.ResolveRef(dir, f.pos(2))
1158	if err != nil {
1159		return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(2), repo.Path())
1160	}
1161	mergeBase, err := gitutil.MergeBase(dir, base, head)
1162	if err != nil {
1163		return c.fail(protocol.ExitUsage, "%v", err)
1164	}
1165	patch, truncated, err := gitutil.Diff(dir, mergeBase, head, 4<<20)
1166	if err != nil {
1167		return c.fail(protocol.ExitFailure, "%v", err)
1168	}
1169	if c.JSON {
1170		return c.emit(map[string]any{"base": base, "head": head, "merge_base": mergeBase, "patch": patch, "truncated": truncated}, nil)
1171	}
1172	fmt.Fprint(c.Stdout, patch)
1173	if truncated {
1174		fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB")
1175	}
1176	return protocol.ExitOK
1177}