package handlers import ( "archive/zip" "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "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"` AvatarURL string `json:"avatarUrl"` Size int64 `json:"size"` } func avatarPath(repoRoot string, repoID int64) string { return filepath.Join(repoRoot, ".avatars", strconv.FormatInt(repoID, 10)) } func isValidRepoName(name string) bool { if len(name) == 0 || len(name) > 100 { return false } for _, c := range name { if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-') { return false } } return true } func (h *RepoHandler) withOwnerName(repo *models.Repository) repoResponse { gitdomain.SetRepoRoot(h.cfg.RepoRoot) ownerName := "" if repo.WorkspaceID != nil && *repo.WorkspaceID != 0 { var ws models.Workspace h.db.ID(*repo.WorkspaceID).Cols("handle").Get(&ws) ownerName = ws.Handle } else { var owner models.User h.db.ID(repo.OwnerID).Cols("username").Get(&owner) ownerName = owner.Username } avURL := "" if _, err := os.Stat(avatarPath(h.cfg.RepoRoot, repo.ID)); err == nil { avURL = "/api/v1/repos/" + ownerName + "/" + repo.Name + "/avatar" } return repoResponse{ Repository: *repo, AvatarURL: avURL, OwnerName: ownerName, 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()) // User-owned repos. var repos []models.Repository h.db.Where("owner_id = ? AND workspace_id IS NULL", userID).Find(&repos) // Workspace repos where user is a member. var memberships []models.WorkspaceMember h.db.Where("user_id = ?", userID).Find(&memberships) if len(memberships) > 0 { wsIDs := make([]int64, len(memberships)) for i, m := range memberships { wsIDs[i] = m.WorkspaceID } var wsRepos []models.Repository h.db.In("workspace_id", wsIDs).Find(&wsRepos) repos = append(repos, wsRepos...) } 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 Workspace string `json:"workspace"` // optional workspace handle } 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" } // Determine owner: workspace or user. var workspaceID *int64 var diskPath string if body.Workspace != "" { var ws models.Workspace if found, _ := h.db.Where("handle = ?", body.Workspace).Get(&ws); !found { jsonError(w, "workspace not found", http.StatusNotFound) return } // Caller must be a member with write access. var member models.WorkspaceMember if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); !found { jsonError(w, "not a member of this workspace", http.StatusForbidden) return } if member.Role == models.WorkspaceRoleMember { jsonError(w, "admin or owner required to create repos in a workspace", http.StatusForbidden) return } wsID := ws.ID workspaceID = &wsID diskPath = diskPathForWorkspaceRepo(h.cfg.RepoRoot, ws.ID, body.Name) } else { diskPath = filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git") } repo := &models.Repository{ OwnerID: userID, WorkspaceID: workspaceID, 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 } resp := h.withOwnerName(repo) gitdomain.SetRepoRoot(h.cfg.RepoRoot) resp.Size = gitdomain.RepoSize(repo.DiskPath) jsonOK(w, resp) } 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 } callerID, _ := middleware.UserIDFromContext(r.Context()) if callerID != repo.OwnerID { jsonError(w, "only the owner can update a repository", http.StatusForbidden) return } var body struct { Name *string `json:"name"` 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{} // Rename: update disk path and DB name atomically. if body.Name != nil && *body.Name != "" && *body.Name != repo.Name { newName := strings.TrimSpace(*body.Name) if !isValidRepoName(newName) { jsonError(w, "invalid repository name: use letters, numbers, hyphens, underscores, and dots only", http.StatusBadRequest) return } newDiskPath := filepath.Join(filepath.Dir(repo.DiskPath), newName+".git") if _, err := os.Stat(newDiskPath); !os.IsNotExist(err) { jsonError(w, "a repository with that name already exists", http.StatusConflict) return } if err := os.Rename(repo.DiskPath, newDiskPath); err != nil { jsonError(w, "could not rename repository on disk", http.StatusInternalServerError) return } repo.DiskPath = newDiskPath repo.Name = newName cols = append(cols, "name", "disk_path") } 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)) } // GetAvatar serves the repository avatar image stored on disk. func (h *RepoHandler) GetAvatar(w http.ResponseWriter, r *http.Request) { repo, ok := h.lookupRepo(w, r) if !ok { return } data, err := os.ReadFile(avatarPath(h.cfg.RepoRoot, repo.ID)) if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", http.DetectContentType(data)) w.Header().Set("Cache-Control", "public, max-age=86400") w.Write(data) } // UploadAvatar accepts a multipart image upload and stores it as the repo avatar. func (h *RepoHandler) UploadAvatar(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 change the avatar", http.StatusForbidden) return } r.Body = http.MaxBytesReader(w, r.Body, 5<<20) if err := r.ParseMultipartForm(5 << 20); err != nil { jsonError(w, "file too large (max 5 MB)", http.StatusBadRequest) return } file, _, err := r.FormFile("avatar") if err != nil { jsonError(w, "avatar file is required", http.StatusBadRequest) return } defer file.Close() // Sniff content type from first 512 bytes, then read the rest. sniff := make([]byte, 512) n, _ := file.Read(sniff) ct := http.DetectContentType(sniff[:n]) if ct != "image/jpeg" && ct != "image/png" && ct != "image/gif" && ct != "image/webp" { jsonError(w, "unsupported image type; use JPEG, PNG, GIF, or WebP", http.StatusBadRequest) return } rest, err := io.ReadAll(file) if err != nil { jsonError(w, "could not read file", http.StatusInternalServerError) return } data := append(sniff[:n], rest...) avatarDir := filepath.Join(h.cfg.RepoRoot, ".avatars") if err := os.MkdirAll(avatarDir, 0755); err != nil { jsonError(w, "could not create avatar directory", http.StatusInternalServerError) return } if err := os.WriteFile(avatarPath(h.cfg.RepoRoot, repo.ID), data, 0644); err != nil { jsonError(w, "could not save avatar", http.StatusInternalServerError) return } var ownerUser models.User h.db.ID(repo.OwnerID).Get(&ownerUser) jsonOK(w, map[string]string{ "avatarUrl": "/api/v1/repos/" + ownerUser.Username + "/" + repo.Name + "/avatar", }) } 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. // The owner segment can be either a username (user-owned repo) or a // workspace handle (workspace-owned repo). func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) { ownerName := chi.URLParam(r, "owner") repoName := chi.URLParam(r, "repo") callerID, _ := middleware.UserIDFromContext(r.Context()) // 1. Try user namespace first. var user models.User if found, _ := h.db.Where("username = ?", ownerName).Get(&user); found { var repo models.Repository if found2, _ := h.db.Where("owner_id = ? AND name = ? AND workspace_id IS NULL", user.ID, repoName).Get(&repo); found2 { if repo.IsPrivate && callerID != repo.OwnerID { // Check repo membership for private user repos. var m models.RepoMember if mfound, _ := h.db.Where("repo_id = ? AND user_id = ?", repo.ID, callerID).Get(&m); !mfound { jsonError(w, "repository not found", http.StatusNotFound) return nil, false } } return &repo, true } } // 2. Try workspace namespace. var ws models.Workspace if found, _ := h.db.Where("handle = ?", ownerName).Get(&ws); found { var repo models.Repository if found2, _ := h.db.Where("workspace_id = ? AND name = ?", ws.ID, repoName).Get(&repo); found2 { if repo.IsPrivate { // Private workspace repo: caller must be a workspace member. var m models.WorkspaceMember if mfound, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, callerID).Get(&m); !mfound { jsonError(w, "repository not found", http.StatusNotFound) return nil, false } } return &repo, true } } jsonError(w, "repository not found", http.StatusNotFound) return nil, false } // SearchFiles handles GET /repos/{owner}/{repo}/files?q=...&ref=... // Returns up to 20 matching file paths (case-insensitive substring match). // When q is empty, returns all file paths up to 500 (used by the sidebar tree). func (h *RepoHandler) SearchFiles(w http.ResponseWriter, r *http.Request) { repo, ok := h.lookupRepo(w, r) if !ok { return } query := strings.TrimSpace(r.URL.Query().Get("q")) ref := r.URL.Query().Get("ref") if ref == "" { ref = repo.DefaultBranch } limit := 20 if query == "" { limit = 500 } files, err := gitdomain.SearchFiles(repo.DiskPath, ref, query, limit) if err != nil { jsonError(w, "search failed", http.StatusInternalServerError) return } if files == nil { files = []string{} } jsonOK(w, files) } // UploadFiles handles POST /repos/{owner}/{repo}/upload — multipart upload. // Accepts multiple regular files (field "file[]") and/or a ZIP archive (field "zip"). // All files are committed in a single git commit. func (h *RepoHandler) UploadFiles(w http.ResponseWriter, r *http.Request) { repo, ok := h.lookupRepo(w, r) if !ok { return } username, _ := r.Context().Value(middleware.ContextKeyUsername).(string) if !HasPermission(h.db, repo, username, "write") { jsonError(w, "you do not have write access to this repository", http.StatusForbidden) return } const maxUpload = 50 << 20 // 50 MB if err := r.ParseMultipartForm(maxUpload); err != nil { jsonError(w, "could not parse upload: "+err.Error(), http.StatusBadRequest) return } branch := r.FormValue("branch") if branch == "" { branch = repo.DefaultBranch } message := r.FormValue("message") if message == "" { message = "Upload files" } var uploads []gitdomain.FileUpload // Regular files (field "file[]" or "file"). Browser sends webkitRelativePath // via the custom header X-File-Path; fall back to the bare filename. for _, fhs := range r.MultipartForm.File { for _, fh := range fhs { if fh.Size == 0 { continue } f, err := fh.Open() if err != nil { continue } data, err := io.ReadAll(io.LimitReader(f, 10<<20)) // 10 MB per file f.Close() if err != nil { continue } // Prefer the relative path sent by the browser (folder upload), // otherwise use the bare filename. relPath := fh.Filename if rp := fh.Header.Get("X-File-Path"); rp != "" { relPath = rp } if strings.EqualFold(fh.Header.Get("Content-Disposition"), "") { // Skip the "zip" field — handled separately below. } clean := filepath.Clean(filepath.FromSlash(relPath)) if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) { jsonError(w, fmt.Sprintf("invalid path: %s", relPath), http.StatusBadRequest) return } uploads = append(uploads, gitdomain.FileUpload{Path: clean, Content: data}) } } // ZIP archive (field "zip"). if zipFHs, ok := r.MultipartForm.File["zip"]; ok && len(zipFHs) > 0 { fh := zipFHs[0] f, err := fh.Open() if err == nil { zipData, err := io.ReadAll(io.LimitReader(f, maxUpload)) f.Close() if err == nil { zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData))) if err == nil { for _, zf := range zr.File { if zf.FileInfo().IsDir() { continue } clean := filepath.Clean(filepath.FromSlash(zf.Name)) if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) { continue } rc, err := zf.Open() if err != nil { continue } data, err := io.ReadAll(io.LimitReader(rc, 10<<20)) rc.Close() if err != nil { continue } uploads = append(uploads, gitdomain.FileUpload{Path: clean, Content: data}) } } } } } if len(uploads) == 0 { jsonError(w, "no files found in upload", http.StatusBadRequest) return } if err := gitdomain.WriteManyFiles(repo.DiskPath, branch, message, username, username+"@forgebucket", uploads); err != nil { jsonError(w, "commit failed: "+err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]int{"committed": len(uploads)}) //nolint:errcheck }