internal/control/repo.go

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

901 lines · 30919 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", "pin"},
 94		Summary: "pin a repository to your dashboard",
 95		Usage:   "repo pin <owner/name>", Run: runRepoPin})
 96	register(Command{Path: []string{"repo", "unpin"},
 97		Summary: "unpin a repository",
 98		Usage:   "repo unpin <owner/name>", Run: runRepoUnpin})
 99}
100
101const (
102	minQueryLen    = 2
103	maxQueryLen    = 200
104	maxGrepMatches = 200
105)
106
107func validQuery(q string) error {
108	if len(q) < minQueryLen || len(q) > maxQueryLen {
109		return fmt.Errorf("query must be %d to %d characters", minQueryLen, maxQueryLen)
110	}
111	return nil
112}
113
114// refuseArchived blocks content writes (pushes are refused in the transport
115// layer) on archived repositories. Settings, access, and lifecycle commands
116// stay available so an archived repo can be managed and unarchived.
117func refuseArchived(c *Ctx, repo store.Repo) int {
118	if repo.Settings.Archived {
119		return c.fail(protocol.ExitDenied, "%s is archived and read-only", repo.Path())
120	}
121	return -1
122}
123
124// resolveRepo loads a repo and checks the given permission for c.User.
125func resolveRepo(c *Ctx, path string, check func(store.User, store.Repo, string) bool) (store.Repo, int) {
126	repo, err := c.Store.RepoByPath(path)
127	if err != nil {
128		if errors.Is(err, store.ErrNotFound) {
129			// Same message whether it doesn't exist or is invisible.
130			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
131		}
132		return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
133	}
134	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
135	if err != nil {
136		return repo, c.fail(protocol.ExitFailure, "checking access: %v", err)
137	}
138	if !check(c.User, repo, grant) {
139		if !policy.CanRead(c.User, repo, grant) {
140			// Invisible repos 404, per the enumeration rule.
141			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
142		}
143		return repo, c.fail(protocol.ExitDenied, "permission denied on %s", path)
144	}
145	return repo, -1
146}
147
148func runRepoCreate(c *Ctx, args []string) int {
149	visibility := "public"
150	var path, description string
151	for i := 0; i < len(args); i++ {
152		switch args[i] {
153		case "--private":
154			visibility = "private"
155		case "--description":
156			if i+1 >= len(args) {
157				return c.fail(protocol.ExitUsage, "--description requires a value")
158			}
159			description = args[i+1]
160			i++
161		default:
162			if path != "" {
163				return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private] [--description <text>]")
164			}
165			path = args[i]
166		}
167	}
168	owner, name, ok := strings.Cut(path, "/")
169	if !ok {
170		return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
171	}
172	if err := policyValidateRepoName(name); err != nil {
173		return c.fail(protocol.ExitUsage, "%v", err)
174	}
175	ownerKind, ownerID := "user", c.User.ID
176	if owner != c.User.Username {
177		org, err := c.Store.OrgByName(owner)
178		if err != nil {
179			return c.fail(protocol.ExitDenied, "cannot create repositories under %q: not you and not an organization you can see", owner)
180		}
181		role, err := c.Store.OrgRole(org.ID, c.User.ID)
182		if err != nil {
183			return c.fail(protocol.ExitFailure, "%v", err)
184		}
185		if role != "admin" {
186			return c.fail(protocol.ExitDenied, "only admins of %s can create repositories there", owner)
187		}
188		ownerKind, ownerID = "org", org.ID
189	}
190	id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
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.fail(protocol.ExitUsage, "%v", 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.
388		c.Store.TransferRepo(repo.ID, repo.OwnerKind, repo.OwnerID)
389		return c.fail(protocol.ExitFailure, "moving repository: %v", err)
390	}
391	// The wiki companion follows its repo.
392	oldWiki := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name+".wiki")
393	if _, err := os.Stat(oldWiki); err == nil {
394		os.Rename(oldWiki, RepoDir(c.Cfg.Server.Root, newOwner, repo.Name+".wiki"))
395	}
396	newPath := newOwner + "/" + repo.Name
397	return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
398		fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
399	})
400}
401
402func runRepoDelete(c *Ctx, args []string) int {
403	var path string
404	var yes bool
405	for _, a := range args {
406		if a == "--yes" {
407			yes = true
408		} else if path == "" {
409			path = a
410		} else {
411			return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
412		}
413	}
414	if path == "" {
415		return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
416	}
417	repo, code := resolveRepo(c, path, policy.CanAdmin)
418	if code >= 0 {
419		return code
420	}
421	if !yes {
422		return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
423	}
424	// Open MRs sourced from this repo keep working (targets own the
425	// objects) but must show that the source is gone.
426	if err := c.Store.MarkSourceGoneForRepo(repo.ID); err != nil {
427		return c.fail(protocol.ExitFailure, "%v", err)
428	}
429	if err := c.Store.DeleteRepo(repo.ID); err != nil {
430		return c.fail(protocol.ExitFailure, "%v", err)
431	}
432	if err := os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)); err != nil {
433		return c.fail(protocol.ExitFailure, "database row removed but disk cleanup failed: %v", err)
434	}
435	os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name+".wiki"))
436	return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
437		fmt.Fprintf(w, "deleted %s\n", repo.Path())
438	})
439}
440
441func runAccessGrant(c *Ctx, args []string) int {
442	if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
443		return c.fail(protocol.ExitUsage, "usage: repo access grant <owner/name> <user> read|write|admin")
444	}
445	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
446	if code >= 0 {
447		return code
448	}
449	target, err := c.Store.UserByUsername(args[1])
450	if err != nil {
451		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
452	}
453	if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
454		return c.fail(protocol.ExitFailure, "%v", err)
455	}
456	return c.emit(map[string]string{"granted": args[2], "user": target.Username},
457		func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
458}
459
460func runAccessRevoke(c *Ctx, args []string) int {
461	if len(args) != 2 {
462		return c.fail(protocol.ExitUsage, "usage: repo access revoke <owner/name> <user>")
463	}
464	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
465	if code >= 0 {
466		return code
467	}
468	target, err := c.Store.UserByUsername(args[1])
469	if err != nil {
470		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
471	}
472	if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
473		if errors.Is(err, store.ErrNotFound) {
474			return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
475		}
476		return c.fail(protocol.ExitFailure, "%v", err)
477	}
478	return c.emit(map[string]string{"revoked": target.Username},
479		func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
480}
481
482func runAccessList(c *Ctx, args []string) int {
483	if len(args) != 1 {
484		return c.fail(protocol.ExitUsage, "usage: repo access list <owner/name>")
485	}
486	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
487	if code >= 0 {
488		return code
489	}
490	entries, err := c.Store.ListAccess(repo.ID)
491	if err != nil {
492		return c.fail(protocol.ExitFailure, "%v", err)
493	}
494	type out struct {
495		User string `json:"user"`
496		Role string `json:"role"`
497	}
498	var ds []out
499	for _, e := range entries {
500		ds = append(ds, out{e.Username, e.Role})
501	}
502	return c.emit(ds, func(w io.Writer) {
503		for _, d := range ds {
504			fmt.Fprintf(w, "%s\t%s\n", d.User, d.Role)
505		}
506	})
507}
508
509func runSettingsShow(c *Ctx, args []string) int {
510	if len(args) != 1 {
511		return c.fail(protocol.ExitUsage, "usage: repo settings show <owner/name>")
512	}
513	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
514	if code >= 0 {
515		return code
516	}
517	return c.emit(repo.Settings, func(w io.Writer) {
518		fmt.Fprintf(w, "protected_branches: %s\nrequire_signed_commits: %v\ngit_daemon: %v\narchived: %v\n",
519			strings.Join(repo.Settings.ProtectedBranches, ", "), repo.Settings.RequireSignedCommits, repo.Settings.GitDaemon, repo.Settings.Archived)
520	})
521}
522
523func runSetDescription(c *Ctx, args []string) int {
524	if len(args) != 2 {
525		return c.fail(protocol.ExitUsage, "usage: repo settings description <owner/name> <text>")
526	}
527	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
528	if code >= 0 {
529		return code
530	}
531	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
532	if err := gitutil.WriteDescription(dir, args[1]); err != nil {
533		return c.fail(protocol.ExitFailure, "%v", err)
534	}
535	return c.emit(map[string]string{"description": gitutil.ReadDescription(dir)}, func(w io.Writer) {
536		fmt.Fprintf(w, "description set on %s\n", repo.Path())
537	})
538}
539
540func runSetWebsite(c *Ctx, args []string) int {
541	if len(args) != 2 {
542		return c.fail(protocol.ExitUsage, "usage: repo settings website <owner/name> <url>")
543	}
544	site := strings.TrimSpace(args[1])
545	if err := validateWebsite(site); err != nil {
546		return c.fail(protocol.ExitUsage, "%v", err)
547	}
548	if len(site) > 256 {
549		return c.fail(protocol.ExitUsage, "website URL too long (max 256)")
550	}
551	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
552	if code >= 0 {
553		return code
554	}
555	s := repo.Settings
556	s.Website = site
557	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
558		return c.fail(protocol.ExitFailure, "%v", err)
559	}
560	return c.emit(map[string]string{"website": site}, func(w io.Writer) {
561		if site == "" {
562			fmt.Fprintf(w, "website cleared on %s\n", repo.Path())
563		} else {
564			fmt.Fprintf(w, "website set on %s\n", repo.Path())
565		}
566	})
567}
568
569func runSetVisibility(c *Ctx, args []string) int {
570	if len(args) != 2 || (args[1] != "public" && args[1] != "private") {
571		return c.fail(protocol.ExitUsage, "usage: repo settings visibility <owner/name> public|private")
572	}
573	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
574	if code >= 0 {
575		return code
576	}
577	if repo.Visibility == args[1] {
578		return c.emit(map[string]string{"visibility": args[1]}, func(w io.Writer) {
579			fmt.Fprintf(w, "%s is already %s\n", repo.Path(), args[1])
580		})
581	}
582	if err := c.Store.SetRepoVisibility(repo.ID, args[1]); err != nil {
583		return c.fail(protocol.ExitFailure, "%v", err)
584	}
585	// Going private takes the repository off every anonymous surface, so
586	// git:// exposure cannot outlive the change.
587	if args[1] == "private" && repo.Settings.GitDaemon {
588		s := repo.Settings
589		s.GitDaemon = false
590		c.Store.SetRepoSettings(repo.ID, s)
591	}
592	c.Store.Audit(c.User.ID, "repo.visibility", map[string]any{"repo": repo.ID, "visibility": args[1]})
593	return c.emit(map[string]string{"visibility": args[1]}, func(w io.Writer) {
594		fmt.Fprintf(w, "%s is now %s\n", repo.Path(), args[1])
595	})
596}
597
598func runGitDaemon(c *Ctx, args []string) int {
599	if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
600		return c.fail(protocol.ExitUsage, "usage: repo settings git-daemon <owner/name> on|off")
601	}
602	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
603	if code >= 0 {
604		return code
605	}
606	on := args[1] == "on"
607	if on && repo.Visibility != "public" {
608		return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
609	}
610	if on && !c.Cfg.GitDaemon.Enabled {
611		return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
612	}
613	s := repo.Settings
614	s.GitDaemon = on
615	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
616		return c.fail(protocol.ExitFailure, "%v", err)
617	}
618	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
619}
620
621func runArchive(c *Ctx, args []string) int   { return setArchived(c, args, true) }
622func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
623
624func setArchived(c *Ctx, args []string, archived bool) int {
625	verb := "archive"
626	if !archived {
627		verb = "unarchive"
628	}
629	if len(args) != 1 {
630		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
631	}
632	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
633	if code >= 0 {
634		return code
635	}
636	if repo.Settings.Archived == archived {
637		return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
638	}
639	s := repo.Settings
640	s.Archived = archived
641	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
642		return c.fail(protocol.ExitFailure, "%v", err)
643	}
644	c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
645	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
646}
647
648func runTopicsList(c *Ctx, args []string) int {
649	if len(args) != 1 {
650		return c.fail(protocol.ExitUsage, "usage: repo topics <owner/name>")
651	}
652	repo, code := resolveRepo(c, args[0], policy.CanRead)
653	if code >= 0 {
654		return code
655	}
656	topics, err := c.Store.ListTopics(repo.ID)
657	if err != nil {
658		return c.fail(protocol.ExitFailure, "%v", err)
659	}
660	return c.emit(topics, func(w io.Writer) {
661		for _, t := range topics {
662			fmt.Fprintln(w, t)
663		}
664	})
665}
666
667func runTopicsAdd(c *Ctx, args []string) int    { return editTopics(c, args, true) }
668func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
669
670func editTopics(c *Ctx, args []string, add bool) int {
671	verb := "add"
672	if !add {
673		verb = "remove"
674	}
675	if len(args) < 2 {
676		return c.fail(protocol.ExitUsage, "usage: repo topics %s <owner/name> <topic>...", verb)
677	}
678	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
679	if code >= 0 {
680		return code
681	}
682	topics := args[1:]
683	if add {
684		for _, t := range topics {
685			if err := policy.ValidateTopic(t); err != nil {
686				return c.fail(protocol.ExitUsage, "%v", err)
687			}
688		}
689		have, err := c.Store.ListTopics(repo.ID)
690		if err != nil {
691			return c.fail(protocol.ExitFailure, "%v", err)
692		}
693		added := 0
694		for _, t := range topics {
695			if !slices.Contains(have, t) {
696				added++
697			}
698		}
699		if len(have)+added > policy.MaxTopics {
700			return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
701		}
702		for _, t := range topics {
703			if err := c.Store.AddTopic(repo.ID, t); err != nil {
704				return c.fail(protocol.ExitFailure, "%v", err)
705			}
706		}
707	} else {
708		for _, t := range topics {
709			if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
710				if errors.Is(err, store.ErrNotFound) {
711					return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
712				}
713				return c.fail(protocol.ExitFailure, "%v", err)
714			}
715		}
716	}
717	now, err := c.Store.ListTopics(repo.ID)
718	if err != nil {
719		return c.fail(protocol.ExitFailure, "%v", err)
720	}
721	return c.emit(now, func(w io.Writer) {
722		fmt.Fprintf(w, "topics on %s: %s\n", repo.Path(), strings.Join(now, ", "))
723	})
724}
725
726// runRepoSearch matches the query against name, owner/name, description,
727// and topics of every repository the caller can see.
728func runRepoSearch(c *Ctx, args []string) int {
729	if len(args) != 1 {
730		return c.fail(protocol.ExitUsage, "usage: repo search <query>")
731	}
732	if err := validQuery(args[0]); err != nil {
733		return c.fail(protocol.ExitUsage, "%v", err)
734	}
735	q := strings.ToLower(args[0])
736
737	public, err := c.Store.ListPublicRepos()
738	if err != nil {
739		return c.fail(protocol.ExitFailure, "%v", err)
740	}
741	own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
742	if err != nil {
743		return c.fail(protocol.ExitFailure, "%v", err)
744	}
745	seen := map[int64]bool{}
746	type out struct {
747		Path        string   `json:"path"`
748		Visibility  string   `json:"visibility"`
749		Description string   `json:"description,omitempty"`
750		Topics      []string `json:"topics,omitempty"`
751	}
752	var ds []out
753	for _, r := range append(public, own...) {
754		if seen[r.ID] {
755			continue
756		}
757		seen[r.ID] = true
758		desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
759		topics, _ := c.Store.ListTopics(r.ID)
760		if !matchesRepo(q, r, desc, topics) {
761			continue
762		}
763		ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
764	}
765	return c.emit(ds, func(w io.Writer) {
766		for _, d := range ds {
767			fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
768		}
769	})
770}
771
772func matchesRepo(q string, r store.Repo, desc string, topics []string) bool {
773	if strings.Contains(strings.ToLower(r.Path()), q) ||
774		strings.Contains(strings.ToLower(desc), q) {
775		return true
776	}
777	for _, t := range topics {
778		if strings.Contains(t, q) {
779			return true
780		}
781	}
782	return false
783}
784
785func runRepoGrep(c *Ctx, args []string) int {
786	var path, query, ref string
787	for i := 0; i < len(args); i++ {
788		switch args[i] {
789		case "--ref":
790			if i+1 >= len(args) {
791				return c.fail(protocol.ExitUsage, "--ref requires a value")
792			}
793			ref = args[i+1]
794			i++
795		default:
796			if path == "" {
797				path = args[i]
798			} else if query == "" {
799				query = args[i]
800			} else {
801				return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
802			}
803		}
804	}
805	if path == "" || query == "" {
806		return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
807	}
808	if err := validQuery(query); err != nil {
809		return c.fail(protocol.ExitUsage, "%v", err)
810	}
811	repo, code := resolveRepo(c, path, policy.CanRead)
812	if code >= 0 {
813		return code
814	}
815	if ref == "" {
816		ref = repo.DefaultBranch
817	}
818	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
819	if _, err := gitutil.ResolveRef(dir, ref); err != nil {
820		return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
821	}
822	matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
823	if err != nil {
824		return c.fail(protocol.ExitFailure, "%v", err)
825	}
826	type out struct {
827		Path string `json:"path"`
828		Line int    `json:"line"`
829		Text string `json:"text"`
830	}
831	var ds []out
832	for _, m := range matches {
833		ds = append(ds, out{m.Path, m.Line, m.Text})
834	}
835	return c.emit(ds, func(w io.Writer) {
836		for _, d := range ds {
837			fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
838		}
839	})
840}
841
842func runRepoPin(c *Ctx, args []string) int   { return setPinned(c, args, true) }
843func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
844
845func setPinned(c *Ctx, args []string, pin bool) int {
846	verb := "pin"
847	if !pin {
848		verb = "unpin"
849	}
850	if len(args) != 1 {
851		return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
852	}
853	repo, code := resolveRepo(c, args[0], policy.CanRead)
854	if code >= 0 {
855		return code
856	}
857	if pin {
858		if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
859			return c.fail(protocol.ExitFailure, "%v", err)
860		}
861	} else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
862		if errors.Is(err, store.ErrNotFound) {
863			return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
864		}
865		return c.fail(protocol.ExitFailure, "%v", err)
866	}
867	return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
868		fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
869	})
870}
871
872func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
873func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
874
875func setProtect(c *Ctx, args []string, protect bool) int {
876	if len(args) != 2 {
877		return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
878	}
879	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
880	if code >= 0 {
881		return code
882	}
883	branch := args[1]
884	s := repo.Settings
885	has := slices.Contains(s.ProtectedBranches, branch)
886	if protect && !has {
887		s.ProtectedBranches = append(s.ProtectedBranches, branch)
888		slices.Sort(s.ProtectedBranches)
889	}
890	if !protect && has {
891		s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
892	}
893	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
894		return c.fail(protocol.ExitFailure, "%v", err)
895	}
896	verb := "protected"
897	if !protect {
898		verb = "unprotected"
899	}
900	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
901}