internal/control/repo.go

d47a2ef73f46cfbc3083c56e041d79130ae9eb71
gitbay/internal/control/repo.go

311 lines · 10714 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"os"
  8	"path/filepath"
  9	"slices"
 10	"strings"
 11
 12	"github.com/krazywarez/forge/internal/gitutil"
 13	"github.com/krazywarez/forge/internal/policy"
 14	"github.com/krazywarez/forge/internal/protocol"
 15	"github.com/krazywarez/forge/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", Run: runRepoList})
 31	register(Command{Path: []string{"repo", "show"},
 32		Summary: "show repository details: repo show <owner/name>", Run: runRepoShow})
 33	register(Command{Path: []string{"repo", "delete"},
 34		Summary: "delete a repository: repo delete <owner/name> --yes", Run: runRepoDelete})
 35	register(Command{Path: []string{"repo", "access", "grant"},
 36		Summary: "grant access: repo access grant <owner/name> <user> read|write|admin", Run: runAccessGrant})
 37	register(Command{Path: []string{"repo", "access", "revoke"},
 38		Summary: "revoke access: repo access revoke <owner/name> <user>", Run: runAccessRevoke})
 39	register(Command{Path: []string{"repo", "access", "list"},
 40		Summary: "list access grants: repo access list <owner/name>", Run: runAccessList})
 41	register(Command{Path: []string{"repo", "settings", "show"},
 42		Summary: "show settings: repo settings show <owner/name>", Run: runSettingsShow})
 43	register(Command{Path: []string{"repo", "settings", "protect"},
 44		Summary: "protect a branch: repo settings protect <owner/name> <branch>", Run: runProtect})
 45	register(Command{Path: []string{"repo", "settings", "unprotect"},
 46		Summary: "unprotect a branch: repo settings unprotect <owner/name> <branch>", Run: runUnprotect})
 47}
 48
 49// resolveRepo loads a repo and checks the given permission for c.User.
 50func resolveRepo(c *Ctx, path string, check func(store.User, store.Repo, string) bool) (store.Repo, int) {
 51	repo, err := c.Store.RepoByPath(path)
 52	if err != nil {
 53		if errors.Is(err, store.ErrNotFound) {
 54			// Same message whether it doesn't exist or is invisible.
 55			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
 56		}
 57		return repo, c.fail(protocol.ExitFailure, "loading repository: %v", err)
 58	}
 59	grant, err := c.Store.AccessRole(repo.ID, c.User.ID)
 60	if err != nil {
 61		return repo, c.fail(protocol.ExitFailure, "checking access: %v", err)
 62	}
 63	if !check(c.User, repo, grant) {
 64		if !policy.CanRead(c.User, repo, grant) {
 65			// Invisible repos 404, per the enumeration rule.
 66			return repo, c.fail(protocol.ExitNotFound, "repository %s not found", path)
 67		}
 68		return repo, c.fail(protocol.ExitDenied, "permission denied on %s", path)
 69	}
 70	return repo, -1
 71}
 72
 73func runRepoCreate(c *Ctx, args []string) int {
 74	visibility := "public"
 75	var path string
 76	for _, a := range args {
 77		switch a {
 78		case "--private":
 79			visibility = "private"
 80		default:
 81			if path != "" {
 82				return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
 83			}
 84			path = a
 85		}
 86	}
 87	owner, name, ok := strings.Cut(path, "/")
 88	if !ok {
 89		return c.fail(protocol.ExitUsage, "usage: repo create <owner/name> [--private]")
 90	}
 91	if owner != c.User.Username {
 92		return c.fail(protocol.ExitDenied, "cannot create repositories under %q (orgs not yet supported)", owner)
 93	}
 94	if err := policyValidateRepoName(name); err != nil {
 95		return c.fail(protocol.ExitUsage, "%v", err)
 96	}
 97	id, err := c.Store.CreateRepo("user", c.User.ID, name, visibility)
 98	if err != nil {
 99		return c.fail(protocol.ExitFailure, "%v", err)
100	}
101	dir := RepoDir(c.Cfg.Server.Root, owner, name)
102	if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
103		c.Store.DeleteRepo(id)
104		return c.fail(protocol.ExitFailure, "initializing repository: %v", err)
105	}
106	type out struct {
107		Path       string `json:"path"`
108		Visibility string `json:"visibility"`
109		SSHURL     string `json:"ssh_url"`
110	}
111	d := out{Path: path, Visibility: visibility, SSHURL: "ssh://git@" + hostOf(c.Cfg.Server.SiteURL) + "/" + path + ".git"}
112	return c.emit(d, func(w io.Writer) {
113		fmt.Fprintf(w, "created %s (%s)\nclone: git clone %s\n", d.Path, d.Visibility, d.SSHURL)
114	})
115}
116
117func policyValidateRepoName(name string) error { return policy.ValidateName(name) }
118
119func hostOf(siteURL string) string {
120	s := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")
121	return strings.TrimSuffix(s, "/")
122}
123
124func runRepoList(c *Ctx, args []string) int {
125	repos, err := c.Store.ListReposForUser(c.User.ID)
126	if err != nil {
127		return c.fail(protocol.ExitFailure, "%v", err)
128	}
129	type out struct {
130		Path       string `json:"path"`
131		Visibility string `json:"visibility"`
132	}
133	var ds []out
134	for _, r := range repos {
135		ds = append(ds, out{r.Path(), r.Visibility})
136	}
137	return c.emit(ds, func(w io.Writer) {
138		for _, d := range ds {
139			fmt.Fprintf(w, "%s\t%s\n", d.Path, d.Visibility)
140		}
141	})
142}
143
144func runRepoShow(c *Ctx, args []string) int {
145	if len(args) != 1 {
146		return c.fail(protocol.ExitUsage, "usage: repo show <owner/name>")
147	}
148	repo, code := resolveRepo(c, args[0], policy.CanRead)
149	if code >= 0 {
150		return code
151	}
152	type out struct {
153		Path              string   `json:"path"`
154		Visibility        string   `json:"visibility"`
155		DefaultBranch     string   `json:"default_branch"`
156		ProtectedBranches []string `json:"protected_branches,omitempty"`
157	}
158	d := out{repo.Path(), repo.Visibility, repo.DefaultBranch, repo.Settings.ProtectedBranches}
159	return c.emit(d, func(w io.Writer) {
160		fmt.Fprintf(w, "%s\t%s\tdefault: %s\n", d.Path, d.Visibility, d.DefaultBranch)
161		if len(d.ProtectedBranches) > 0 {
162			fmt.Fprintf(w, "protected: %s\n", strings.Join(d.ProtectedBranches, ", "))
163		}
164	})
165}
166
167func runRepoDelete(c *Ctx, args []string) int {
168	var path string
169	var yes bool
170	for _, a := range args {
171		if a == "--yes" {
172			yes = true
173		} else if path == "" {
174			path = a
175		} else {
176			return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
177		}
178	}
179	if path == "" {
180		return c.fail(protocol.ExitUsage, "usage: repo delete <owner/name> --yes")
181	}
182	repo, code := resolveRepo(c, path, policy.CanAdmin)
183	if code >= 0 {
184		return code
185	}
186	if !yes {
187		return c.fail(protocol.ExitUsage, "repo delete is permanent; re-run with --yes")
188	}
189	if err := c.Store.DeleteRepo(repo.ID); err != nil {
190		return c.fail(protocol.ExitFailure, "%v", err)
191	}
192	if err := os.RemoveAll(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)); err != nil {
193		return c.fail(protocol.ExitFailure, "database row removed but disk cleanup failed: %v", err)
194	}
195	return c.emit(map[string]string{"deleted": repo.Path()}, func(w io.Writer) {
196		fmt.Fprintf(w, "deleted %s\n", repo.Path())
197	})
198}
199
200func runAccessGrant(c *Ctx, args []string) int {
201	if len(args) != 3 || !slices.Contains([]string{"read", "write", "admin"}, args[2]) {
202		return c.fail(protocol.ExitUsage, "usage: repo access grant <owner/name> <user> read|write|admin")
203	}
204	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
205	if code >= 0 {
206		return code
207	}
208	target, err := c.Store.UserByUsername(args[1])
209	if err != nil {
210		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
211	}
212	if err := c.Store.GrantAccess(repo.ID, target.ID, args[2]); err != nil {
213		return c.fail(protocol.ExitFailure, "%v", err)
214	}
215	return c.emit(map[string]string{"granted": args[2], "user": target.Username},
216		func(w io.Writer) { fmt.Fprintf(w, "granted %s to %s on %s\n", args[2], target.Username, repo.Path()) })
217}
218
219func runAccessRevoke(c *Ctx, args []string) int {
220	if len(args) != 2 {
221		return c.fail(protocol.ExitUsage, "usage: repo access revoke <owner/name> <user>")
222	}
223	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
224	if code >= 0 {
225		return code
226	}
227	target, err := c.Store.UserByUsername(args[1])
228	if err != nil {
229		return c.fail(protocol.ExitNotFound, "no such user %q", args[1])
230	}
231	if err := c.Store.RevokeAccess(repo.ID, target.ID); err != nil {
232		if errors.Is(err, store.ErrNotFound) {
233			return c.fail(protocol.ExitNotFound, "%s has no grant on %s", target.Username, repo.Path())
234		}
235		return c.fail(protocol.ExitFailure, "%v", err)
236	}
237	return c.emit(map[string]string{"revoked": target.Username},
238		func(w io.Writer) { fmt.Fprintf(w, "revoked %s on %s\n", target.Username, repo.Path()) })
239}
240
241func runAccessList(c *Ctx, args []string) int {
242	if len(args) != 1 {
243		return c.fail(protocol.ExitUsage, "usage: repo access list <owner/name>")
244	}
245	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
246	if code >= 0 {
247		return code
248	}
249	entries, err := c.Store.ListAccess(repo.ID)
250	if err != nil {
251		return c.fail(protocol.ExitFailure, "%v", err)
252	}
253	type out struct {
254		User string `json:"user"`
255		Role string `json:"role"`
256	}
257	var ds []out
258	for _, e := range entries {
259		ds = append(ds, out{e.Username, e.Role})
260	}
261	return c.emit(ds, func(w io.Writer) {
262		for _, d := range ds {
263			fmt.Fprintf(w, "%s\t%s\n", d.User, d.Role)
264		}
265	})
266}
267
268func runSettingsShow(c *Ctx, args []string) int {
269	if len(args) != 1 {
270		return c.fail(protocol.ExitUsage, "usage: repo settings show <owner/name>")
271	}
272	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
273	if code >= 0 {
274		return code
275	}
276	return c.emit(repo.Settings, func(w io.Writer) {
277		fmt.Fprintf(w, "protected_branches: %s\nrequire_signed_commits: %v\n",
278			strings.Join(repo.Settings.ProtectedBranches, ", "), repo.Settings.RequireSignedCommits)
279	})
280}
281
282func runProtect(c *Ctx, args []string) int   { return setProtect(c, args, true) }
283func runUnprotect(c *Ctx, args []string) int { return setProtect(c, args, false) }
284
285func setProtect(c *Ctx, args []string, protect bool) int {
286	if len(args) != 2 {
287		return c.fail(protocol.ExitUsage, "usage: repo settings protect|unprotect <owner/name> <branch>")
288	}
289	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
290	if code >= 0 {
291		return code
292	}
293	branch := args[1]
294	s := repo.Settings
295	has := slices.Contains(s.ProtectedBranches, branch)
296	if protect && !has {
297		s.ProtectedBranches = append(s.ProtectedBranches, branch)
298		slices.Sort(s.ProtectedBranches)
299	}
300	if !protect && has {
301		s.ProtectedBranches = slices.DeleteFunc(s.ProtectedBranches, func(b string) bool { return b == branch })
302	}
303	if err := c.Store.SetRepoSettings(repo.ID, s); err != nil {
304		return c.fail(protocol.ExitFailure, "%v", err)
305	}
306	verb := "protected"
307	if !protect {
308		verb = "unprotected"
309	}
310	return c.emit(s, func(w io.Writer) { fmt.Fprintf(w, "%s %s on %s\n", verb, branch, repo.Path()) })
311}