internal/control/repo.go

1539 lines · 54141 bytes

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