461 lines
12 KiB
Go
461 lines
12 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
"path/filepath"
|
|
"strconv"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"xorm.io/xorm"
|
|
|
|
"github.com/forgeo/forgebucket/internal/api/middleware"
|
|
"github.com/forgeo/forgebucket/internal/config"
|
|
gitdomain "github.com/forgeo/forgebucket/internal/domain/git"
|
|
"github.com/forgeo/forgebucket/internal/models"
|
|
)
|
|
|
|
// repoResponse enriches a Repository with derived fields the frontend needs.
|
|
type repoResponse struct {
|
|
models.Repository
|
|
OwnerName string `json:"ownerName"`
|
|
IsEmpty bool `json:"isEmpty"`
|
|
}
|
|
|
|
func (h *RepoHandler) withOwnerName(repo *models.Repository) repoResponse {
|
|
var owner models.User
|
|
h.db.ID(repo.OwnerID).Get(&owner)
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
return repoResponse{
|
|
Repository: *repo,
|
|
OwnerName: owner.Username,
|
|
IsEmpty: gitdomain.IsEmpty(repo.DiskPath),
|
|
}
|
|
}
|
|
|
|
type RepoHandler struct {
|
|
db *xorm.Engine
|
|
cfg *config.Config
|
|
}
|
|
|
|
func NewRepoHandler(db *xorm.Engine, cfg *config.Config) *RepoHandler {
|
|
return &RepoHandler{db: db, cfg: cfg}
|
|
}
|
|
|
|
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
|
|
|
var repos []models.Repository
|
|
if err := h.db.Where("owner_id = ?", userID).Find(&repos); err != nil {
|
|
jsonError(w, "could not list repositories", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
result := make([]repoResponse, len(repos))
|
|
for i := range repos {
|
|
result[i] = h.withOwnerName(&repos[i])
|
|
}
|
|
jsonOK(w, result)
|
|
}
|
|
|
|
func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
|
|
|
var body struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
IsPrivate bool `json:"isPrivate"`
|
|
DefaultBranch string `json:"defaultBranch"`
|
|
InitReadme string `json:"initReadme"` // "none" | "blank" | "tutorial"
|
|
InitGitignore bool `json:"initGitignore"` // true → add .gitignore
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if body.Name == "" {
|
|
jsonError(w, "name is required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
branch := body.DefaultBranch
|
|
if branch == "" {
|
|
branch = "main"
|
|
}
|
|
|
|
diskPath := filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
|
|
|
repo := &models.Repository{
|
|
OwnerID: userID,
|
|
Name: body.Name,
|
|
Description: body.Description,
|
|
IsPrivate: body.IsPrivate,
|
|
DefaultBranch: branch,
|
|
DiskPath: diskPath,
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
if err := gitdomain.Init(diskPath); err != nil {
|
|
jsonError(w, "could not initialise git repository", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// Update bare repo HEAD if branch differs from the Init default (main).
|
|
if branch != "main" {
|
|
gitdomain.SetDefaultBranch(diskPath, branch)
|
|
}
|
|
|
|
if _, err := h.db.Insert(repo); err != nil {
|
|
jsonError(w, "repository name already taken", http.StatusConflict)
|
|
return
|
|
}
|
|
|
|
// Create initial commit when README or .gitignore was requested.
|
|
wantsReadme := body.InitReadme == "blank" || body.InitReadme == "tutorial"
|
|
if wantsReadme || body.InitGitignore {
|
|
var u models.User
|
|
h.db.ID(userID).Get(&u)
|
|
authorEmail := u.Email
|
|
if authorEmail == "" {
|
|
authorEmail = u.Username + "@forgebucket.local"
|
|
}
|
|
if err := gitdomain.InitWithFiles(diskPath, branch, body.Name, u.Username, authorEmail, wantsReadme, body.InitGitignore); err != nil {
|
|
// Non-fatal: repo is created, just without initial files.
|
|
_ = err
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
json.NewEncoder(w).Encode(h.withOwnerName(repo))
|
|
}
|
|
|
|
func (h *RepoHandler) Import(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := middleware.UserIDFromContext(r.Context())
|
|
if !ok {
|
|
jsonError(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var body struct {
|
|
URL string `json:"url"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
IsPrivate bool `json:"isPrivate"`
|
|
AuthUser string `json:"authUser"`
|
|
AuthPass string `json:"authPass"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if body.URL == "" || body.Name == "" {
|
|
jsonError(w, "url and name are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Inject credentials into the URL if provided.
|
|
srcURL := body.URL
|
|
if body.AuthUser != "" {
|
|
u, err := url.Parse(body.URL)
|
|
if err != nil {
|
|
jsonError(w, "invalid URL", http.StatusBadRequest)
|
|
return
|
|
}
|
|
u.User = url.UserPassword(body.AuthUser, body.AuthPass)
|
|
srcURL = u.String()
|
|
}
|
|
|
|
diskPath := filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
|
|
|
repo := &models.Repository{
|
|
OwnerID: userID,
|
|
Name: body.Name,
|
|
Description: body.Description,
|
|
IsPrivate: body.IsPrivate,
|
|
DefaultBranch: "main",
|
|
DiskPath: diskPath,
|
|
}
|
|
|
|
if _, err := h.db.Insert(repo); err != nil {
|
|
jsonError(w, "repository name already taken", http.StatusConflict)
|
|
return
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
if err := gitdomain.CloneRepo(srcURL, diskPath); err != nil {
|
|
h.db.ID(repo.ID).Delete(&models.Repository{})
|
|
jsonError(w, "import failed: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
json.NewEncoder(w).Encode(h.withOwnerName(repo))
|
|
}
|
|
|
|
func (h *RepoHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
jsonOK(w, h.withOwnerName(repo))
|
|
}
|
|
|
|
func (h *RepoHandler) Tree(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ref := r.URL.Query().Get("ref")
|
|
if ref == "" {
|
|
ref = repo.DefaultBranch
|
|
}
|
|
subPath := r.URL.Query().Get("path")
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
entries, err := gitdomain.TreeLS(repo.DiskPath, ref, subPath)
|
|
if err != nil {
|
|
jsonError(w, "could not read tree", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if entries == nil {
|
|
entries = []gitdomain.TreeEntry{}
|
|
}
|
|
jsonOK(w, entries)
|
|
}
|
|
|
|
func (h *RepoHandler) Blob(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ref := r.URL.Query().Get("ref")
|
|
if ref == "" {
|
|
ref = repo.DefaultBranch
|
|
}
|
|
path := r.URL.Query().Get("path")
|
|
if path == "" {
|
|
jsonError(w, "path is required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
content, err := gitdomain.BlobCat(repo.DiskPath, ref, path)
|
|
if err != nil {
|
|
jsonError(w, "file not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
jsonOK(w, map[string]string{"content": string(content), "path": path, "ref": ref})
|
|
}
|
|
|
|
func (h *RepoHandler) UpdateBlob(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
userID, ok := middleware.UserIDFromContext(r.Context())
|
|
if !ok {
|
|
jsonError(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
var u models.User
|
|
if has, _ := h.db.ID(userID).Get(&u); !has {
|
|
jsonError(w, "user not found", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Path string `json:"path"`
|
|
Content string `json:"content"`
|
|
Message string `json:"message"`
|
|
Branch string `json:"branch"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
jsonError(w, "invalid body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if req.Path == "" || req.Message == "" {
|
|
jsonError(w, "path and message are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if req.Branch == "" {
|
|
req.Branch = repo.DefaultBranch
|
|
}
|
|
|
|
authorEmail := u.Email
|
|
if authorEmail == "" {
|
|
authorEmail = u.Username + "@forgebucket.local"
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
if err := gitdomain.WriteFile(repo.DiskPath, req.Branch, req.Path, req.Content, u.Username, authorEmail, req.Message); err != nil {
|
|
jsonError(w, "could not save file: "+err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
jsonOK(w, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (h *RepoHandler) Branches(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
branches, err := gitdomain.Branches(repo.DiskPath)
|
|
if err != nil {
|
|
jsonError(w, "could not list branches", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if branches == nil {
|
|
branches = []gitdomain.Branch{}
|
|
}
|
|
jsonOK(w, branches)
|
|
}
|
|
|
|
func (h *RepoHandler) Commits(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ref := r.URL.Query().Get("ref")
|
|
if ref == "" {
|
|
ref = repo.DefaultBranch
|
|
}
|
|
limit := 30
|
|
if l := r.URL.Query().Get("limit"); l != "" {
|
|
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 100 {
|
|
limit = n
|
|
}
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
commits, err := gitdomain.Log(repo.DiskPath, ref, limit)
|
|
if err != nil {
|
|
jsonError(w, "could not read commits", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if commits == nil {
|
|
commits = []gitdomain.Commit{}
|
|
}
|
|
jsonOK(w, commits)
|
|
}
|
|
|
|
func (h *RepoHandler) Update(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var body struct {
|
|
Description *string `json:"description"`
|
|
IsPrivate *bool `json:"isPrivate"`
|
|
DefaultBranch *string `json:"defaultBranch"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
cols := []string{}
|
|
if body.Description != nil {
|
|
repo.Description = *body.Description
|
|
cols = append(cols, "description")
|
|
}
|
|
if body.IsPrivate != nil {
|
|
repo.IsPrivate = *body.IsPrivate
|
|
cols = append(cols, "is_private")
|
|
}
|
|
if body.DefaultBranch != nil {
|
|
repo.DefaultBranch = *body.DefaultBranch
|
|
cols = append(cols, "default_branch")
|
|
}
|
|
|
|
if len(cols) > 0 {
|
|
if _, err := h.db.ID(repo.ID).Cols(cols...).Update(repo); err != nil {
|
|
jsonError(w, "could not update repository", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
jsonOK(w, h.withOwnerName(repo))
|
|
}
|
|
|
|
func (h *RepoHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
callerID, _ := middleware.UserIDFromContext(r.Context())
|
|
if callerID != repo.OwnerID {
|
|
jsonError(w, "only the owner can delete a repository", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
if _, err := h.db.ID(repo.ID).Delete(&models.Repository{}); err != nil {
|
|
jsonError(w, "could not delete repository", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *RepoHandler) Diff(w http.ResponseWriter, r *http.Request) {
|
|
repo, ok := h.lookupRepo(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
base := r.URL.Query().Get("base")
|
|
head := r.URL.Query().Get("head")
|
|
if base == "" || head == "" {
|
|
jsonError(w, "base and head query params are required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
|
diffs, err := gitdomain.Diff(repo.DiskPath, base, head)
|
|
if err != nil {
|
|
jsonError(w, "could not compute diff", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if diffs == nil {
|
|
diffs = []gitdomain.FileDiff{}
|
|
}
|
|
jsonOK(w, diffs)
|
|
}
|
|
|
|
// lookupRepo resolves {owner}/{repo} URL params to a DB row, enforcing access.
|
|
func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) {
|
|
ownerName := chi.URLParam(r, "owner")
|
|
repoName := chi.URLParam(r, "repo")
|
|
|
|
var owner models.User
|
|
found, err := h.db.Where("username = ?", ownerName).Get(&owner)
|
|
if err != nil || !found {
|
|
jsonError(w, "repository not found", http.StatusNotFound)
|
|
return nil, false
|
|
}
|
|
|
|
var repo models.Repository
|
|
found, err = h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo)
|
|
if err != nil || !found {
|
|
jsonError(w, "repository not found", http.StatusNotFound)
|
|
return nil, false
|
|
}
|
|
|
|
// Private repo: only the owner may access (RBAC will be expanded in Phase 3)
|
|
if repo.IsPrivate {
|
|
callerID, _ := middleware.UserIDFromContext(r.Context())
|
|
if callerID != repo.OwnerID {
|
|
jsonError(w, "repository not found", http.StatusNotFound)
|
|
return nil, false
|
|
}
|
|
}
|
|
|
|
return &repo, true
|
|
}
|