gshr
git static host repo -- generates static html for repos
git clone https://git.vogt.world/gshr.git
Log | Files | README.md | LICENSE
← All files
name: file.go
-rw-r--r--
2216
 1package main
 2
 3import (
 4	"fmt"
 5	"html/template"
 6	"io/fs"
 7	"os"
 8	"path"
 9	"path/filepath"
10	"strings"
11)
12
13type filePage struct {
14	RepoData       repoData
15	Mode           string
16	Name           string
17	Size           string
18	Origin         string
19	Extension      string
20	CanRender      bool
21	Destination    string
22	DestinationDir string
23	Content        template.HTML
24}
25
26func (f *filePage) renderPage(t *template.Template) {
27	debug("file %v %v", f.RepoData.Name, f.Name)
28	err := os.MkdirAll(f.DestinationDir, 0777)
29	checkErr(err)
30	err = os.MkdirAll(filepath.Dir(f.Destination), 0777)
31	checkErr(err)
32	output, err := os.Create(f.Destination)
33	checkErr(err)
34	err = t.Execute(output, f)
35	checkErr(err)
36}
37
38func renderIndividualFilePages(data repoData) {
39	t, err := template.ParseFS(htmlTemplates, "template.file.html", "template.partials.html")
40	checkErr(err)
41	err = filepath.Walk(data.cloneDir(), func(filename string, info fs.FileInfo, err error) error {
42		if info.IsDir() && info.Name() == ".git" {
43			return filepath.SkipDir
44		}
45
46		if !info.IsDir() {
47			ext := filepath.Ext(filename)
48			_, canRenderExtension := stt.TextExtensions[ext]
49			_, canRenderByFullName := stt.PlainFiles[filepath.Base(filename)]
50			canRender := canRenderExtension || canRenderByFullName
51			partialPath, _ := strings.CutPrefix(filename, data.cloneDir())
52			destDir := path.Join(args.OutputDir, data.Name, "files", partialPath)
53			outputName := path.Join(args.OutputDir, data.Name, "files", partialPath, "index.html")
54			var content template.HTML
55			info, err := os.Stat(filename)
56			checkErr(err)
57			if canRender {
58				fileBytes, err := os.ReadFile(filename)
59				checkErr(err)
60				fileStr := string(fileBytes)
61				highlighted := highlight(destDir, &fileStr)
62				checkErr(err)
63				content = template.HTML(highlighted)
64			}
65			(&filePage{
66				RepoData:       data,
67				Mode:           info.Mode().String(),
68				Size:           fmt.Sprintf("%v", info.Size()),
69				Name:           strings.TrimPrefix(partialPath, "/"),
70				Extension:      ext,
71				CanRender:      canRender,
72				Origin:         filename,
73				Destination:    outputName,
74				DestinationDir: destDir,
75				Content:        content,
76			}).renderPage(t)
77		}
78		return nil
79	})
80	checkErr(err)
81}