internal/control/repo.go

0d12684707ba92a7a5dcf9aee6077df1f8c17c9c
gitbay/internal/control/repo.go history · blame · raw

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