gitshow

Log | Files | Refs

tree.go (1927B)


      1 package main
      2 
      3 import (
      4 	"github.com/gorilla/mux"
      5 	// "fmt"
      6 	// "github.com/libgit2/git2go/v31"
      7 	"html/template"
      8 	"log"
      9 	"github.com/go-git/go-git/v5/plumbing/object"
     10 	"github.com/go-git/go-git/v5/plumbing"
     11 	"net/http"
     12 	"path/filepath"
     13 )
     14 
     15 type TreePageData struct {
     16 	Name    string
     17 	Ref string
     18 	Entries []object.TreeEntry
     19 }
     20 
     21 func getTree(w http.ResponseWriter, r *http.Request) {
     22 	logger := log.Default()
     23 	vars := mux.Vars(r)
     24 	reponame := vars["repository"]
     25 
     26 	repo, err := checkRepo(reponame)
     27 	if err != nil {
     28 		w.WriteHeader(http.StatusNotFound)
     29 		return
     30 	}
     31 
     32 	var revstr string
     33 	revstr, present := vars["ref"]
     34 
     35 	if !present {
     36 		head, err := repo.Head()
     37 		if err != nil {
     38 			// TODO: handle no head
     39 			w.WriteHeader(http.StatusInternalServerError)
     40 			return
     41 		}
     42 		revstr = head.Name().String()
     43 	}
     44 
     45 	logger.Printf("In repo %s, search for %s", reponame, revstr)
     46 
     47 	hash, err := repo.ResolveRevision(plumbing.Revision(revstr))
     48 	if err != nil {
     49 		w.WriteHeader(http.StatusNotFound)
     50 		return
     51 	}
     52 
     53 	commit, err := repo.CommitObject(*hash)
     54 	if err != nil {
     55 		logger.Fatal(err)
     56 	}
     57 	logger.Printf("Called %s: ref to %s", revstr, commit.Hash.String())
     58 
     59 	tree, err := commit.Tree()
     60 	if err != nil {
     61 		logger.Fatalf("Could not get tree")
     62 	}
     63 
     64 	// url, err := reporouter.Get("tree").URL("repository", reponame, "ref", commit.Hash.String())
     65 	// if err != nil {
     66 	// 	logger.Fatalf("Could not generate URL")
     67 	// }
     68 
     69 	w.WriteHeader(http.StatusOK)
     70 
     71 	tmpl := template.Must(template.New("tree_root").Funcs(template.FuncMap{
     72 		"isFile": func(obj *object.TreeEntry) bool {
     73 			return obj.Mode.IsFile()
     74 		},
     75 	}).ParseFiles(
     76 		filepath.Join("templates", "tree.html"),
     77 		filepath.Join("templates", "wrap.html"),
     78 	))
     79 
     80 	_, ishtmx := r.Header["Hx-Request"]
     81 
     82 	data := TreePageData{
     83 		Name:    reponame,
     84 		Entries: tree.Entries,
     85 		Ref:  commit.Hash.String(),
     86 	}
     87 
     88 	if ishtmx {
     89 		tmpl.ExecuteTemplate(w, "tree_content", data)
     90 	} else {
     91 		tmpl.Execute(w, data)
     92 	}
     93 }