internal/store/repos.go
421 lines · 13518 bytes
1package store
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "strings"
10)
11
12type Repo struct {
13 ID int64
14 OwnerKind string // user | org
15 OwnerID int64
16 OwnerName string // resolved for display and disk paths
17 Name string
18 Visibility string // public | private
19 DefaultBranch string
20 ForkOf int64 // 0 when not a fork
21 Settings RepoSettings
22}
23
24type RepoSettings struct {
25 ProtectedBranches []string `json:"protected_branches,omitempty"`
26 RequireSignedCommits bool `json:"require_signed_commits,omitempty"`
27 RequireChecks bool `json:"require_checks,omitempty"`
28 RequireApprovals int `json:"require_approvals,omitempty"`
29 RequireResolved bool `json:"require_resolved,omitempty"`
30 RequireCodeowners bool `json:"require_codeowners,omitempty"`
31 RequireMR bool `json:"require_mr,omitempty"`
32 GitDaemon bool `json:"git_daemon,omitempty"`
33 Archived bool `json:"archived,omitempty"`
34 Website string `json:"website,omitempty"`
35}
36
37// Path returns the canonical owner/name form.
38func (r Repo) Path() string { return r.OwnerName + "/" + r.Name }
39
40func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error) {
41 res, err := s.DB.Exec(
42 "INSERT INTO repos (owner_kind, owner_id, name, visibility) VALUES (?, ?, ?, ?)",
43 ownerKind, ownerID, name, visibility)
44 if err != nil {
45 if isUniqueErr(err) {
46 return 0, fmt.Errorf("repository %q already exists", name)
47 }
48 return 0, err
49 }
50 return res.LastInsertId()
51}
52
53// repoSelect resolves the owner name from whichever table owns the repo.
54const repoSelect = `
55 SELECT r.id, r.owner_kind, r.owner_id, COALESCE(u.username, o.name),
56 r.name, r.visibility, r.default_branch, COALESCE(r.fork_of, 0), r.settings_json
57 FROM repos r
58 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
59 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id`
60
61func scanRepo(row interface{ Scan(...any) error }) (Repo, error) {
62 var r Repo
63 var settingsJSON string
64 err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &r.ForkOf, &settingsJSON)
65 if err != nil {
66 return r, err
67 }
68 if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
69 return r, fmt.Errorf("repo %d settings: %w", r.ID, err)
70 }
71 return r, nil
72}
73
74// RepoByPath resolves "owner/name"; the owner may be a user or an org.
75func (s *Store) RepoByPath(path string) (Repo, error) {
76 owner, name, ok := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(path, "/"), ".git"), "/")
77 if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
78 return Repo{}, fmt.Errorf("%w: repository path must be owner/name", ErrNotFound)
79 }
80 r, err := scanRepo(s.DB.QueryRow(
81 repoSelect+" WHERE COALESCE(u.username, o.name) = ? AND r.name = ?", owner, name))
82 if errors.Is(err, sql.ErrNoRows) {
83 return Repo{}, ErrNotFound
84 }
85 return r, err
86}
87
88// SetRepoVisibility switches a repository between public and private.
89func (s *Store) SetRepoVisibility(repoID int64, visibility string) error {
90 if visibility != "public" && visibility != "private" {
91 return fmt.Errorf("visibility must be public or private")
92 }
93 _, err := s.DB.Exec("UPDATE repos SET visibility = ? WHERE id = ?", visibility, repoID)
94 return err
95}
96
97// UpdateRepoSettings applies mutate to the repository's settings and
98// stores the result, returning what was stored.
99//
100// settings_json is one blob, so changing one field means writing all of
101// them. Callers used to read the struct off a Repo they had loaded
102// earlier, change a field and write the whole blob back, which loses the
103// other admin's change whenever two ran at once — last write wins over a
104// value it never read. The read and the write happen here instead, inside
105// one transaction, and BEGIN IMMEDIATE takes the write lock up front: a
106// second updater waits at the start rather than discovering the conflict
107// after it has already read a stale blob.
108func (s *Store) UpdateRepoSettings(repoID int64, mutate func(*RepoSettings)) (RepoSettings, error) {
109 ctx := context.Background()
110 var out RepoSettings
111 // The whole exchange must run on one connection for BEGIN to bracket
112 // it; the pool would otherwise be free to hand the statements out
113 // separately.
114 conn, err := s.DB.Conn(ctx)
115 if err != nil {
116 return out, err
117 }
118 defer conn.Close()
119 if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
120 return out, err
121 }
122 committed := false
123 defer func() {
124 if !committed {
125 conn.ExecContext(ctx, "ROLLBACK")
126 }
127 }()
128 var raw string
129 if err := conn.QueryRowContext(ctx,
130 "SELECT settings_json FROM repos WHERE id = ?", repoID).Scan(&raw); err != nil {
131 if errors.Is(err, sql.ErrNoRows) {
132 return out, ErrNotFound
133 }
134 return out, err
135 }
136 if raw != "" {
137 if err := json.Unmarshal([]byte(raw), &out); err != nil {
138 return out, err
139 }
140 }
141 mutate(&out)
142 next, err := json.Marshal(out)
143 if err != nil {
144 return out, err
145 }
146 if _, err := conn.ExecContext(ctx,
147 "UPDATE repos SET settings_json = ? WHERE id = ?", string(next), repoID); err != nil {
148 return out, err
149 }
150 if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil {
151 return out, err
152 }
153 committed = true
154 return out, nil
155}
156
157// CreateFork is CreateRepo with fork_of set in the same insert, so a fork
158// never exists for a moment as a plain repository (#108).
159func (s *Store) CreateFork(ownerKind string, ownerID int64, name, visibility string, forkOf int64) (int64, error) {
160 res, err := s.DB.Exec(
161 "INSERT INTO repos (owner_kind, owner_id, name, visibility, fork_of) VALUES (?, ?, ?, ?, ?)",
162 ownerKind, ownerID, name, visibility, forkOf)
163 if err != nil {
164 if isUniqueErr(err) {
165 return 0, fmt.Errorf("repository %q already exists", name)
166 }
167 return 0, err
168 }
169 return res.LastInsertId()
170}
171
172func (s *Store) SetForkOf(repoID, parentID int64) error {
173 _, err := s.DB.Exec("UPDATE repos SET fork_of = ? WHERE id = ?", parentID, repoID)
174 return err
175}
176
177func (s *Store) DeleteRepo(repoID int64) error {
178 res, err := s.DB.Exec("DELETE FROM repos WHERE id = ?", repoID)
179 if err != nil {
180 return err
181 }
182 if n, _ := res.RowsAffected(); n == 0 {
183 return ErrNotFound
184 }
185 return nil
186}
187
188// ListReposForUser returns repos the user owns, reaches through an org
189// (unless the org scopes members to 'none'), has an explicit grant on, or
190// reaches through a team. limit 0 means everything; after (an owner/name
191// path) starts the page strictly beyond it, matching the path-ascending
192// order.
193func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo, error) {
194 q := repoSelect + `
195 LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
196 LEFT JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
197 LEFT JOIN orgs og ON r.owner_kind = 'org' AND og.id = r.owner_id
198 WHERE ((r.owner_kind = 'user' AND r.owner_id = ?)
199 OR a.subject_id IS NOT NULL
200 OR (m.user_id IS NOT NULL AND (m.role = 'admin' OR og.members_role <> 'none'))
201 OR EXISTS (SELECT 1 FROM team_repos tr
202 JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
203 WHERE tr.repo_id = r.id))`
204 args := []any{userID, userID, userID, userID}
205 if after != "" {
206 owner, name, _ := strings.Cut(after, "/")
207 q += ` AND (COALESCE(u.username, o.name) > ?
208 OR (COALESCE(u.username, o.name) = ? AND r.name > ?))`
209 args = append(args, owner, owner, name)
210 }
211 q += `
212 GROUP BY r.id
213 ORDER BY 4, r.name`
214 if limit > 0 {
215 q += " LIMIT ?"
216 args = append(args, limit)
217 }
218 rows, err := s.DB.Query(q, args...)
219 if err != nil {
220 return nil, err
221 }
222 defer rows.Close()
223 var out []Repo
224 for rows.Next() {
225 r, err := scanRepo(rows)
226 if err != nil {
227 return nil, err
228 }
229 out = append(out, r)
230 }
231 return out, rows.Err()
232}
233
234// AccessRole returns the user's effective role on the repo ("" if none):
235// the strongest of any explicit grant, the role derived from org
236// membership (org admin -> admin; plain member -> the org's members_role,
237// 'write' by default so the pre-teams model is the degenerate case), and
238// any team grants on the repo.
239func (s *Store) AccessRole(repoID, userID int64) (string, error) {
240 rank := map[string]int{"": 0, "none": 0, "read": 1, "write": 2, "admin": 3}
241 best := ""
242 better := func(role string) {
243 if rank[role] > rank[best] {
244 best = role
245 }
246 }
247
248 var explicit string
249 err := s.DB.QueryRow(
250 "SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
251 repoID, userID).Scan(&explicit)
252 if err != nil && !errors.Is(err, sql.ErrNoRows) {
253 return "", err
254 }
255 better(explicit)
256
257 var orgRole, membersRole string
258 err = s.DB.QueryRow(`
259 SELECT m.role, o.members_role FROM repos r
260 JOIN org_members m ON r.owner_kind = 'org' AND m.org_id = r.owner_id AND m.user_id = ?
261 JOIN orgs o ON o.id = r.owner_id
262 WHERE r.id = ?`, userID, repoID).Scan(&orgRole, &membersRole)
263 if err != nil && !errors.Is(err, sql.ErrNoRows) {
264 return "", err
265 }
266 if orgRole == "admin" {
267 better("admin")
268 } else if orgRole == "member" {
269 better(membersRole) // write | read | none
270 }
271
272 var teamRole string
273 err = s.DB.QueryRow(`
274 SELECT tr.role FROM team_repos tr
275 JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?
276 WHERE tr.repo_id = ?
277 ORDER BY CASE tr.role WHEN 'admin' THEN 3 WHEN 'write' THEN 2 ELSE 1 END DESC
278 LIMIT 1`, userID, repoID).Scan(&teamRole)
279 if err != nil && !errors.Is(err, sql.ErrNoRows) {
280 return "", err
281 }
282 better(teamRole)
283 return best, nil
284}
285
286func (s *Store) GrantAccess(repoID, userID int64, role string) error {
287 _, err := s.DB.Exec(`
288 INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
289 ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
290 repoID, userID, role)
291 return err
292}
293
294func (s *Store) RevokeAccess(repoID, userID int64) error {
295 res, err := s.DB.Exec(
296 "DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
297 repoID, userID)
298 if err != nil {
299 return err
300 }
301 if n, _ := res.RowsAffected(); n == 0 {
302 return ErrNotFound
303 }
304 return nil
305}
306
307type AccessEntry struct {
308 Username string
309 Role string
310}
311
312func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error) {
313 rows, err := s.DB.Query(`
314 SELECT u.username, a.role FROM repo_access a
315 JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id
316 WHERE a.repo_id = ? ORDER BY u.username`, repoID)
317 if err != nil {
318 return nil, err
319 }
320 defer rows.Close()
321 var out []AccessEntry
322 for rows.Next() {
323 var e AccessEntry
324 if err := rows.Scan(&e.Username, &e.Role); err != nil {
325 return nil, err
326 }
327 out = append(out, e)
328 }
329 return out, rows.Err()
330}
331
332func (s *Store) RepoByID(id int64) (Repo, error) {
333 r, err := scanRepo(s.DB.QueryRow(repoSelect+" WHERE r.id = ?", id))
334 if errors.Is(err, sql.ErrNoRows) {
335 return Repo{}, ErrNotFound
336 }
337 return r, err
338}
339
340// ListPublicRepos returns all public repositories, for the anonymous index.
341func (s *Store) ListPublicRepos() ([]Repo, error) {
342 rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name")
343 if err != nil {
344 return nil, err
345 }
346 defer rows.Close()
347 var out []Repo
348 for rows.Next() {
349 r, err := scanRepo(rows)
350 if err != nil {
351 return nil, err
352 }
353 out = append(out, r)
354 }
355 return out, rows.Err()
356}
357
358// ListForks returns the repositories forked from one repo. The caller
359// filters by what the viewer may see.
360func (s *Store) ListForks(repoID int64) ([]Repo, error) {
361 rows, err := s.DB.Query(repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID)
362 if err != nil {
363 return nil, err
364 }
365 defer rows.Close()
366 var out []Repo
367 for rows.Next() {
368 r, err := scanRepo(rows)
369 if err != nil {
370 return nil, err
371 }
372 out = append(out, r)
373 }
374 return out, rows.Err()
375}
376
377func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
378 _, err := s.DB.Exec("UPDATE repos SET default_branch = ? WHERE id = ?", branch, repoID)
379 return err
380}
381
382// ListReposForOwner returns every repo owned by one user or org; the caller
383// filters by viewer visibility.
384func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
385 rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
386 ownerKind, ownerID)
387 if err != nil {
388 return nil, err
389 }
390 defer rows.Close()
391 var out []Repo
392 for rows.Next() {
393 r, err := scanRepo(rows)
394 if err != nil {
395 return nil, err
396 }
397 out = append(out, r)
398 }
399 return out, rows.Err()
400}
401
402// RenameRepo changes a repository's name under the same owner. The unique
403// index on (owner_kind, owner_id, name) refuses collisions.
404func (s *Store) RenameRepo(repoID int64, newName string) error {
405 _, err := s.DB.Exec("UPDATE repos SET name = ? WHERE id = ?", newName, repoID)
406 if isUniqueErr(err) {
407 return fmt.Errorf("the owner already has a repository by that name")
408 }
409 return err
410}
411
412// TransferRepo moves a repository to a new owner. The unique index on
413// (owner_kind, owner_id, name) refuses collisions in the target namespace.
414func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error {
415 _, err := s.DB.Exec("UPDATE repos SET owner_kind = ?, owner_id = ? WHERE id = ?",
416 newKind, newOwnerID, repoID)
417 if isUniqueErr(err) {
418 return fmt.Errorf("the target owner already has a repository by that name")
419 }
420 return err
421}