internal/control/repo.go

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

762 lines · 26394 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	// The wiki companion follows its repo.
311	oldWiki := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name+".wiki")
312	if _, err := os.Stat(oldWiki); err == nil {
313		os.Rename(oldWiki, RepoDir(c.Cfg.Server.Root, newOwner, repo.Name+".wiki"))
314	}
315	newPath := newOwner + "/" + repo.Name
316	return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
317		fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
318	})
319}
320
321func runRepoDelete(c *Ctx, args []string) int {
322	var path string
323	var yes bool
324	for _, a := range args {
325		if a == "--yes" {
326			yes = true
327		} else if path == "" {
328			path = a
329		} else {
330			return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
331		}
332	}
333	if path == "" {
334		return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
335	}
336	repo, code := resolveRepo(c, path, policy.CanAdmin)
337	if code >= 0 {
338		return code
339	}
340	if !yes {
341		return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
342	}
343	// Open MRs sourced from this repo keep working (targets own the
344	// objects) but must show that the source is gone.
345	if err := c.Store.MarkSourceGoneForRepo(repo.ID); err != nil {
346		return c.fail(protocol.ExitFailure, "%v", err)
347	}
348	if err := c.Store.DeleteRepo(repo.ID); err != nil {
349		return c.fail(protocol.ExitFailure, "%v", err)
350	}
351	if err := os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)); err != nil {
352		return c.fail(protocol.ExitFailure, "database row removed but disk cleanup failed: %v", err)
353	}
354	os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name+".wiki"))
355	return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
356		fmt.Fprintf(w, "deleted %s\n", repo.Path())
357	})
358}
359
360func runAccessGrant(c *Ctx, args []string) int {
361	if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
362		return c.fail(protocol.ExitUsage, "usage: repo access grant <owner/name> <user> read|write|admin")
363	}
364	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
365	if code >= 0 {
366		return code
367	}
368	target, err := c.Store.UserByUsername(args[1])
369	if err != nil {
370		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
371	}
372	if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
373		return c.fail(protocol.ExitFailure, "%v", err)
374	}
375	return c.emit(map[string]string{"granted": args[2], "user": target.Username},
376		func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
377}
378
379func runAccessRevoke(c *Ctx, args []string) int {
380	if len(args) != 2 {
381		return c.fail(protocol.ExitUsage, "usage: repo access revoke <owner/name> <user>")
382	}
383	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
384	if code >= 0 {
385		return code
386	}
387	target, err := c.Store.UserByUsername(args[1])
388	if err != nil {
389		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
390	}
391	if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
392		if errors.Is(err, store.ErrNotFound) {
393			return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
394		}
395		return c.fail(protocol.ExitFailure, "%v", err)
396	}
397	return c.emit(map[string]string{"revoked": target.Username},
398		func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
399}
400
401func runAccessList(c *Ctx, args []string) int {
402	if len(args) != 1 {
403		return c.fail(protocol.ExitUsage, "usage: repo access list <owner/name>")
404	}
405	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
406	if code >= 0 {
407		return code
408	}
409	entries, err := c.Store.ListAccess(repo.ID)
410	if err != nil {
411		return c.fail(protocol.ExitFailure, "%v", err)
412	}
413	type out struct {
414		User string `json:"user"`
415		Role string `json:"role"`
416	}
417	var ds []out
418	for _, e := range entries {
419		ds = append(ds, out{e.Username, e.Role})
420	}
421	return c.emit(ds, func(w io.Writer) {
422		for _, d := range ds {
423			fmt.Fprintf(w, "%s\t%s\n", d.User, d.Role)
424		}
425	})
426}
427
428func runSettingsShow(c *Ctx, args []string) int {
429	if len(args) != 1 {
430		return c.fail(protocol.ExitUsage, "usage: repo settings show <owner/name>")
431	}
432	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
433	if code >= 0 {
434		return code
435	}
436	return c.emit(repo.Settings, func(w io.Writer) {
437		fmt.Fprintf(w, "protected_branches: %s\nrequire_signed_commits: %v\ngit_daemon: %v\narchived: %v\n",
438			strings.Join(repo.Settings.ProtectedBranches, ", "), repo.Settings.RequireSignedCommits, repo.Settings.GitDaemon, repo.Settings.Archived)
439	})
440}
441
442func runSetDescription(c *Ctx, args []string) int {
443	if len(args) != 2 {
444		return c.fail(protocol.ExitUsage, "usage: repo settings description <owner/name> <text>")
445	}
446	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
447	if code >= 0 {
448		return code
449	}
450	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
451	if err := gitutil.WriteDescription(dir, args[1]); err != nil {
452		return c.fail(protocol.ExitFailure, "%v", err)
453	}
454	return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
455		fmt.Fprintf(w, "description set on %s\n", repo.Path())
456	})
457}
458
459func runGitDaemon(c *Ctx, args []string) int {
460	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
461		return c.fail(protocol.ExitUsage, "usage: repo settings git-daemon <owner/name> on|off")
462	}
463	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
464	if code >= 0 {
465		return code
466	}
467	on := args[1] == "on"
468	if on && repo.Visibility != "public" {
469		return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
470	}
471	if on && !c.Cfg.GitDaemon.Enabled {
472		return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
473	}
474	s := repo.Settings
475	s.GitDaemon = on
476	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
477		return c.fail(protocol.ExitFailure, "%v", err)
478	}
479	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
480}
481
482func runArchive(c *Ctx, args []string) int   { return setArchived(c, args, true) }
483func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
484
485func setArchived(c *Ctx, args []string, archived bool) int {
486	verb := "archive"
487	if !archived {
488		verb = "unarchive"
489	}
490	if len(args) != 1 {
491		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
492	}
493	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
494	if code >= 0 {
495		return code
496	}
497	if repo.Settings.Archived == archived {
498		return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
499	}
500	s := repo.Settings
501	s.Archived = archived
502	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
503		return c.fail(protocol.ExitFailure, "%v", err)
504	}
505	c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
506	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
507}
508
509func runTopicsList(c *Ctx, args []string) int {
510	if len(args) != 1 {
511		return c.fail(protocol.ExitUsage, "usage: repo topics <owner/name>")
512	}
513	repo, code := resolveRepo(c, args[0], policy.CanRead)
514	if code >= 0 {
515		return code
516	}
517	topics, err := c.Store.ListTopics(repo.ID)
518	if err != nil {
519		return c.fail(protocol.ExitFailure, "%v", err)
520	}
521	return c.emit(topics, func(w io.Writer) {
522		for _, t := range topics {
523			fmt.Fprintln(w, t)
524		}
525	})
526}
527
528func runTopicsAdd(c *Ctx, args []string) int    { return editTopics(c, args, true) }
529func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
530
531func editTopics(c *Ctx, args []string, add bool) int {
532	verb := "add"
533	if !add {
534		verb = "remove"
535	}
536	if len(args) < 2 {
537		return c.fail(protocol.ExitUsage, "usage: repo topics %s <owner/name> <topic>...", verb)
538	}
539	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
540	if code >= 0 {
541		return code
542	}
543	topics := args[1:]
544	if add {
545		for _, t := range topics {
546			if err := policy.ValidateTopic(t); err != nil {
547				return c.fail(protocol.ExitUsage, "%v", err)
548			}
549		}
550		have, err := c.Store.ListTopics(repo.ID)
551		if err != nil {
552			return c.fail(protocol.ExitFailure, "%v", err)
553		}
554		added := 0
555		for _, t := range topics {
556			if !slices.Contains(have, t) {
557				added++
558			}
559		}
560		if len(have)+added > policy.MaxTopics {
561			return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
562		}
563		for _, t := range topics {
564			if err := c.Store.AddTopic(repo.ID, t); err != nil {
565				return c.fail(protocol.ExitFailure, "%v", err)
566			}
567		}
568	} else {
569		for _, t := range topics {
570			if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
571				if errors.Is(err, store.ErrNotFound) {
572					return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
573				}
574				return c.fail(protocol.ExitFailure, "%v", err)
575			}
576		}
577	}
578	now, err := c.Store.ListTopics(repo.ID)
579	if err != nil {
580		return c.fail(protocol.ExitFailure, "%v", err)
581	}
582	return c.emit(now, func(w io.Writer) {
583		fmt.Fprintf(w, "topics on %s: %s\n", repo.Path(), strings.Join(now, ", "))
584	})
585}
586
587// runRepoSearch matches the query against name, owner/name, description,
588// and topics of every repository the caller can see.
589func runRepoSearch(c *Ctx, args []string) int {
590	if len(args) != 1 {
591		return c.fail(protocol.ExitUsage, "usage: repo search <query>")
592	}
593	if err := validQuery(args[0]); err != nil {
594		return c.fail(protocol.ExitUsage, "%v", err)
595	}
596	q := strings.ToLower(args[0])
597
598	public, err := c.Store.ListPublicRepos()
599	if err != nil {
600		return c.fail(protocol.ExitFailure, "%v", err)
601	}
602	own, err := c.Store.ListReposForUser(c.User.ID)
603	if err != nil {
604		return c.fail(protocol.ExitFailure, "%v", err)
605	}
606	seen := map[int64]bool{}
607	type out struct {
608		Path        string   `json:"path"`
609		Visibility  string   `json:"visibility"`
610		Description string   `json:"description,omitempty"`
611		Topics      []string `json:"topics,omitempty"`
612	}
613	var ds []out
614	for _, r := range append(public, own...) {
615		if seen[r.ID] {
616			continue
617		}
618		seen[r.ID] = true
619		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
620		topics, _ := c.Store.ListTopics(r.ID)
621		if !matchesRepo(q, r, desc, topics) {
622			continue
623		}
624		ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
625	}
626	return c.emit(ds, func(w io.Writer) {
627		for _, d := range ds {
628			fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
629		}
630	})
631}
632
633func matchesRepo(q string, r store.Repo, desc string, topics []string) bool {
634	if strings.Contains(strings.ToLower(r.Path()), q) ||
635		strings.Contains(strings.ToLower(desc), q) {
636		return true
637	}
638	for _, t := range topics {
639		if strings.Contains(t, q) {
640			return true
641		}
642	}
643	return false
644}
645
646func runRepoGrep(c *Ctx, args []string) int {
647	var path, query, ref string
648	for i := 0; i < len(args); i++ {
649		switch args[i] {
650		case "--ref":
651			if i+1 >= len(args) {
652				return c.fail(protocol.ExitUsage, "--ref requires a value")
653			}
654			ref = args[i+1]
655			i++
656		default:
657			if path == "" {
658				path = args[i]
659			} else if query == "" {
660				query = args[i]
661			} else {
662				return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
663			}
664		}
665	}
666	if path == "" || query == "" {
667		return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
668	}
669	if err := validQuery(query); err != nil {
670		return c.fail(protocol.ExitUsage, "%v", err)
671	}
672	repo, code := resolveRepo(c, path, policy.CanRead)
673	if code >= 0 {
674		return code
675	}
676	if ref == "" {
677		ref = repo.DefaultBranch
678	}
679	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
680	if _, err := gitutil.ResolveRef(dir, ref); err != nil {
681		return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
682	}
683	matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
684	if err != nil {
685		return c.fail(protocol.ExitFailure, "%v", err)
686	}
687	type out struct {
688		Path string `json:"path"`
689		Line int    `json:"line"`
690		Text string `json:"text"`
691	}
692	var ds []out
693	for _, m := range matches {
694		ds = append(ds, out{m.Path, m.Line, m.Text})
695	}
696	return c.emit(ds, func(w io.Writer) {
697		for _, d := range ds {
698			fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
699		}
700	})
701}
702
703func runRepoPin(c *Ctx, args []string) int   { return setPinned(c, args, true) }
704func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
705
706func setPinned(c *Ctx, args []string, pin bool) int {
707	verb := "pin"
708	if !pin {
709		verb = "unpin"
710	}
711	if len(args) != 1 {
712		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
713	}
714	repo, code := resolveRepo(c, args[0], policy.CanRead)
715	if code >= 0 {
716		return code
717	}
718	if pin {
719		if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
720			return c.fail(protocol.ExitFailure, "%v", err)
721		}
722	} else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
723		if errors.Is(err, store.ErrNotFound) {
724			return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
725		}
726		return c.fail(protocol.ExitFailure, "%v", err)
727	}
728	return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
729		fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
730	})
731}
732
733func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
734func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
735
736func setProtect(c *Ctx, args []string, protect bool) int {
737	if len(args) != 2 {
738		return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
739	}
740	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
741	if code >= 0 {
742		return code
743	}
744	branch := args[1]
745	s := repo.Settings
746	has := slices.Contains(s.ProtectedBranches, branch)
747	if protect && !has {
748		s.ProtectedBranches = append(s.ProtectedBranches, branch)
749		slices.Sort(s.ProtectedBranches)
750	}
751	if !protect && has {
752		s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
753	}
754	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
755		return c.fail(protocol.ExitFailure, "%v", err)
756	}
757	verb := "protected"
758	if !protect {
759		verb = "unprotected"
760	}
761	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
762}