feat: Phase 2 — Git 核心功能,go-git 克隆、SSE 进度、D3.js 图形、diff2html 查看器
This commit is contained in:
+219
-12
@@ -2,15 +2,20 @@ package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/HoHD/PR-Helper/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ReposHandler struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
reposDir string
|
||||
}
|
||||
|
||||
@@ -56,22 +61,18 @@ func (h *ReposHandler) DeleteRepo(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// Remove from filesystem
|
||||
os.RemoveAll(localPath)
|
||||
// Remove from database
|
||||
h.db.Exec(`DELETE FROM analyses WHERE repo_id = ?`, id)
|
||||
h.db.Exec(`DELETE FROM repositories WHERE id = ?`, id)
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
func (h *ReposHandler) CleanupRepos(c *gin.Context) {
|
||||
// Get max age from settings
|
||||
var maxAgeDays string
|
||||
h.db.QueryRow(`SELECT value FROM settings WHERE key = 'cache.max_age_days'`).Scan(&maxAgeDays)
|
||||
if maxAgeDays == "" {
|
||||
maxAgeDays = "7"
|
||||
}
|
||||
// Find expired repos
|
||||
rows, err := h.db.Query(`SELECT id, local_path FROM repositories WHERE last_used < datetime('now', '-' || ? || ' days')`, maxAgeDays)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
@@ -92,22 +93,228 @@ func (h *ReposHandler) CleanupRepos(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"cleaned": cleaned})
|
||||
}
|
||||
|
||||
// CloneRepo handles POST /api/repos — stub for Phase 2
|
||||
// CloneRepo handles POST /api/repos with SSE progress events.
|
||||
func (h *ReposHandler) CloneRepo(c *gin.Context) {
|
||||
c.JSON(http.StatusNotImplemented, gin.H{"error": "clone not implemented yet — coming in Phase 2"})
|
||||
var req struct {
|
||||
URL string `json:"url" binding:"required"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "url is required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Set SSE headers
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.Header("Connection", "keep-alive")
|
||||
c.Header("X-Accel-Buffering", "no")
|
||||
|
||||
flusher, ok := c.Writer.(http.Flusher)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "streaming not supported"})
|
||||
return
|
||||
}
|
||||
|
||||
sendEvent := func(event string, data interface{}) {
|
||||
jsonData, _ := json.Marshal(data)
|
||||
fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event, jsonData)
|
||||
flusher.Flush()
|
||||
}
|
||||
|
||||
sendEvent("start", map[string]interface{}{"url": req.URL})
|
||||
|
||||
// Generate unique directory name
|
||||
repoName := filepath.Base(req.URL)
|
||||
if repoName == "" || repoName == "." || repoName == "/" {
|
||||
repoName = fmt.Sprintf("repo_%d", time.Now().UnixNano())
|
||||
}
|
||||
repoDir := filepath.Join(h.reposDir, fmt.Sprintf("%s_%d", repoName, time.Now().UnixNano()))
|
||||
|
||||
result, err := services.Clone(services.CloneOptions{
|
||||
URL: req.URL,
|
||||
Dir: repoDir,
|
||||
Username: req.Username,
|
||||
Password: req.Password,
|
||||
}, func(event string, data interface{}) {
|
||||
sendEvent(event, data)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
sendEvent("error", map[string]interface{}{"message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Save to database
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
res, err := h.db.Exec(`INSERT INTO repositories (url, local_path, size_bytes, cloned_at, last_used) VALUES (?, ?, ?, ?, ?)`,
|
||||
req.URL, repoDir, result.SizeBytes, now, now)
|
||||
if err != nil {
|
||||
sendEvent("error", map[string]interface{}{"message": "save to db: " + err.Error()})
|
||||
return
|
||||
}
|
||||
repoID, _ := res.LastInsertId()
|
||||
|
||||
sendEvent("complete", map[string]interface{}{
|
||||
"repo_id": repoID,
|
||||
"size_bytes": result.SizeBytes,
|
||||
})
|
||||
}
|
||||
|
||||
// GetGraph handles GET /api/repos/:id/graph — stub for Phase 2
|
||||
// GetGraph handles GET /api/repos/:id/graph — returns D3.js-compatible data.
|
||||
func (h *ReposHandler) GetGraph(c *gin.Context) {
|
||||
c.JSON(http.StatusNotImplemented, gin.H{"error": "graph not implemented yet — coming in Phase 2"})
|
||||
id := c.Param("id")
|
||||
var localPath string
|
||||
err := h.db.QueryRow(`SELECT local_path FROM repositories WHERE id = ?`, id).Scan(&localPath)
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "repository not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update last_used
|
||||
h.db.Exec(`UPDATE repositories SET last_used = datetime('now') WHERE id = ?`, id)
|
||||
|
||||
repo, err := services.OpenRepo(localPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "open repo: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
maxCommits := 200
|
||||
if mc := c.Query("max_commits"); mc != "" {
|
||||
if n, err := strconv.Atoi(mc); err == nil && n > 0 {
|
||||
maxCommits = n
|
||||
}
|
||||
}
|
||||
|
||||
graph, err := services.GetGraph(repo, maxCommits)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, graph)
|
||||
}
|
||||
|
||||
// GetDiff handles GET /api/repos/:id/diff — stub for Phase 2
|
||||
// GetDiff handles GET /api/repos/:id/diff — returns unified diff or per-file diffs.
|
||||
func (h *ReposHandler) GetDiff(c *gin.Context) {
|
||||
c.JSON(http.StatusNotImplemented, gin.H{"error": "diff not implemented yet — coming in Phase 2"})
|
||||
id := c.Param("id")
|
||||
base := c.Query("base")
|
||||
head := c.Query("head")
|
||||
|
||||
if base == "" || head == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "base and head query params are required"})
|
||||
return
|
||||
}
|
||||
|
||||
var localPath string
|
||||
err := h.db.QueryRow(`SELECT local_path FROM repositories WHERE id = ?`, id).Scan(&localPath)
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "repository not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update last_used
|
||||
h.db.Exec(`UPDATE repositories SET last_used = datetime('now') WHERE id = ?`, id)
|
||||
|
||||
repo, err := services.OpenRepo(localPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Check if per-file mode is requested
|
||||
if c.Query("per_file") == "true" {
|
||||
files, err := services.GetDiffFiles(repo, base, head)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, files)
|
||||
return
|
||||
}
|
||||
|
||||
diff, err := services.GetDiff(repo, base, head)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"diff": diff})
|
||||
}
|
||||
|
||||
// GetRefs handles GET /api/repos/:id/refs — returns branches and tags.
|
||||
func (h *ReposHandler) GetRefs(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
var localPath string
|
||||
err := h.db.QueryRow(`SELECT local_path FROM repositories WHERE id = ?`, id).Scan(&localPath)
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "repository not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
repo, err := services.OpenRepo(localPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
refs, err := services.GetRefs(repo)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, refs)
|
||||
}
|
||||
|
||||
// GetCommits handles GET /api/repos/:id/commits — returns commit log for a ref.
|
||||
func (h *ReposHandler) GetCommits(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
refName := c.Query("ref")
|
||||
if refName == "" {
|
||||
refName = "HEAD"
|
||||
}
|
||||
maxCommits := 100
|
||||
if mc := c.Query("limit"); mc != "" {
|
||||
if n, err := strconv.Atoi(mc); err == nil && n > 0 {
|
||||
maxCommits = n
|
||||
}
|
||||
}
|
||||
|
||||
var localPath string
|
||||
err := h.db.QueryRow(`SELECT local_path FROM repositories WHERE id = ?`, id).Scan(&localPath)
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "repository not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
commits, err := services.GetBranchCommits(localPath, refName, maxCommits)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, commits)
|
||||
}
|
||||
|
||||
// dirSize returns the total size of a directory in bytes
|
||||
func dirSize(path string) int64 {
|
||||
var size int64
|
||||
filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
|
||||
|
||||
Reference in New Issue
Block a user