internal/control/repo.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/control/repo.go

1549 lines · 54589 bytes

64 symbols in this file
   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 krz-labs"},
  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			"security ignore", strings.Join(repo.Settings.SecurityIgnore, ", "),
 848			"security exclude rules", strings.Join(repo.Settings.SecurityExcludeRules, ", "),
 849			"git daemon", strconv.FormatBool(repo.Settings.GitDaemon),
 850			"archived", strconv.FormatBool(repo.Settings.Archived),
 851		)
 852	}, func() screen {
 853		set := repo.Settings
 854		onOff := func(b bool) cell {
 855			if b {
 856				return cText("on")
 857			}
 858			return cMeta("off")
 859		}
 860		approvals := cMeta("off")
 861		if set.RequireApprovals > 0 {
 862			approvals = cText(strconv.Itoa(set.RequireApprovals))
 863		}
 864		list := func(xs []string) cell {
 865			if len(xs) == 0 {
 866				return cMeta("none")
 867			}
 868			return cText(strings.Join(xs, ", "))
 869		}
 870		mr := "on"
 871		if set.RequireMR {
 872			mr = "off"
 873		}
 874		s := screen{fields: []field{
 875			{"Repo", []cell{cLink(repo.Path(), c.siteURL(repo.Path())), cMeta("settings")}},
 876			{"Protected", []cell{list(set.ProtectedBranches)}},
 877			{"Protected tags", []cell{list(set.ProtectedTags)}},
 878			{"Require MR", []cell{onOff(set.RequireMR)}},
 879			{"Require checks", []cell{onOff(set.RequireChecks)}},
 880			{"Contexts", []cell{list(set.RequiredContexts)}},
 881			{"Approvals", []cell{approvals}},
 882			{"Resolved threads", []cell{onOff(set.RequireResolved)}},
 883			{"Code owners", []cell{onOff(set.RequireCodeowners)}},
 884			{"Signed commits", []cell{onOff(set.RequireSignedCommits)}},
 885			{"Secret scan", []cell{cText(leaks.Mode(set.SecretScan))}},
 886			{"Scan allows", []cell{list(set.SecretScanAllow)}},
 887			{"Scan ignores", []cell{list(set.SecurityIgnore)}},
 888			{"Rules off", []cell{list(set.SecurityExcludeRules)}},
 889			{"Git daemon", []cell{onOff(set.GitDaemon)}},
 890			{"Archived", []cell{onOff(set.Archived)}},
 891		}, actions: []action{
 892			{"Settings", []string{"repo", "settings", "protect", repo.Path(), "<branch>"}},
 893			{"Settings", []string{"repo", "settings", "require-mr", repo.Path(), mr}},
 894		}}
 895		if set.Website != "" {
 896			s.fields = append(s.fields, field{"Website", []cell{cText(set.Website)}})
 897		}
 898		return s
 899	})
 900}
 901
 902func runSetDescription(c *Ctx, args []string) int {
 903	if len(args) != 2 {
 904		return c.usage()
 905	}
 906	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 907	if code >= 0 {
 908		return code
 909	}
 910	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 911	if err := gitutil.WriteDescription(dir, args[1]); err != nil {
 912		return c.fail(protocol.ExitFailure, "%v", err)
 913	}
 914	return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
 915		fmt.Fprintf(w, "description set on %s\n", repo.Path())
 916	})
 917}
 918
 919func runSetDefaultBranch(c *Ctx, args []string) int {
 920	if len(args) != 2 {
 921		return c.usage()
 922	}
 923	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 924	if code >= 0 {
 925		return code
 926	}
 927	branch := args[1]
 928	if strings.HasPrefix(branch, "-") {
 929		return c.fail(protocol.ExitUsage, "a default branch may not start with '-'")
 930	}
 931	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 932	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+branch); err != nil {
 933		return c.fail(protocol.ExitFailure, "no branch named %q on %s", branch, repo.Path())
 934	}
 935	if err := gitutil.SetHead(dir, branch); err != nil {
 936		return c.fail(protocol.ExitFailure, "%v", err)
 937	}
 938	if err := c.Store.UpdateDefaultBranch(repo.ID, branch); err != nil {
 939		return c.fail(protocol.ExitFailure, "%v", err)
 940	}
 941	c.Store.RequestSymbolIndex(repo.ID, false)
 942	return c.emit(map[string]string{"default_branch": branch}, func(w io.Writer) {
 943		fmt.Fprintf(w, "default branch of %s is now %s\n", repo.Path(), branch)
 944	})
 945}
 946
 947func runSetWebsite(c *Ctx, args []string) int {
 948	if len(args) != 2 {
 949		return c.usage()
 950	}
 951	site := strings.TrimSpace(args[1])
 952	if err := validateWebsite(site); err != nil {
 953		return c.failInput(err)
 954	}
 955	if len(site) > 256 {
 956		return c.fail(protocol.ExitUsage, "website URL too long (max 256)")
 957	}
 958	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 959	if code >= 0 {
 960		return code
 961	}
 962	if _, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Website = site }); err != nil {
 963		return c.fail(protocol.ExitFailure, "%v", err)
 964	}
 965	return c.emit(map[string]string{"website": site}, func(w io.Writer) {
 966		if site == "" {
 967			fmt.Fprintf(w, "website cleared on %s\n", repo.Path())
 968		} else {
 969			fmt.Fprintf(w, "website set on %s\n", repo.Path())
 970		}
 971	})
 972}
 973
 974func runSetVisibility(c *Ctx, args []string) int {
 975	if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
 976		return c.usage()
 977	}
 978	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 979	if code >= 0 {
 980		return code
 981	}
 982	return setRepoVisibility(c, repo, args[1])
 983}
 984
 985// setRepoVisibility applies a visibility change the caller has already
 986// been cleared to make.
 987func setRepoVisibility(c *Ctx, repo store.Repo, visibility string) int {
 988	if repo.Visibility == visibility {
 989		return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
 990			fmt.Fprintf(w, "%s is already %s\n", repo.Path(), visibility)
 991		})
 992	}
 993	if err := c.Store.SetRepoVisibility(repo.ID, visibility); err != nil {
 994		return c.fail(protocol.ExitFailure, "%v", err)
 995	}
 996	// Going private takes the repository off every anonymous surface, so
 997	// git:// exposure cannot outlive the change.
 998	if visibility == "private" && repo.Settings.GitDaemon {
 999		c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = false })
1000	}
1001	c.Store.Audit(c.User.ID, "repo.visibility", map[string]any{"repo": repo.ID, "visibility": visibility})
1002	return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
1003		fmt.Fprintf(w, "%s is now %s\n", repo.Path(), visibility)
1004	})
1005}
1006
1007func runGitDaemon(c *Ctx, args []string) int {
1008	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
1009		return c.usage()
1010	}
1011	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1012	if code >= 0 {
1013		return code
1014	}
1015	on := args[1] == "on"
1016	if on && repo.Visibility != "public" {
1017		return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
1018	}
1019	if on && !c.Cfg.GitDaemon.Enabled {
1020		return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
1021	}
1022	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.GitDaemon = on })
1023	if err != nil {
1024		return c.fail(protocol.ExitFailure, "%v", err)
1025	}
1026	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
1027}
1028
1029func runArchive(c *Ctx, args []string) int   { return setArchived(c, args, true) }
1030func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
1031
1032func setArchived(c *Ctx, args []string, archived bool) int {
1033	if len(args) != 1 {
1034		return c.usage()
1035	}
1036	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1037	if code >= 0 {
1038		return code
1039	}
1040	return archiveRepo(c, repo, archived)
1041}
1042
1043// archiveRepo flips the archived flag on a repository the caller has
1044// already been cleared to manage.
1045func archiveRepo(c *Ctx, repo store.Repo, archived bool) int {
1046	verb := "archive"
1047	if !archived {
1048		verb = "unarchive"
1049	}
1050	if repo.Settings.Archived == archived {
1051		return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
1052	}
1053	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.Archived = archived })
1054	if err != nil {
1055		return c.fail(protocol.ExitFailure, "%v", err)
1056	}
1057	if archived {
1058		_ = c.Store.ClearMirrorsPending(repo.ID)
1059	}
1060	c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
1061	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
1062}
1063
1064// topicsScreen is a repository's topics at a terminal, after a read or
1065// an edit.
1066func topicsScreen(repo store.Repo, topics []string) screen {
1067	rows := make([]row, len(topics))
1068	for i, t := range topics {
1069		rows[i] = rowOf(cRef(t))
1070	}
1071	return listScreen("Topics", rows,
1072		action{"Edit", []string{"repo", "topics", "add", repo.Path(), "<topic>"}},
1073		action{"Edit", []string{"repo", "topics", "remove", repo.Path(), "<topic>"}},
1074	)
1075}
1076
1077func runTopicsList(c *Ctx, args []string) int {
1078	if len(args) != 1 {
1079		return c.usage()
1080	}
1081	repo, code := resolveRepo(c, args[0], policy.CanRead)
1082	if code >= 0 {
1083		return code
1084	}
1085	topics, err := c.Store.ListTopics(repo.ID)
1086	if err != nil {
1087		return c.fail(protocol.ExitFailure, "%v", err)
1088	}
1089	return c.emitView(topics, func(w io.Writer) {
1090		tb := c.table(w, "TOPIC")
1091		for _, t := range topics {
1092			tb.row(cRef(t))
1093		}
1094		tb.flush()
1095	}, func() screen {
1096		return topicsScreen(repo, topics)
1097	})
1098}
1099
1100func runTopicsAdd(c *Ctx, args []string) int    { return editTopics(c, args, true) }
1101func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
1102
1103func editTopics(c *Ctx, args []string, add bool) int {
1104	if len(args) < 2 {
1105		return c.usage()
1106	}
1107	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1108	if code >= 0 {
1109		return code
1110	}
1111	topics := args[1:]
1112	if add {
1113		for _, t := range topics {
1114			if err := policy.ValidateTopic(t); err != nil {
1115				return c.failInput(err)
1116			}
1117		}
1118		have, err := c.Store.ListTopics(repo.ID)
1119		if err != nil {
1120			return c.fail(protocol.ExitFailure, "%v", err)
1121		}
1122		added := 0
1123		for _, t := range topics {
1124			if !slices.Contains(have, t) {
1125				added++
1126			}
1127		}
1128		if len(have)+added > policy.MaxTopics {
1129			return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
1130		}
1131		for _, t := range topics {
1132			if err := c.Store.AddTopic(repo.ID, t); err != nil {
1133				return c.fail(protocol.ExitFailure, "%v", err)
1134			}
1135		}
1136	} else {
1137		for _, t := range topics {
1138			if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
1139				if errors.Is(err, store.ErrNotFound) {
1140					return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
1141				}
1142				return c.fail(protocol.ExitFailure, "%v", err)
1143			}
1144		}
1145	}
1146	now, err := c.Store.ListTopics(repo.ID)
1147	if err != nil {
1148		return c.fail(protocol.ExitFailure, "%v", err)
1149	}
1150	return c.emitView(now, func(w io.Writer) {
1151		tb := c.table(w, "TOPIC")
1152		for _, t := range now {
1153			tb.row(cRef(t))
1154		}
1155		tb.flush()
1156	}, func() screen {
1157		return topicsScreen(repo, now)
1158	})
1159}
1160
1161// runRepoSearch matches the query against name, owner/name, description,
1162// and topics of every repository the caller can see.
1163func runRepoSearch(c *Ctx, args []string) int {
1164	if len(args) != 1 {
1165		return c.usage()
1166	}
1167	if err := validQuery(args[0]); err != nil {
1168		return c.failInput(err)
1169	}
1170	q := strings.ToLower(args[0])
1171
1172	public, err := c.Store.ListPublicRepos()
1173	if err != nil {
1174		return c.fail(protocol.ExitFailure, "%v", err)
1175	}
1176	own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
1177	if err != nil {
1178		return c.fail(protocol.ExitFailure, "%v", err)
1179	}
1180	seen := map[int64]bool{}
1181	type out struct {
1182		Path        string   `json:"path"`
1183		Visibility  string   `json:"visibility"`
1184		Description string   `json:"description,omitempty"`
1185		Topics      []string `json:"topics,omitempty"`
1186	}
1187	var ds []out
1188	for _, r := range append(public, own...) {
1189		if seen[r.ID] {
1190			continue
1191		}
1192		seen[r.ID] = true
1193		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
1194		topics, _ := c.Store.ListTopics(r.ID)
1195		if !MatchesRepo(q, r.Path(), desc, topics) {
1196			continue
1197		}
1198		ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
1199	}
1200	return c.emitView(ds, func(w io.Writer) {
1201		tb := c.table(w, "PATH", "VISIBILITY", "DESCRIPTION")
1202		for _, d := range ds {
1203			tb.row(cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cFlex(d.Description))
1204		}
1205		tb.flush()
1206	}, func() screen {
1207		rows := make([]row, len(ds))
1208		for i, d := range ds {
1209			rows[i] = rowOf(cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility), cFlex(d.Description), cMeta(strings.Join(d.Topics, ", ")))
1210		}
1211		s := listScreen(fmt.Sprintf("Repositories matching %q", args[0]), rows)
1212		if len(ds) > 0 {
1213			s.actions = []action{{"Read", []string{"repo", "show", ds[0].Path}}}
1214		}
1215		return s
1216	})
1217}
1218
1219// MatchesRepo is the one rule for matching a repository against a text
1220// query: its path, its description, or any of its topics. The web's
1221// /explore filter and /search page call it too, so the three surfaces
1222// cannot answer the same query differently.
1223func MatchesRepo(q, path, desc string, topics []string) bool {
1224	q = strings.ToLower(q)
1225	if strings.Contains(strings.ToLower(path), q) ||
1226		strings.Contains(strings.ToLower(desc), q) {
1227		return true
1228	}
1229	for _, t := range topics {
1230		if strings.Contains(strings.ToLower(t), q) {
1231			return true
1232		}
1233	}
1234	return false
1235}
1236
1237func runRepoGrep(c *Ctx, args []string) int {
1238	f, err := c.parseArgs(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: "repo grep <owner/name> <query> [--ref <ref>]"})
1239	if err != nil {
1240		return c.fail(protocol.ExitUsage, "%v", err)
1241	}
1242	path, query, ref := f.pos(0), f.pos(1), f.Value("--ref")
1243	if path == "" || query == "" {
1244		return c.usage()
1245	}
1246	if err := validQuery(query); err != nil {
1247		return c.failInput(err)
1248	}
1249	repo, code := resolveRepo(c, path, policy.CanRead)
1250	if code >= 0 {
1251		return code
1252	}
1253	if ref == "" {
1254		ref = repo.DefaultBranch
1255	}
1256	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1257	if _, err := gitutil.ResolveRef(dir, ref); err != nil {
1258		return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
1259	}
1260	matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
1261	if err != nil {
1262		return c.fail(protocol.ExitFailure, "%v", err)
1263	}
1264	type out struct {
1265		Path string `json:"path"`
1266		Line int    `json:"line"`
1267		Text string `json:"text"`
1268	}
1269	var ds []out
1270	for _, m := range matches {
1271		ds = append(ds, out{m.Path, m.Line, m.Text})
1272	}
1273	return c.emit(ds, func(w io.Writer) {
1274		for _, d := range ds {
1275			fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
1276		}
1277	})
1278}
1279
1280func runRepoPin(c *Ctx, args []string) int   { return setPinned(c, args, true) }
1281func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
1282
1283func setPinned(c *Ctx, args []string, pin bool) int {
1284	return setRepoMark(c, args, pin, "pinned", "unpinned", c.Store.PinRepo, c.Store.UnpinRepo)
1285}
1286
1287// setRepoMark marks a repository the caller can read with mark, or clears
1288// it with unmark; done and undone are the words the output uses.
1289func setRepoMark(c *Ctx, args []string, on bool, done, undone string, mark, unmark func(userID, repoID int64) error) int {
1290	if len(args) != 1 {
1291		return c.usage()
1292	}
1293	repo, code := resolveRepo(c, args[0], policy.CanRead)
1294	if code >= 0 {
1295		return code
1296	}
1297	word := done
1298	if on {
1299		if err := mark(c.User.ID, repo.ID); err != nil {
1300			return c.fail(protocol.ExitFailure, "%v", err)
1301		}
1302	} else {
1303		word = undone
1304		if err := unmark(c.User.ID, repo.ID); err != nil {
1305			if errors.Is(err, store.ErrNotFound) {
1306				return c.fail(protocol.ExitNotFound, "%s is not %s", repo.Path(), done)
1307			}
1308			return c.fail(protocol.ExitFailure, "%v", err)
1309		}
1310	}
1311	return c.emit(map[string]string{word: repo.Path()}, func(w io.Writer) {
1312		fmt.Fprintf(w, "%s %s\n", word, repo.Path())
1313	})
1314}
1315
1316func runRepoBookmark(c *Ctx, args []string) int   { return setBookmarked(c, args, true) }
1317func runRepoUnbookmark(c *Ctx, args []string) int { return setBookmarked(c, args, false) }
1318
1319// A bookmark needs only read access — bookmarking is something you do to
1320// someone else's repository, which is the whole point of it — and a
1321// private repository you cannot read is not found, as everywhere.
1322func setBookmarked(c *Ctx, args []string, on bool) int {
1323	return setRepoMark(c, args, on, "bookmarked", "unbookmarked", c.Store.BookmarkRepo, c.Store.UnbookmarkRepo)
1324}
1325
1326// BookmarkOut is one row of `repo bookmarks`: the repository and how many
1327// people have bookmarked it.
1328type BookmarkOut struct {
1329	Path        string `json:"path"`
1330	Description string `json:"description,omitempty"`
1331	Visibility  string `json:"visibility"`
1332	Bookmarks   int    `json:"bookmarks"`
1333}
1334
1335func runRepoBookmarks(c *Ctx, args []string) int {
1336	if len(args) != 0 {
1337		return c.usage()
1338	}
1339	repos, err := c.Store.ListBookmarks(c.User.ID)
1340	if err != nil {
1341		return c.fail(protocol.ExitFailure, "%v", err)
1342	}
1343	out := []BookmarkOut{}
1344	for _, r := range repos {
1345		// A repository bookmarked while public and since made private
1346		// stays in the table and drops out of the listing, the same way
1347		// it disappears from every other surface.
1348		grant, err := c.Store.AccessRole(r.ID, c.User.ID)
1349		if err != nil {
1350			return c.fail(protocol.ExitFailure, "%v", err)
1351		}
1352		if !policy.CanRead(c.User, r, grant) {
1353			continue
1354		}
1355		out = append(out, BookmarkOut{
1356			Path:        r.Path(),
1357			Description: gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name)),
1358			Visibility:  r.Visibility,
1359			Bookmarks:   c.Store.BookmarkCount(r.ID),
1360		})
1361	}
1362	return c.emitView(out, func(w io.Writer) {
1363		tb := c.table(w, "PATH", "COUNT", "DESCRIPTION")
1364		for _, b := range out {
1365			tb.row(cRef(b.Path), cNum(int64(b.Bookmarks)), cFlex(b.Description))
1366		}
1367		tb.flush()
1368	}, func() screen {
1369		rows := make([]row, len(out))
1370		for i, b := range out {
1371			n := fmt.Sprintf("%d bookmarks", b.Bookmarks)
1372			if b.Bookmarks == 1 {
1373				n = "1 bookmark"
1374			}
1375			rows[i] = rowOf(cLink(b.Path, c.siteURL(b.Path)), cState(b.Visibility), cFlex(b.Description), cMeta(n))
1376		}
1377		s := listScreen("Bookmarks", rows)
1378		if len(out) > 0 {
1379			s.actions = []action{{"Read", []string{"repo", "show", out[0].Path}}}
1380		}
1381		return s
1382	})
1383}
1384
1385func runProtectTag(c *Ctx, args []string) int   { return setProtectTag(c, args, true) }
1386func runUnprotectTag(c *Ctx, args []string) int { return setProtectTag(c, args, false) }
1387
1388func setProtectTag(c *Ctx, args []string, protect bool) int {
1389	if len(args) != 2 {
1390		return c.usage()
1391	}
1392	glob := args[1]
1393	if _, err := path.Match(glob, "x"); err != nil || glob == "" {
1394		return c.fail(protocol.ExitUsage, "bad glob %q", glob)
1395	}
1396	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1397	if code >= 0 {
1398		return code
1399	}
1400	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1401		has := slices.Contains(s.ProtectedTags, glob)
1402		if protect && !has {
1403			s.ProtectedTags = append(s.ProtectedTags, glob)
1404			slices.Sort(s.ProtectedTags)
1405		}
1406		if !protect && has {
1407			s.ProtectedTags = slices.DeleteFunc(s.ProtectedTags, func(g string) bool { return g == glob })
1408		}
1409	})
1410	if err != nil {
1411		return c.fail(protocol.ExitFailure, "%v", err)
1412	}
1413	verb := "protected"
1414	if !protect {
1415		verb = "unprotected"
1416	}
1417	return c.emit(s, func(w io.Writer) {
1418		fmt.Fprintf(w, "tags %s %s on %s\n", glob, verb, repo.Path())
1419	})
1420}
1421
1422func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
1423func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
1424
1425func setProtect(c *Ctx, args []string, protect bool) int {
1426	if len(args) != 2 {
1427		return c.usage()
1428	}
1429	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
1430	if code >= 0 {
1431		return code
1432	}
1433	branch := args[1]
1434	// The list is read and rewritten inside the update, so two admins
1435	// protecting different branches at once both land.
1436	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) {
1437		has := slices.Contains(s.ProtectedBranches, branch)
1438		if protect && !has {
1439			s.ProtectedBranches = append(s.ProtectedBranches, branch)
1440			slices.Sort(s.ProtectedBranches)
1441		}
1442		if !protect && has {
1443			s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
1444		}
1445	})
1446	if err != nil {
1447		return c.fail(protocol.ExitFailure, "%v", err)
1448	}
1449	verb := "protected"
1450	if !protect {
1451		verb = "unprotected"
1452	}
1453	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
1454}
1455
1456// runRepoDiff is the compare view's command: what head adds on top of
1457// base, measured from their merge base the way a merge request diff is,
1458// so a base that moved on does not show up as removals (#118).
1459func runRepoDiff(c *Ctx, args []string) int {
1460	f, err := c.parseArgs(args, flagSpec{MaxPos: 3, Usage: "repo diff <owner/name> <base> <head>"})
1461	if err != nil || len(f.Pos) != 3 {
1462		return c.usage()
1463	}
1464	repo, code := resolveRepo(c, f.pos(0), policy.CanRead)
1465	if code >= 0 {
1466		return code
1467	}
1468	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
1469	base, err := gitutil.ResolveRef(dir, f.pos(1))
1470	if err != nil {
1471		return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(1), repo.Path())
1472	}
1473	head, err := gitutil.ResolveRef(dir, f.pos(2))
1474	if err != nil {
1475		return c.fail(protocol.ExitNotFound, "no ref %q in %s", f.pos(2), repo.Path())
1476	}
1477	mergeBase, err := gitutil.MergeBase(dir, base, head)
1478	if err != nil {
1479		return c.fail(protocol.ExitUsage, "%v", err)
1480	}
1481	patch, truncated, err := gitutil.Diff(dir, mergeBase, head, 4<<20)
1482	if err != nil {
1483		return c.fail(protocol.ExitFailure, "%v", err)
1484	}
1485	if c.JSON {
1486		return c.emit(map[string]any{"base": base, "head": head, "merge_base": mergeBase, "patch": patch, "truncated": truncated}, nil)
1487	}
1488	fmt.Fprint(c.Stdout, c.Term.diff(patch))
1489	if truncated {
1490		fmt.Fprintln(c.Stderr, "diff truncated at 4 MiB")
1491	}
1492	return protocol.ExitOK
1493}
1494
1495// repoShowScreen is repo show at a terminal: how to clone it, where the
1496// default branch stands, what is open, and the latest commits.
1497func repoShowScreen(c *Ctx, d repoShowOut, g repoGlance, mrs []store.MR, issues []store.Issue, commits []CommitOut) screen {
1498	s := screen{body: d.Description, format: "text"}
1499	name := []cell{cLink(d.Path, c.siteURL(d.Path)), cState(d.Visibility)}
1500	if d.Archived {
1501		name[1].s += ", archived"
1502	}
1503	s.fields = append(s.fields, field{"Repo", name})
1504	if g.clone != "" {
1505		s.fields = append(s.fields, field{"Clone", []cell{cText(g.clone)}})
1506	}
1507	head := []cell{cText(d.DefaultBranch)}
1508	if g.checks != "" {
1509		head = []cell{cText(d.DefaultBranch), cText(strings.TrimSuffix(g.checks, " on "+d.DefaultBranch))}
1510	}
1511	s.fields = append(s.fields, field{"Head", head})
1512	if g.release != "" {
1513		s.fields = append(s.fields, field{"Release", []cell{cText(g.release)}})
1514	}
1515	if len(d.Topics) > 0 {
1516		s.fields = append(s.fields, field{"Topics", []cell{cText(strings.Join(d.Topics, ", "))}})
1517	}
1518	if d.ForkOf != "" {
1519		s.fields = append(s.fields, field{"Fork of", []cell{cRef(d.ForkOf)}})
1520	}
1521	for _, m := range d.Mirrors {
1522		if m.LastError != "" {
1523			s.fields = append(s.fields, field{"Mirror", []cell{cGlyph("failed"), cText(m.Direction + " " + m.URL + ": " + m.LastError)}})
1524		}
1525	}
1526	if !c.Term.Links {
1527		s.fields = append(s.fields, field{"URL", []cell{cText(c.siteURL(d.Path))}})
1528	}
1529
1530	ms := section{title: "Open merge requests", n: g.mrsN, more: []string{"mr", "list", d.Path}}
1531	for _, m := range mrs {
1532		ms.rows = append(ms.rows, rowOf(cRef(fmt.Sprintf("!%d", m.Number)), cFlex(m.Title), cAge(m.UpdatedAt)))
1533	}
1534	is := section{title: "Open issues", n: g.issuesN, more: []string{"issue", "list", d.Path}}
1535	for _, i := range issues {
1536		is.rows = append(is.rows, rowOf(cRef(fmt.Sprintf("#%d", i.Number)), cFlex(i.Title), cAge(i.UpdatedAt)))
1537	}
1538	cs := section{title: "Recent commits", n: len(commits), more: []string{"repo", "log", d.Path}}
1539	for _, cm := range commits {
1540		cs.rows = append(cs.rows, rowOf(cRef(fmt.Sprintf("%.7s", cm.SHA)), cFlex(cm.Subject)))
1541	}
1542	s.sections = []section{ms, is, cs}
1543	s.actions = []action{
1544		{"Contribute", []string{"mr", "create", d.Path}},
1545		{"Contribute", []string{"issue", "create", d.Path}},
1546		{"Read", []string{"repo", "log", d.Path}},
1547	}
1548	return s
1549}