2.7 KB
git.go
package controllers
import (
"log"
"net/http"
"os"
"strings"
"github.com/readysite/readysite/pkg/application"
"github.com/readysite/readysite/readysite.org/internal/sharing"
"github.com/sosedoff/gitkit"
)
// GitController handles git repository browsing and HTTP access.
type GitController struct {
application.BaseController
gitServer *gitkit.Server
}
// Git returns the controller name and instance.
func Git() (string, *GitController) {
return "git", &GitController{}
}
// Setup registers routes for git browsing and HTTP access.
func (c *GitController) Setup(app *application.App) {
c.BaseController.Setup(app)
// Initialize git repository in production
if os.Getenv("ENV") == "production" {
if err := sharing.InitRepo(); err != nil {
log.Printf("git: failed to init repo: %v", err)
}
if err := sharing.InstallPostReceiveHook(); err != nil {
log.Printf("git: failed to install hook: %v", err)
}
}
// Git explorer routes
http.Handle("GET /git", app.Serve("git/index.html", nil))
http.Handle("GET /git/tree/{path...}", app.Serve("git/tree.html", nil))
http.Handle("GET /git/blob/{path...}", app.Serve("git/blob.html", nil))
http.Handle("GET /git/commits", app.Serve("git/commits.html", nil))
// HTTP git access (clone/fetch)
c.gitServer = gitkit.New(gitkit.Config{
Dir: "/var/git",
AutoCreate: false,
})
// Handle git HTTP protocol
http.HandleFunc("GET /git/readysite.git/", c.handleGit)
http.HandleFunc("POST /git/readysite.git/", c.handleGit)
http.HandleFunc("GET /git/readysite.git/info/refs", c.handleGit)
http.HandleFunc("POST /git/readysite.git/git-upload-pack", c.handleGit)
}
// handleGit proxies requests to gitkit for HTTP git protocol.
func (c *GitController) handleGit(w http.ResponseWriter, r *http.Request) {
// Only allow read operations (no push via HTTP)
if r.URL.Query().Get("service") == "git-receive-pack" {
http.Error(w, "Push not allowed via HTTP", http.StatusForbidden)
return
}
if strings.HasSuffix(r.URL.Path, "git-receive-pack") {
http.Error(w, "Push not allowed via HTTP", http.StatusForbidden)
return
}
// Strip /git prefix for gitkit (it expects paths like /readysite.git/...)
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/git")
if c.gitServer == nil {
http.Error(w, "Git server not initialized", http.StatusServiceUnavailable)
return
}
c.gitServer.ServeHTTP(w, r)
}
// Handle returns a request-scoped controller instance.
func (c GitController) Handle(r *http.Request) application.Controller {
c.Request = r
return &c
}
// Repo returns a git repository browser for the current request path.
// Use in templates: {{with $repo := git.Repo}}{{$repo.FileName}}{{end}}
func (c *GitController) Repo() *sharing.Repo {
return sharing.NewRepo(c.Host, c.PathValue("path"))
}