internal/control/repo.go
903 lines · 31334 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 f, err := parseFlags(args, flagSpec{Values: []string{"--description"}, Bools: []string{"--private"}, MaxPos: 1, Usage: "repo create <owner/name> [--private] [--description <text>]"})
150 if err != nil {
151 return c.fail(protocol.ExitUsage, "%v", err)
152 }
153 visibility, path, description := "public", f.pos(0), f.Value("--description")
154 if f.Has("--private") {
155 visibility = "private"
156 }
157 owner, name, ok := strings.Cut(path, "/")
158 if !ok {
159 return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
160 }
161 if err := policyValidateRepoName(name); err != nil {
162 return c.failErr(err)
163 }
164 ownerKind, ownerID := "user", c.User.ID
165 if owner != c.User.Username {
166 org, err := c.Store.OrgByName(owner)
167 if err != nil {
168 return c.fail(protocol.ExitDenied, "cannot create repositories under %q: not you and not an organization you can see", owner)
169 }
170 role, err := c.Store.OrgRole(org.ID, c.User.ID)
171 if err != nil {
172 return c.fail(protocol.ExitFailure, "%v", err)
173 }
174 if role != "admin" {
175 return c.fail(protocol.ExitDenied, "only admins of %s can create repositories there", owner)
176 }
177 ownerKind, ownerID = "org", org.ID
178 }
179 if ownerKind == "user" {
180 if code := checkRepoQuota(c); code >= 0 {
181 return code
182 }
183 }
184 id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
185 if err != nil {
186 return c.fail(protocol.ExitFailure, "%v", err)
187 }
188 dir := RepoDir(c.Cfg.Server.Root, owner, name)
189 if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
190 c.Store.DeleteRepo(id)
191 return c.fail(protocol.ExitFailure, "initializing repository: %v", err)
192 }
193 if description != "" {
194 if err := gitutil.WriteDescription(dir, description); err != nil {
195 return c.fail(protocol.ExitFailure, "writing description: %v", err)
196 }
197 }
198 type out struct {
199 Path string `json:"path"`
200 Visibility string `json:"visibility"`
201 SSHURL string `json:"ssh_url"`
202 }
203 d := out{Path: path, Visibility: visibility, SSHURL: "ssh://git@" + hostOf(c.Cfg.Server.SiteURL) + "/" + path + ".git"}
204 return c.emit(d, func(w io.Writer) {
205 fmt.Fprintf(w, "created %s (%s)\nclone: git clone %s\n", d.Path, d.Visibility, d.SSHURL)
206 })
207}
208
209func policyValidateRepoName(name string) error { return policy.ValidateName(name) }
210
211func hostOf(siteURL string) string {
212 s := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")
213 return strings.TrimSuffix(s, "/")
214}
215
216func runRepoList(c *Ctx, args []string) int {
217 args, p, code := parsePageFlags(c, args, "repo", false)
218 if code >= 0 {
219 return code
220 }
221 if len(args) != 0 {
222 return c.fail(protocol.ExitUsage, "usage: repo list [--limit <n>] [--cursor <c>]")
223 }
224 repos, err := c.Store.ListReposForUser(c.User.ID, p.queryLimit(), p.key)
225 if err != nil {
226 return c.fail(protocol.ExitFailure, "%v", err)
227 }
228 repos, next := trimPage(p, repos, "repo", store.Repo.Path)
229 type out struct {
230 Path string `json:"path"`
231 Visibility string `json:"visibility"`
232 Description string `json:"description,omitempty"`
233 Archived bool `json:"archived,omitempty"`
234 }
235 var ds []out
236 for _, r := range repos {
237 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
238 ds = append(ds, out{r.Path(), r.Visibility, desc, r.Settings.Archived})
239 }
240 return c.emitPage(p, ds, next, func(w io.Writer) {
241 for _, d := range ds {
242 mark := ""
243 if d.Archived {
244 mark = "\t[archived]"
245 }
246 fmt.Fprintf(w, "%s\t%s\t%s%s\n", d.Path, d.Visibility, d.Description, mark)
247 }
248 })
249}
250
251func runRepoShow(c *Ctx, args []string) int {
252 if len(args) != 1 {
253 return c.fail(protocol.ExitUsage, "usage: repo show <owner/name>")
254 }
255 repo, code := resolveRepo(c, args[0], policy.CanRead)
256 if code >= 0 {
257 return code
258 }
259 type mirrorOut struct {
260 Direction string `json:"direction"`
261 URL string `json:"url"`
262 Pending bool `json:"pending"`
263 LastSync string `json:"last_sync,omitempty"`
264 LastError string `json:"last_error,omitempty"`
265 }
266 type out struct {
267 Path string `json:"path"`
268 Description string `json:"description,omitempty"`
269 Website string `json:"website,omitempty"`
270 Visibility string `json:"visibility"`
271 DefaultBranch string `json:"default_branch"`
272 ProtectedBranches []string `json:"protected_branches,omitempty"`
273 Archived bool `json:"archived,omitempty"`
274 Topics []string `json:"topics,omitempty"`
275 Domains []string `json:"domains,omitempty"`
276 Mirrors []mirrorOut `json:"mirrors,omitempty"`
277 }
278 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name))
279 topics, err := c.Store.ListTopics(repo.ID)
280 if err != nil {
281 return c.fail(protocol.ExitFailure, "%v", err)
282 }
283 var domains []string
284 if ds, err := c.Store.ListPageDomains(repo.ID); err == nil {
285 for _, pd := range ds {
286 if pd.Verified() {
287 domains = append(domains, pd.Domain)
288 }
289 }
290 }
291 d := out{repo.Path(), desc, repo.Settings.Website, repo.Visibility, repo.DefaultBranch,
292 repo.Settings.ProtectedBranches, repo.Settings.Archived, topics, domains, nil}
293 // Mirror status is admin-only, like repo mirror list. The token never
294 // leaves the server.
295 if grant, err := c.Store.AccessRole(repo.ID, c.User.ID); err == nil && policy.CanAdmin(c.User, repo, grant) {
296 ms, err := c.Store.ListMirrors(repo.ID)
297 if err != nil {
298 return c.fail(protocol.ExitFailure, "%v", err)
299 }
300 for _, m := range ms {
301 d.Mirrors = append(d.Mirrors, mirrorOut{m.Direction, m.URL, m.Dirty, m.LastSync, m.LastError})
302 }
303 }
304 return c.emit(d, func(w io.Writer) {
305 line := fmt.Sprintf("%s\t%s\tdefault: %s", d.Path, d.Visibility, d.DefaultBranch)
306 if d.Archived {
307 line += "\t[archived]"
308 }
309 fmt.Fprintln(w, line)
310 if d.Description != "" {
311 fmt.Fprintf(w, "%s\n", d.Description)
312 }
313 if d.Website != "" {
314 fmt.Fprintf(w, "website: %s\n", d.Website)
315 }
316 if len(d.Topics) > 0 {
317 fmt.Fprintf(w, "topics: %s\n", strings.Join(d.Topics, ", "))
318 }
319 if len(d.ProtectedBranches) > 0 {
320 fmt.Fprintf(w, "protected: %s\n", strings.Join(d.ProtectedBranches, ", "))
321 }
322 if len(d.Domains) > 0 {
323 fmt.Fprintf(w, "pages domains: %s\n", strings.Join(d.Domains, ", "))
324 }
325 for _, m := range d.Mirrors {
326 status := "ok"
327 if m.Pending {
328 status = "pending"
329 }
330 if m.LastError != "" {
331 status = "error: " + m.LastError
332 }
333 fmt.Fprintf(w, "mirror: %s %s\tlast %s\t%s\n", m.Direction, m.URL, orDash(m.LastSync), status)
334 }
335 })
336}
337
338func runRepoTransfer(c *Ctx, args []string) int {
339 if len(args) != 2 {
340 return c.fail(protocol.ExitUsage, "usage: repo transfer <owner/name> <new-owner>")
341 }
342 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
343 if code >= 0 {
344 return code
345 }
346 newOwner := args[1]
347 if newOwner == repo.OwnerName {
348 return c.fail(protocol.ExitUsage, "%s already owns this repository", newOwner)
349 }
350
351 // Target: yourself, or an org you admin — same rule as repo create.
352 newKind, newID := "", int64(0)
353 if newOwner == c.User.Username {
354 newKind, newID = "user", c.User.ID
355 } else if org, err := c.Store.OrgByName(newOwner); err == nil {
356 role, err := c.Store.OrgRole(org.ID, c.User.ID)
357 if err != nil {
358 return c.fail(protocol.ExitFailure, "%v", err)
359 }
360 if role != "admin" {
361 return c.fail(protocol.ExitDenied, "only admins of %s can receive repositories there", newOwner)
362 }
363 newKind, newID = "org", org.ID
364 } else {
365 return c.fail(protocol.ExitDenied, "cannot transfer to %q: not you and not an organization you can see", newOwner)
366 }
367
368 oldDir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
369 newDir := RepoDir(c.Cfg.Server.Root, newOwner, repo.Name)
370 if _, err := os.Stat(newDir); err == nil {
371 return c.fail(protocol.ExitFailure, "repository directory already exists at %s/%s", newOwner, repo.Name)
372 }
373 if err := c.Store.TransferRepo(repo.ID, newKind, newID); err != nil {
374 return c.failErr(err)
375 }
376 if err := os.MkdirAll(filepath.Dir(newDir), 0o750); err != nil {
377 c.Store.TransferRepo(repo.ID, repo.OwnerKind, repo.OwnerID)
378 return c.fail(protocol.ExitFailure, "%v", err)
379 }
380 if err := os.Rename(oldDir, newDir); err != nil {
381 // Keep name and disk consistent: revert the database change.
382 c.Store.TransferRepo(repo.ID, repo.OwnerKind, repo.OwnerID)
383 return c.fail(protocol.ExitFailure, "moving repository: %v", err)
384 }
385 // The wiki companion follows its repo.
386 oldWiki := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name+".wiki")
387 if _, err := os.Stat(oldWiki); err == nil {
388 os.Rename(oldWiki, RepoDir(c.Cfg.Server.Root, newOwner, repo.Name+".wiki"))
389 }
390 newPath := newOwner + "/" + repo.Name
391 return c.emit(map[string]string{"repo": newPath, "was": repo.Path()}, func(w io.Writer) {
392 fmt.Fprintf(w, "transferred %s to %s — clone URLs now use %s\n", repo.Path(), newPath, newPath)
393 })
394}
395
396func runRepoDelete(c *Ctx, args []string) int {
397 var path string
398 var yes bool
399 for _, a := range args {
400 if a == "--yes" {
401 yes = true
402 } else if path == "" {
403 path = a
404 } else {
405 return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
406 }
407 }
408 if path == "" {
409 return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
410 }
411 repo, code := resolveRepo(c, path, policy.CanAdmin)
412 if code >= 0 {
413 return code
414 }
415 if !yes {
416 return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
417 }
418 return deleteRepo(c, repo)
419}
420
421// deleteRepo removes a repository the caller has already been cleared to
422// delete: the database row, then the directory and its wiki companion.
423func deleteRepo(c *Ctx, repo store.Repo) int {
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.failErr(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 return setRepoVisibility(c, repo, args[1])
578}
579
580// setRepoVisibility applies a visibility change the caller has already
581// been cleared to make.
582func setRepoVisibility(c *Ctx, repo store.Repo, visibility string) int {
583 if repo.Visibility == visibility {
584 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
585 fmt.Fprintf(w, "%s is already %s\n", repo.Path(), visibility)
586 })
587 }
588 if err := c.Store.SetRepoVisibility(repo.ID, visibility); err != nil {
589 return c.fail(protocol.ExitFailure, "%v", err)
590 }
591 // Going private takes the repository off every anonymous surface, so
592 // git:// exposure cannot outlive the change.
593 if visibility == "private" && repo.Settings.GitDaemon {
594 s := repo.Settings
595 s.GitDaemon = false
596 c.Store.SetRepoSettings(repo.ID, s)
597 }
598 c.Store.Audit(c.User.ID, "repo.visibility", map[string]any{"repo": repo.ID, "visibility": visibility})
599 return c.emit(map[string]string{"visibility": visibility}, func(w io.Writer) {
600 fmt.Fprintf(w, "%s is now %s\n", repo.Path(), visibility)
601 })
602}
603
604func runGitDaemon(c *Ctx, args []string) int {
605 if len(args) != 2 || (args[1] != "on" && args[1] != "off") {
606 return c.fail(protocol.ExitUsage, "usage: repo settings git-daemon <owner/name> on|off")
607 }
608 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
609 if code >= 0 {
610 return code
611 }
612 on := args[1] == "on"
613 if on && repo.Visibility != "public" {
614 return c.fail(protocol.ExitUsage, "git:// serves only public repositories; %s is private", repo.Path())
615 }
616 if on && !c.Cfg.GitDaemon.Enabled {
617 return c.fail(protocol.ExitUsage, "this instance does not run the git:// daemon ([git_daemon] enabled = false)")
618 }
619 s := repo.Settings
620 s.GitDaemon = on
621 if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
622 return c.fail(protocol.ExitFailure, "%v", err)
623 }
624 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "git-daemon %s on %s\n", args[1], repo.Path()) })
625}
626
627func runArchive(c *Ctx, args []string) int { return setArchived(c, args, true) }
628func runUnarchive(c *Ctx, args []string) int { return setArchived(c, args, false) }
629
630func setArchived(c *Ctx, args []string, archived bool) int {
631 verb := "archive"
632 if !archived {
633 verb = "unarchive"
634 }
635 if len(args) != 1 {
636 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
637 }
638 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
639 if code >= 0 {
640 return code
641 }
642 return archiveRepo(c, repo, archived)
643}
644
645// archiveRepo flips the archived flag on a repository the caller has
646// already been cleared to manage.
647func archiveRepo(c *Ctx, repo store.Repo, archived bool) int {
648 verb := "archive"
649 if !archived {
650 verb = "unarchive"
651 }
652 if repo.Settings.Archived == archived {
653 return c.fail(protocol.ExitUsage, "%s is already %sd", repo.Path(), verb)
654 }
655 s := repo.Settings
656 s.Archived = archived
657 if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
658 return c.fail(protocol.ExitFailure, "%v", err)
659 }
660 c.Store.RecordEvent(repo.ID, c.User.ID, "repo."+verb+"d", "{}")
661 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%sd %s\n", verb, repo.Path()) })
662}
663
664func runTopicsList(c *Ctx, args []string) int {
665 if len(args) != 1 {
666 return c.fail(protocol.ExitUsage, "usage: repo topics <owner/name>")
667 }
668 repo, code := resolveRepo(c, args[0], policy.CanRead)
669 if code >= 0 {
670 return code
671 }
672 topics, err := c.Store.ListTopics(repo.ID)
673 if err != nil {
674 return c.fail(protocol.ExitFailure, "%v", err)
675 }
676 return c.emit(topics, func(w io.Writer) {
677 for _, t := range topics {
678 fmt.Fprintln(w, t)
679 }
680 })
681}
682
683func runTopicsAdd(c *Ctx, args []string) int { return editTopics(c, args, true) }
684func runTopicsRemove(c *Ctx, args []string) int { return editTopics(c, args, false) }
685
686func editTopics(c *Ctx, args []string, add bool) int {
687 verb := "add"
688 if !add {
689 verb = "remove"
690 }
691 if len(args) < 2 {
692 return c.fail(protocol.ExitUsage, "usage: repo topics %s <owner/name> <topic>...", verb)
693 }
694 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
695 if code >= 0 {
696 return code
697 }
698 topics := args[1:]
699 if add {
700 for _, t := range topics {
701 if err := policy.ValidateTopic(t); err != nil {
702 return c.failErr(err)
703 }
704 }
705 have, err := c.Store.ListTopics(repo.ID)
706 if err != nil {
707 return c.fail(protocol.ExitFailure, "%v", err)
708 }
709 added := 0
710 for _, t := range topics {
711 if !slices.Contains(have, t) {
712 added++
713 }
714 }
715 if len(have)+added > policy.MaxTopics {
716 return c.fail(protocol.ExitUsage, "a repository can have at most %d topics", policy.MaxTopics)
717 }
718 for _, t := range topics {
719 if err := c.Store.AddTopic(repo.ID, t); err != nil {
720 return c.fail(protocol.ExitFailure, "%v", err)
721 }
722 }
723 } else {
724 for _, t := range topics {
725 if err := c.Store.RemoveTopic(repo.ID, t); err != nil {
726 if errors.Is(err, store.ErrNotFound) {
727 return c.fail(protocol.ExitNotFound, "%s has no topic %q", repo.Path(), t)
728 }
729 return c.fail(protocol.ExitFailure, "%v", err)
730 }
731 }
732 }
733 now, err := c.Store.ListTopics(repo.ID)
734 if err != nil {
735 return c.fail(protocol.ExitFailure, "%v", err)
736 }
737 return c.emit(now, func(w io.Writer) {
738 fmt.Fprintf(w, "topics on %s: %s\n", repo.Path(), strings.Join(now, ", "))
739 })
740}
741
742// runRepoSearch matches the query against name, owner/name, description,
743// and topics of every repository the caller can see.
744func runRepoSearch(c *Ctx, args []string) int {
745 if len(args) != 1 {
746 return c.fail(protocol.ExitUsage, "usage: repo search <query>")
747 }
748 if err := validQuery(args[0]); err != nil {
749 return c.failErr(err)
750 }
751 q := strings.ToLower(args[0])
752
753 public, err := c.Store.ListPublicRepos()
754 if err != nil {
755 return c.fail(protocol.ExitFailure, "%v", err)
756 }
757 own, err := c.Store.ListReposForUser(c.User.ID, 0, "")
758 if err != nil {
759 return c.fail(protocol.ExitFailure, "%v", err)
760 }
761 seen := map[int64]bool{}
762 type out struct {
763 Path string `json:"path"`
764 Visibility string `json:"visibility"`
765 Description string `json:"description,omitempty"`
766 Topics []string `json:"topics,omitempty"`
767 }
768 var ds []out
769 for _, r := range append(public, own...) {
770 if seen[r.ID] {
771 continue
772 }
773 seen[r.ID] = true
774 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
775 topics, _ := c.Store.ListTopics(r.ID)
776 if !matchesRepo(q, r, desc, topics) {
777 continue
778 }
779 ds = append(ds, out{r.Path(), r.Visibility, desc, topics})
780 }
781 return c.emit(ds, func(w io.Writer) {
782 for _, d := range ds {
783 fmt.Fprintf(w, "%s\t%s\t%s\n", d.Path, d.Visibility, d.Description)
784 }
785 })
786}
787
788func matchesRepo(q string, r store.Repo, desc string, topics []string) bool {
789 if strings.Contains(strings.ToLower(r.Path()), q) ||
790 strings.Contains(strings.ToLower(desc), q) {
791 return true
792 }
793 for _, t := range topics {
794 if strings.Contains(t, q) {
795 return true
796 }
797 }
798 return false
799}
800
801func runRepoGrep(c *Ctx, args []string) int {
802 f, err := parseFlags(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: "repo grep <owner/name> <query> [--ref <ref>]"})
803 if err != nil {
804 return c.fail(protocol.ExitUsage, "%v", err)
805 }
806 path, query, ref := f.pos(0), f.pos(1), f.Value("--ref")
807 if path == "" || query == "" {
808 return c.fail(protocol.ExitUsage, "usage: repo grep <owner/name> <query> [--ref <ref>]")
809 }
810 if err := validQuery(query); err != nil {
811 return c.failErr(err)
812 }
813 repo, code := resolveRepo(c, path, policy.CanRead)
814 if code >= 0 {
815 return code
816 }
817 if ref == "" {
818 ref = repo.DefaultBranch
819 }
820 dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
821 if _, err := gitutil.ResolveRef(dir, ref); err != nil {
822 return c.fail(protocol.ExitNotFound, "no ref %q in %s", ref, repo.Path())
823 }
824 matches, err := gitutil.Grep(dir, ref, query, maxGrepMatches)
825 if err != nil {
826 return c.fail(protocol.ExitFailure, "%v", err)
827 }
828 type out struct {
829 Path string `json:"path"`
830 Line int `json:"line"`
831 Text string `json:"text"`
832 }
833 var ds []out
834 for _, m := range matches {
835 ds = append(ds, out{m.Path, m.Line, m.Text})
836 }
837 return c.emit(ds, func(w io.Writer) {
838 for _, d := range ds {
839 fmt.Fprintf(w, "%s:%d:%s\n", d.Path, d.Line, d.Text)
840 }
841 })
842}
843
844func runRepoPin(c *Ctx, args []string) int { return setPinned(c, args, true) }
845func runRepoUnpin(c *Ctx, args []string) int { return setPinned(c, args, false) }
846
847func setPinned(c *Ctx, args []string, pin bool) int {
848 verb := "pin"
849 if !pin {
850 verb = "unpin"
851 }
852 if len(args) != 1 {
853 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
854 }
855 repo, code := resolveRepo(c, args[0], policy.CanRead)
856 if code >= 0 {
857 return code
858 }
859 if pin {
860 if err := c.Store.PinRepo(c.User.ID, repo.ID); err != nil {
861 return c.fail(protocol.ExitFailure, "%v", err)
862 }
863 } else if err := c.Store.UnpinRepo(c.User.ID, repo.ID); err != nil {
864 if errors.Is(err, store.ErrNotFound) {
865 return c.fail(protocol.ExitNotFound, "%s is not pinned", repo.Path())
866 }
867 return c.fail(protocol.ExitFailure, "%v", err)
868 }
869 return c.emit(map[string]string{verb + "ned": repo.Path()}, func(w io.Writer) {
870 fmt.Fprintf(w, "%sned %s\n", verb, repo.Path())
871 })
872}
873
874func runProtect(c *Ctx, args []string) int { return setProtect(c, args, true) }
875func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
876
877func setProtect(c *Ctx, args []string, protect bool) int {
878 if len(args) != 2 {
879 return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
880 }
881 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
882 if code >= 0 {
883 return code
884 }
885 branch := args[1]
886 s := repo.Settings
887 has := slices.Contains(s.ProtectedBranches, branch)
888 if protect && !has {
889 s.ProtectedBranches = append(s.ProtectedBranches, branch)
890 slices.Sort(s.ProtectedBranches)
891 }
892 if !protect && has {
893 s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
894 }
895 if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
896 return c.fail(protocol.ExitFailure, "%v", err)
897 }
898 verb := "protected"
899 if !protect {
900 verb = "unprotected"
901 }
902 return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
903}