internal/store/repos.go

d47a2ef73f46cfbc3083c56e041d79130ae9eb71
gitbay/internal/store/repos.go

192 lines · 5840 bytes

  1package store
  2
  3import (
  4	"database/sql"
  5	"encoding/json"
  6	"errors"
  7	"fmt"
  8	"strings"
  9)
 10
 11type Repo struct {
 12	ID            int64
 13	OwnerKind     string // user | org
 14	OwnerID       int64
 15	OwnerName     string // resolved for display and disk paths
 16	Name          string
 17	Visibility    string // public | private
 18	DefaultBranch string
 19	Settings      RepoSettings
 20}
 21
 22type RepoSettings struct {
 23	ProtectedBranches    []string `json:"protected_branches,omitempty"`
 24	RequireSignedCommits bool     `json:"require_signed_commits,omitempty"`
 25}
 26
 27// Path returns the canonical owner/name form.
 28func (r Repo) Path() string { return r.OwnerName + "/" + r.Name }
 29
 30func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error) {
 31	res, err := s.DB.Exec(
 32		"INSERT INTO repos (owner_kind, owner_id, name, visibility) VALUES (?, ?, ?, ?)",
 33		ownerKind, ownerID, name, visibility)
 34	if err != nil {
 35		if isUniqueErr(err) {
 36			return 0, fmt.Errorf("repository %q already exists", name)
 37		}
 38		return 0, err
 39	}
 40	return res.LastInsertId()
 41}
 42
 43// RepoByPath resolves "owner/name". Only user owners exist until orgs land.
 44func (s *Store) RepoByPath(path string) (Repo, error) {
 45	owner, name, ok := strings.Cut(strings.TrimSuffix(strings.TrimPrefix(path, "/"), ".git"), "/")
 46	if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
 47		return Repo{}, fmt.Errorf("%w: repository path must be owner/name", ErrNotFound)
 48	}
 49	var r Repo
 50	var settingsJSON string
 51	err := s.DB.QueryRow(`
 52		SELECT r.id, r.owner_kind, r.owner_id, u.username, r.name, r.visibility, r.default_branch, r.settings_json
 53		FROM repos r JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
 54		WHERE u.username = ? AND r.name = ?`, owner, name).
 55		Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &settingsJSON)
 56	if errors.Is(err, sql.ErrNoRows) {
 57		return Repo{}, ErrNotFound
 58	}
 59	if err != nil {
 60		return Repo{}, err
 61	}
 62	if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
 63		return Repo{}, fmt.Errorf("repo %d settings: %w", r.ID, err)
 64	}
 65	return r, nil
 66}
 67
 68func (s *Store) SetRepoSettings(repoID int64, settings RepoSettings) error {
 69	raw, err := json.Marshal(settings)
 70	if err != nil {
 71		return err
 72	}
 73	_, err = s.DB.Exec("UPDATE repos SET settings_json = ? WHERE id = ?", string(raw), repoID)
 74	return err
 75}
 76
 77func (s *Store) DeleteRepo(repoID int64) error {
 78	res, err := s.DB.Exec("DELETE FROM repos WHERE id = ?", repoID)
 79	if err != nil {
 80		return err
 81	}
 82	if n, _ := res.RowsAffected(); n == 0 {
 83		return ErrNotFound
 84	}
 85	return nil
 86}
 87
 88// ListReposForUser returns repos the user owns or has an explicit grant on.
 89func (s *Store) ListReposForUser(userID int64) ([]Repo, error) {
 90	rows, err := s.DB.Query(`
 91		SELECT DISTINCT r.id, r.owner_kind, r.owner_id, u.username, r.name, r.visibility, r.default_branch, r.settings_json
 92		FROM repos r
 93		JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
 94		LEFT JOIN repo_access a ON a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?
 95		WHERE r.owner_id = ? OR a.subject_id IS NOT NULL
 96		ORDER BY u.username, r.name`, userID, userID)
 97	if err != nil {
 98		return nil, err
 99	}
100	defer rows.Close()
101	var out []Repo
102	for rows.Next() {
103		var r Repo
104		var settingsJSON string
105		if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &settingsJSON); err != nil {
106			return nil, err
107		}
108		if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
109			return nil, err
110		}
111		out = append(out, r)
112	}
113	return out, rows.Err()
114}
115
116// AccessRole returns the explicit grant for userID on repoID ("" if none).
117func (s *Store) AccessRole(repoID, userID int64) (string, error) {
118	var role string
119	err := s.DB.QueryRow(
120		"SELECT role FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
121		repoID, userID).Scan(&role)
122	if errors.Is(err, sql.ErrNoRows) {
123		return "", nil
124	}
125	return role, err
126}
127
128func (s *Store) GrantAccess(repoID, userID int64, role string) error {
129	_, err := s.DB.Exec(`
130		INSERT INTO repo_access (repo_id, subject_kind, subject_id, role) VALUES (?, 'user', ?, ?)
131		ON CONFLICT (repo_id, subject_kind, subject_id) DO UPDATE SET role = excluded.role`,
132		repoID, userID, role)
133	return err
134}
135
136func (s *Store) RevokeAccess(repoID, userID int64) error {
137	res, err := s.DB.Exec(
138		"DELETE FROM repo_access WHERE repo_id = ? AND subject_kind = 'user' AND subject_id = ?",
139		repoID, userID)
140	if err != nil {
141		return err
142	}
143	if n, _ := res.RowsAffected(); n == 0 {
144		return ErrNotFound
145	}
146	return nil
147}
148
149type AccessEntry struct {
150	Username string
151	Role     string
152}
153
154func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error) {
155	rows, err := s.DB.Query(`
156		SELECT u.username, a.role FROM repo_access a
157		JOIN users u ON a.subject_kind = 'user' AND u.id = a.subject_id
158		WHERE a.repo_id = ? ORDER BY u.username`, repoID)
159	if err != nil {
160		return nil, err
161	}
162	defer rows.Close()
163	var out []AccessEntry
164	for rows.Next() {
165		var e AccessEntry
166		if err := rows.Scan(&e.Username, &e.Role); err != nil {
167			return nil, err
168		}
169		out = append(out, e)
170	}
171	return out, rows.Err()
172}
173
174func (s *Store) RepoByID(id int64) (Repo, error) {
175	var r Repo
176	var settingsJSON string
177	err := s.DB.QueryRow(`
178		SELECT r.id, r.owner_kind, r.owner_id, u.username, r.name, r.visibility, r.default_branch, r.settings_json
179		FROM repos r JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
180		WHERE r.id = ?`, id).
181		Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &r.OwnerName, &r.Name, &r.Visibility, &r.DefaultBranch, &settingsJSON)
182	if errors.Is(err, sql.ErrNoRows) {
183		return Repo{}, ErrNotFound
184	}
185	if err != nil {
186		return Repo{}, err
187	}
188	if err := json.Unmarshal([]byte(settingsJSON), &r.Settings); err != nil {
189		return Repo{}, err
190	}
191	return r, nil
192}