internal/control/repo.go

273e9b95f8b87ee2be442c6bff6cbffbfd09cccf
gitbay/internal/control/repo.go

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