internal/control/repo.go

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

756 lines · 26076 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: repo create <owner/name> [--private]", Run: runRepoCreate})
 29	register(Command{Path: []string{"repo", "list"},
 30		Summary: "list repositories you own or can access", ReadOnly: true, Run: runRepoList})
 31	register(Command{Path: []string{"repo", "show"},
 32		Summary: "show repository details: repo show <owner/name>", ReadOnly: true, Run: runRepoShow})
 33	register(Command{Path: []string{"repo", "transfer"},
 34		Summary: "move a repository to another owner: repo transfer <owner/name> <new-owner> (clone URLs change)", Run: runRepoTransfer})
 35	register(Command{Path: []string{"repo", "delete"},
 36		Summary: "delete a repository: repo delete <owner/name> --yes", Run: runRepoDelete})
 37	register(Command{Path: []string{"repo", "access", "grant"},
 38		Summary: "grant access: repo access grant <owner/name> <user> read|write|admin", Run: runAccessGrant})
 39	register(Command{Path: []string{"repo", "access", "revoke"},
 40		Summary: "revoke access: repo access revoke <owner/name> <user>", Run: runAccessRevoke})
 41	register(Command{Path: []string{"repo", "access", "list"},
 42		Summary: "list access grants: repo access list <owner/name>", ReadOnly: true, Run: runAccessList})
 43	register(Command{Path: []string{"repo", "settings", "show"},
 44		Summary: "show settings: repo settings show <owner/name>", ReadOnly: true, Run: runSettingsShow})
 45	register(Command{Path: []string{"repo", "settings", "protect"},
 46		Summary: "protect a branch: repo settings protect <owner/name> <branch>", Run: runProtect})
 47	register(Command{Path: []string{"repo", "settings", "unprotect"},
 48		Summary: "unprotect a branch: repo settings unprotect <owner/name> <branch>", Run: runUnprotect})
 49	register(Command{Path: []string{"repo", "settings", "description"},
 50		Summary: "set the repository description: repo settings description <owner/name> <text> ('' clears)", Run: runSetDescription})
 51	register(Command{Path: []string{"repo", "settings", "git-daemon"},
 52		Summary: "expose over git://: repo settings git-daemon <owner/name> on|off", Run: runGitDaemon})
 53	register(Command{Path: []string{"repo", "archive"},
 54		Summary: "archive a repository (read-only: pushes and issue/MR writes refused): repo archive <owner/name>", Run: runArchive})
 55	register(Command{Path: []string{"repo", "unarchive"},
 56		Summary: "unarchive a repository: repo unarchive <owner/name>", Run: runUnarchive})
 57	register(Command{Path: []string{"repo", "topics"},
 58		Summary: "list topics: repo topics <owner/name>", ReadOnly: true, Run: runTopicsList})
 59	register(Command{Path: []string{"repo", "topics", "add"},
 60		Summary: "add topics: repo topics add <owner/name> <topic>...", Run: runTopicsAdd})
 61	register(Command{Path: []string{"repo", "topics", "remove"},
 62		Summary: "remove topics: repo topics remove <owner/name> <topic>...", Run: runTopicsRemove})
 63	register(Command{Path: []string{"repo", "search"},
 64		Summary: "find repositories by name, description, or topic: repo search <query>", ReadOnly: true, Run: runRepoSearch})
 65	register(Command{Path: []string{"repo", "grep"},
 66		Summary: "search file contents: repo grep <owner/name> <query> [--ref <ref>]", ReadOnly: true, Run: runRepoGrep})
 67	register(Command{Path: []string{"repo", "pin"},
 68		Summary: "pin a repository to your dashboard: repo pin <owner/name>", Run: runRepoPin})
 69	register(Command{Path: []string{"repo", "unpin"},
 70		Summary: "unpin a repository: repo unpin <owner/name>", Run: runRepoUnpin})
 71}
 72
 73const (
 74	minQueryLen    = 2
 75	maxQueryLen    = 200
 76	maxGrepMatches = 200
 77)
 78
 79func validQuery(q string) error {
 80	if len(q) < minQueryLen || len(q) > maxQueryLen {
 81		return fmt.Errorf("query must be %d to %d characters", minQueryLen, maxQueryLen)
 82	}
 83	return nil
 84}
 85
 86// refuseArchived blocks content writes (pushes are refused in the transport
 87// layer) on archived repositories. Settings, access, and lifecycle commands
 88// stay available so an archived repo can be managed and unarchived.
 89func refuseArchived(c *Ctx, repo store.Repo) int {
 90	if repo.Settings.Archived {
 91		return c.fail(protocol.ExitDenied, "%s is archived and read-only", repo.Path())
 92	}
 93	return -1
 94}
 95
 96// resolveRepo loads a repo and checks the given permission for c.User.
 97func resolveRepo(c *Ctx, path string, check func(store.User, store.Repo, string) bool) (store.Repo, int) {
 98	repo, err := c.Store.RepoByPath(path)
 99	if err != nil {
100		if errors.Is(err, store.ErrNotFound) {
101			// Same message whether it doesn't exist or is invisible.
102			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
103		}
104		return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
105	}
106	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
107	if err != nil {
108		return repo, c.fail(protocol.ExitFailure, "checking access: %v", err)
109	}
110	if !check(c.User, repo, grant) {
111		if !policy.CanRead(c.User, repo, grant) {
112			// Invisible repos 404, per the enumeration rule.
113			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
114		}
115		return repo, c.fail(protocol.ExitDenied, "permission denied on %s", path)
116	}
117	return repo, -1
118}
119
120func runRepoCreate(c *Ctx, args []string) int {
121	visibility := "public"
122	var path, description string
123	for i := 0; i < len(args); i++ {
124		switch args[i] {
125		case "--private":
126			visibility = "private"
127		case "--description":
128			if i+1 >= len(args) {
129				return c.fail(protocol.ExitUsage, "--description requires a value")
130			}
131			description = args[i+1]
132			i++
133		default:
134			if path != "" {
135				return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private] [--description <text>]")
136			}
137			path = args[i]
138		}
139	}
140	owner, name, ok := strings.Cut(path, "/")
141	if !ok {
142		return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
143	}
144	if err := policyValidateRepoName(name); err != nil {
145		return c.fail(protocol.ExitUsage, "%v", err)
146	}
147	ownerKind, ownerID := "user", c.User.ID
148	if owner != c.User.Username {
149		org, err := c.Store.OrgByName(owner)
150		if err != nil {
151			return c.fail(protocol.ExitDenied, "cannot create repositories under %q: not you and not an organization you can see", owner)
152		}
153		role, err := c.Store.OrgRole(org.ID, c.User.ID)
154		if err != nil {
155			return c.fail(protocol.ExitFailure, "%v", err)
156		}
157		if role != "admin" {
158			return c.fail(protocol.ExitDenied, "only admins of %s can create repositories there", owner)
159		}
160		ownerKind, ownerID = "org", org.ID
161	}
162	id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
163	if err != nil {
164		return c.fail(protocol.ExitFailure, "%v", err)
165	}
166	dir := RepoDir(c.Cfg.Server.Root, owner, name)
167	if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
168		c.Store.DeleteRepo(id)
169		return c.fail(protocol.ExitFailure, "initializing repository: %v", err)
170	}
171	if description != "" {
172		if err := gitutil.WriteDescription(dir, description); err != nil {
173			return c.fail(protocol.ExitFailure, "writing description: %v", err)
174		}
175	}
176	type out struct {
177		Path       string `json:"path"`
178		Visibility string `json:"visibility"`
179		SSHURL     string `json:"ssh_url"`
180	}
181	d := out{Path: path, Visibility: visibility, SSHURL: "ssh://git@" + hostOf(c.Cfg.Server.SiteURL) + "/" + path + ".git"}
182	return c.emit(d, func(w io.Writer) {
183		fmt.Fprintf(w, "created %s (%s)\nclone: git clone %s\n", d.Path, d.Visibility, d.SSHURL)
184	})
185}
186
187func policyValidateRepoName(name string) error { return policy.ValidateName(name) }
188
189func hostOf(siteURL string) string {
190	s := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")
191	return strings.TrimSuffix(s, "/")
192}
193
194func runRepoList(c *Ctx, args []string) int {
195	repos, err := c.Store.ListReposForUser(c.User.ID)
196	if err != nil {
197		return c.fail(protocol.ExitFailure, "%v", err)
198	}
199	type out struct {
200		Path        string `json:"path"`
201		Visibility  string `json:"visibility"`
202		Description string `json:"description,omitempty"`
203		Archived    bool   `json:"archived,omitempty"`
204	}
205	var ds []out
206	for _, r := range repos {
207		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
208		ds = append(ds, out{r.Path(), r.Visibility, desc, r.Settings.Archived})
209	}
210	return c.emit(ds, func(w io.Writer) {
211		for _, d := range ds {
212			mark := ""
213			if d.Archived {
214				mark = "\t[archived]"
215			}
216			fmt.Fprintf(w, "%s\t%s\t%s%s\n", d.Path, d.Visibility, d.Description, mark)
217		}
218	})
219}
220
221func runRepoShow(c *Ctx, args []string) int {
222	if len(args) != 1 {
223		return c.fail(protocol.ExitUsage, "usage: repo show <owner/name>")
224	}
225	repo, code := resolveRepo(c, args[0], policy.CanRead)
226	if code >= 0 {
227		return code
228	}
229	type out struct {
230		Path              string   `json:"path"`
231		Description       string   `json:"description,omitempty"`
232		Visibility        string   `json:"visibility"`
233		DefaultBranch     string   `json:"default_branch"`
234		ProtectedBranches []string `json:"protected_branches,omitempty"`
235		Archived          bool     `json:"archived,omitempty"`
236		Topics            []string `json:"topics,omitempty"`
237	}
238	desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name))
239	topics, err := c.Store.ListTopics(repo.ID)
240	if err != nil {
241		return c.fail(protocol.ExitFailure, "%v", err)
242	}
243	d := out{repo.Path(), desc, repo.Visibility, repo.DefaultBranch, repo.Settings.ProtectedBranches,
244		repo.Settings.Archived, topics}
245	return c.emit(d, func(w io.Writer) {
246		line := fmt.Sprintf("%s\t%s\tdefault: %s", d.Path, d.Visibility, d.DefaultBranch)
247		if d.Archived {
248			line += "\t[archived]"
249		}
250		fmt.Fprintln(w, line)
251		if d.Description != "" {
252			fmt.Fprintf(w, "%s\n", d.Description)
253		}
254		if len(d.Topics) > 0 {
255			fmt.Fprintf(w, "topics: %s\n", strings.Join(d.Topics, ", "))
256		}
257		if len(d.ProtectedBranches) > 0 {
258			fmt.Fprintf(w, "protected: %s\n", strings.Join(d.ProtectedBranches, ", "))
259		}
260	})
261}
262
263func runRepoTransfer(c *Ctx, args []string) int {
264	if len(args) != 2 {
265		return c.fail(protocol.ExitUsage, "usage: repo transfer <owner/name> <new-owner>")
266	}
267	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
268	if code >= 0 {
269		return code
270	}
271	newOwner := args[1]
272	if newOwner == repo.OwnerName {
273		return c.fail(protocol.ExitUsage, "%s already owns this repository", newOwner)
274	}
275
276	// Target: yourself, or an org you admin — same rule as repo create.
277	newKind, newID := "", int64(0)
278	if newOwner == c.User.Username {
279		newKind, newID = "user", c.User.ID
280	} else if org, err := c.Store.OrgByName(newOwner); err == nil {
281		role, err := c.Store.OrgRole(org.ID, c.User.ID)
282		if err != nil {
283			return c.fail(protocol.ExitFailure, "%v", err)
284		}
285		if role != "admin" {
286			return c.fail(protocol.ExitDenied, "only admins of %s can receive repositories there", newOwner)
287		}
288		newKind, newID = "org", org.ID
289	} else {
290		return c.fail(protocol.ExitDenied, "cannot transfer to %q: not you and not an organization you can see", newOwner)
291	}
292
293	oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
294	newDir := RepoDir(c.Cfg.Server.Root, newOwner, repo.Name)
295	if _, err := os.Stat(newDir); err == nil {
296		return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", newOwner, repo.Name)
297	}
298	if err := c.Store.TransferRepo(repo.ID, newKind, newID); err != nil {
299		return c.fail(protocol.ExitUsage, "%v", err)
300	}
301	if err := os.MkdirAll(filepath.Dir(newDir), 0o750); err != nil {
302		c.Store.TransferRepo(repo.ID, repo.OwnerKind, repo.OwnerID)
303		return c.fail(protocol.ExitFailure, "%v", err)
304	}
305	if err := os.Rename(oldDir, newDir); err != nil {
306		// Keep name and disk consistent: revert the database change.
307		c.Store.TransferRepo(repo.ID, repo.OwnerKind, repo.OwnerID)
308		return c.fail(protocol.ExitFailure, "moving repository: %v", err)
309	}
310	newPath := newOwner + "/" + repo.Name
311	return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
312		fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
313	})
314}
315
316func runRepoDelete(c *Ctx, args []string) int {
317	var path string
318	var yes bool
319	for _, a := range args {
320		if a == "--yes" {
321			yes = true
322		} else if path == "" {
323			path = a
324		} else {
325			return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
326		}
327	}
328	if path == "" {
329		return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
330	}
331	repo, code := resolveRepo(c, path, policy.CanAdmin)
332	if code >= 0 {
333		return code
334	}
335	if !yes {
336		return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
337	}
338	// Open MRs sourced from this repo keep working (targets own the
339	// objects) but must show that the source is gone.
340	if err := c.Store.MarkSourceGoneForRepo(repo.ID); err != nil {
341		return c.fail(protocol.ExitFailure, "%v", err)
342	}
343	if err := c.Store.DeleteRepo(repo.ID); err != nil {
344		return c.fail(protocol.ExitFailure, "%v", err)
345	}
346	if err := os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)); err != nil {
347		return c.fail(protocol.ExitFailure, "database row removed but disk cleanup failed: %v", err)
348	}
349	return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
350		fmt.Fprintf(w, "deleted %s\n", repo.Path())
351	})
352}
353
354func runAccessGrant(c *Ctx, args []string) int {
355	if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
356		return c.fail(protocol.ExitUsage, "usage: repo access grant <owner/name> <user> read|write|admin")
357	}
358	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
359	if code >= 0 {
360		return code
361	}
362	target, err := c.Store.UserByUsername(args[1])
363	if err != nil {
364		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
365	}
366	if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
367		return c.fail(protocol.ExitFailure, "%v", err)
368	}
369	return c.emit(map[string]string{"granted": args[2], "user": target.Username},
370		func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
371}
372
373func runAccessRevoke(c *Ctx, args []string) int {
374	if len(args) != 2 {
375		return c.fail(protocol.ExitUsage, "usage: repo access revoke <owner/name> <user>")
376	}
377	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
378	if code >= 0 {
379		return code
380	}
381	target, err := c.Store.UserByUsername(args[1])
382	if err != nil {
383		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
384	}
385	if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
386		if errors.Is(err, store.ErrNotFound) {
387			return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
388		}
389		return c.fail(protocol.ExitFailure, "%v", err)
390	}
391	return c.emit(map[string]string{"revoked": target.Username},
392		func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
393}
394
395func runAccessList(c *Ctx, args []string) int {
396	if len(args) != 1 {
397		return c.fail(protocol.ExitUsage, "usage: repo access list <owner/name>")
398	}
399	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
400	if code >= 0 {
401		return code
402	}
403	entries, err := c.Store.ListAccess(repo.ID)
404	if err != nil {
405		return c.fail(protocol.ExitFailure, "%v", err)
406	}
407	type out struct {
408		User string `json:"user"`
409		Role string `json:"role"`
410	}
411	var ds []out
412	for _, e := range entries {
413		ds = append(ds, out{e.Username, e.Role})
414	}
415	return c.emit(ds, func(w io.Writer) {
416		for _, d := range ds {
417			fmt.Fprintf(w, "%s\t%s\n", d.User, d.Role)
418		}
419	})
420}
421
422func runSettingsShow(c *Ctx, args []string) int {
423	if len(args) != 1 {
424		return c.fail(protocol.ExitUsage, "usage: repo settings show <owner/name>")
425	}
426	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
427	if code >= 0 {
428		return code
429	}
430	return c.emit(repo.Settings, func(w io.Writer) {
431		fmt.Fprintf(w, "protected_branches: %s\nrequire_signed_commits: %v\ngit_daemon: %v\narchived: %v\n",
432			strings.Join(repo.Settings.ProtectedBranches, ", "), repo.Settings.RequireSignedCommits, repo.Settings.GitDaemon, repo.Settings.Archived)
433	})
434}
435
436func runSetDescription(c *Ctx, args []string) int {
437	if len(args) != 2 {
438		return c.fail(protocol.ExitUsage, "usage: repo settings description <owner/name> <text>")
439	}
440	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
441	if code >= 0 {
442		return code
443	}
444	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
445	if err := gitutil.WriteDescription(dir, args[1]); err != nil {
446		return c.fail(protocol.ExitFailure, "%v", err)
447	}
448	return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
449		fmt.Fprintf(w, "description set on %s\n", repo.Path())
450	})
451}
452
453func runGitDaemon(c *Ctx, args []string) int {
454	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
455		return c.fail(protocol.ExitUsage, "usage: repo settings git-daemon <owner/name> on|off")
456	}
457	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
458	if code >= 0 {
459		return code
460	}
461	on := args[1] == "on"
462	if on && repo.Visibility != "public" {
463		return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
464	}
465	if on && !c.Cfg.GitDaemon.Enabled {
466		return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
467	}
468	s := repo.Settings
469	s.GitDaemon = on
470	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
471		return c.fail(protocol.ExitFailure, "%v", err)
472	}
473	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
474}
475
476func runArchive(c *Ctx, args []string) int   { return setArchived(c, args, true) }
477func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
478
479func setArchived(c *Ctx, args []string, archived bool) int {
480	verb := "archive"
481	if !archived {
482		verb = "unarchive"
483	}
484	if len(args) != 1 {
485		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
486	}
487	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
488	if code >= 0 {
489		return code
490	}
491	if repo.Settings.Archived == archived {
492		return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
493	}
494	s := repo.Settings
495	s.Archived = archived
496	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
497		return c.fail(protocol.ExitFailure, "%v", err)
498	}
499	c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
500	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
501}
502
503func runTopicsList(c *Ctx, args []string) int {
504	if len(args) != 1 {
505		return c.fail(protocol.ExitUsage, "usage: repo topics <owner/name>")
506	}
507	repo, code := resolveRepo(c, args[0], policy.CanRead)
508	if code >= 0 {
509		return code
510	}
511	topics, err := c.Store.ListTopics(repo.ID)
512	if err != nil {
513		return c.fail(protocol.ExitFailure, "%v", err)
514	}
515	return c.emit(topics, func(w io.Writer) {
516		for _, t := range topics {
517			fmt.Fprintln(w, t)
518		}
519	})
520}
521
522func runTopicsAdd(c *Ctx, args []string) int    { return editTopics(c, args, true) }
523func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
524
525func editTopics(c *Ctx, args []string, add bool) int {
526	verb := "add"
527	if !add {
528		verb = "remove"
529	}
530	if len(args) < 2 {
531		return c.fail(protocol.ExitUsage, "usage: repo topics %s <owner/name> <topic>...", verb)
532	}
533	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
534	if code >= 0 {
535		return code
536	}
537	topics := args[1:]
538	if add {
539		for _, t := range topics {
540			if err := policy.ValidateTopic(t); err != nil {
541				return c.fail(protocol.ExitUsage, "%v", err)
542			}
543		}
544		have, err := c.Store.ListTopics(repo.ID)
545		if err != nil {
546			return c.fail(protocol.ExitFailure, "%v", err)
547		}
548		added := 0
549		for _, t := range topics {
550			if !slices.Contains(have, t) {
551				added++
552			}
553		}
554		if len(have)+added > policy.MaxTopics {
555			return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
556		}
557		for _, t := range topics {
558			if err := c.Store.AddTopic(repo.ID, t); err != nil {
559				return c.fail(protocol.ExitFailure, "%v", err)
560			}
561		}
562	} else {
563		for _, t := range topics {
564			if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
565				if errors.Is(err, store.ErrNotFound) {
566					return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
567				}
568				return c.fail(protocol.ExitFailure, "%v", err)
569			}
570		}
571	}
572	now, err := c.Store.ListTopics(repo.ID)
573	if err != nil {
574		return c.fail(protocol.ExitFailure, "%v", err)
575	}
576	return c.emit(now, func(w io.Writer) {
577		fmt.Fprintf(w, "topics on %s: %s\n", repo.Path(), strings.Join(now, ", "))
578	})
579}
580
581// runRepoSearch matches the query against name, owner/name, description,
582// and topics of every repository the caller can see.
583func runRepoSearch(c *Ctx, args []string) int {
584	if len(args) != 1 {
585		return c.fail(protocol.ExitUsage, "usage: repo search <query>")
586	}
587	if err := validQuery(args[0]); err != nil {
588		return c.fail(protocol.ExitUsage, "%v", err)
589	}
590	q := strings.ToLower(args[0])
591
592	public, err := c.Store.ListPublicRepos()
593	if err != nil {
594		return c.fail(protocol.ExitFailure, "%v", err)
595	}
596	own, err := c.Store.ListReposForUser(c.User.ID)
597	if err != nil {
598		return c.fail(protocol.ExitFailure, "%v", err)
599	}
600	seen := map[int64]bool{}
601	type out struct {
602		Path        string   `json:"path"`
603		Visibility  string   `json:"visibility"`
604		Description string   `json:"description,omitempty"`
605		Topics      []string `json:"topics,omitempty"`
606	}
607	var ds []out
608	for _, r := range append(public, own...) {
609		if seen[r.ID] {
610			continue
611		}
612		seen[r.ID] = true
613		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
614		topics, _ := c.Store.ListTopics(r.ID)
615		if !matchesRepo(q, r, desc, topics) {
616			continue
617		}
618		ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
619	}
620	return c.emit(ds, func(w io.Writer) {
621		for _, d := range ds {
622			fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
623		}
624	})
625}
626
627func matchesRepo(q string, r store.Repo, desc string, topics []string) bool {
628	if strings.Contains(strings.ToLower(r.Path()), q) ||
629		strings.Contains(strings.ToLower(desc), q) {
630		return true
631	}
632	for _, t := range topics {
633		if strings.Contains(t, q) {
634			return true
635		}
636	}
637	return false
638}
639
640func runRepoGrep(c *Ctx, args []string) int {
641	var path, query, ref string
642	for i := 0; i < len(args); i++ {
643		switch args[i] {
644		case "--ref":
645			if i+1 >= len(args) {
646				return c.fail(protocol.ExitUsage, "--ref requires a value")
647			}
648			ref = args[i+1]
649			i++
650		default:
651			if path == "" {
652				path = args[i]
653			} else if query == "" {
654				query = args[i]
655			} else {
656				return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
657			}
658		}
659	}
660	if path == "" || query == "" {
661		return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
662	}
663	if err := validQuery(query); err != nil {
664		return c.fail(protocol.ExitUsage, "%v", err)
665	}
666	repo, code := resolveRepo(c, path, policy.CanRead)
667	if code >= 0 {
668		return code
669	}
670	if ref == "" {
671		ref = repo.DefaultBranch
672	}
673	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
674	if _, err := gitutil.ResolveRef(dir, ref); err != nil {
675		return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
676	}
677	matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
678	if err != nil {
679		return c.fail(protocol.ExitFailure, "%v", err)
680	}
681	type out struct {
682		Path string `json:"path"`
683		Line int    `json:"line"`
684		Text string `json:"text"`
685	}
686	var ds []out
687	for _, m := range matches {
688		ds = append(ds, out{m.Path, m.Line, m.Text})
689	}
690	return c.emit(ds, func(w io.Writer) {
691		for _, d := range ds {
692			fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
693		}
694	})
695}
696
697func runRepoPin(c *Ctx, args []string) int   { return setPinned(c, args, true) }
698func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
699
700func setPinned(c *Ctx, args []string, pin bool) int {
701	verb := "pin"
702	if !pin {
703		verb = "unpin"
704	}
705	if len(args) != 1 {
706		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
707	}
708	repo, code := resolveRepo(c, args[0], policy.CanRead)
709	if code >= 0 {
710		return code
711	}
712	if pin {
713		if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
714			return c.fail(protocol.ExitFailure, "%v", err)
715		}
716	} else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
717		if errors.Is(err, store.ErrNotFound) {
718			return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
719		}
720		return c.fail(protocol.ExitFailure, "%v", err)
721	}
722	return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
723		fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
724	})
725}
726
727func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
728func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
729
730func setProtect(c *Ctx, args []string, protect bool) int {
731	if len(args) != 2 {
732		return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
733	}
734	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
735	if code >= 0 {
736		return code
737	}
738	branch := args[1]
739	s := repo.Settings
740	has := slices.Contains(s.ProtectedBranches, branch)
741	if protect && !has {
742		s.ProtectedBranches = append(s.ProtectedBranches, branch)
743		slices.Sort(s.ProtectedBranches)
744	}
745	if !protect && has {
746		s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
747	}
748	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
749		return c.fail(protocol.ExitFailure, "%v", err)
750	}
751	verb := "protected"
752	if !protect {
753		verb = "unprotected"
754	}
755	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
756}