internal/control/repo.go

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

1041 lines · 37009 bytes

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