gitshow

Log | Files | Refs

repo.go (1464B)


      1 package main
      2 import (
      3 	"github.com/gorilla/mux"
      4 	"log"
      5 	"net/http"
      6 	"path/filepath"
      7 	"github.com/go-git/go-git/v5/plumbing"
      8 	"html/template"
      9 )
     10 
     11 type RepoPageData struct {
     12 	Name string
     13 	Refname string
     14 	Readme string
     15 }
     16 
     17 func getRepo(w http.ResponseWriter, r *http.Request) {
     18 	logger := log.Default()
     19 	vars := mux.Vars(r)
     20 	reponame := vars["repository"]
     21 
     22 	repo, err := checkRepo(reponame)
     23 
     24 	if err != nil {
     25 		w.WriteHeader(http.StatusNotFound)
     26 		return
     27 	}
     28 
     29 	head, err := repo.Head()
     30 	if err != nil {
     31 		// TODO: handle no head
     32 		w.WriteHeader(http.StatusInternalServerError)
     33 		return
     34 	}
     35 
     36 	hash, err := repo.ResolveRevision(plumbing.Revision(head.Strings()[0]))
     37 	if err != nil {
     38 		logger.Fatal(err)
     39 	}
     40 
     41 	commit, err := repo.CommitObject(*hash)
     42 	if err != nil {
     43 		logger.Fatal(err)
     44 	}
     45 
     46 	readmef, err := commit.File("README")
     47 
     48 	isbinary, err := readmef.IsBinary()
     49 	if err != nil {
     50 		logger.Fatal(err)
     51 	}
     52 
     53 	var readme string
     54 	if err != nil || isbinary {
     55 		readme = "No readme"
     56 	} else {
     57 		readme, err = readmef.Contents()
     58 		if err != nil {
     59 			logger.Fatal(err)
     60 		}
     61 	}
     62 
     63 	w.WriteHeader(http.StatusOK)
     64 	
     65 	tmpl := template.Must(template.ParseFiles(
     66 		filepath.Join("templates", "repo.html"),
     67 		filepath.Join("templates", "wrap.html"),
     68 	))
     69 
     70 	_, ishtmx := r.Header["Hx-Request"]
     71 
     72 	data :=  RepoPageData {
     73 		Name: reponame,
     74 		Refname: head.Name().Short(),
     75 		Readme: readme,
     76 	}
     77 
     78 	if ishtmx {
     79 		tmpl.ExecuteTemplate(w, "repo_content", data)
     80 	} else {
     81 		tmpl.Execute(w, data)
     82 	} 
     83 }