internal/control/repo.go

954 lines · 33895 bytes

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