generate.go

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package gen

import (
	"bytes"
	"fmt"
	"html/template"
	"os/exec"
	"senary/common"
	"slices"

	htmlform "github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/alecthomas/chroma/v2/lexers"
	"github.com/alecthomas/chroma/v2/styles"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"os"
	"path/filepath"
	"strings"
)

type StaticBase struct {
	User common.AuthInfo
	Repo string
}

type StaticDirListing struct {
	StaticBase
	Path     string
	DirName  string
	Contents []FileEntry
	Commit   string
}

type StaticCommitListing struct {
	StaticBase
	Commits []StaticCommit
}

type StaticCommit struct {
	Hash    string
	Author  string
	Message string
	Date    string
}

type StaticListing struct {
	StaticBase
	FileName string
	Contents template.HTML
}

func GenerateRepoPages(config *common.Config, repo string) error {

	r, err := git.PlainOpen(repo)
	if err != nil {
		return err
	}

	headRef, err := r.Head()
	if err != nil {
		fmt.Printf("could not find head\n")
		return err
	}

	commit, err := r.CommitObject(headRef.Hash())
	if err != nil {
		return err
	}

	tree, err := commit.Tree()
	if err != nil {
		return err
	}

	WalkDir(config, repo, "", r, tree)

	tree.Files().ForEach(func(f *object.File) error {
		//fmt.Printf("file: %v\n", f.Name)
		staticPath := filepath.Join(config.RepoDir, filepath.Base(repo), "tree", f.Name)
		dir := filepath.Dir(staticPath)
		os.MkdirAll(dir, 0755)
		if !f.Mode.IsFile() {

		} else {
			if binary, _ := f.IsBinary(); binary {

			} else {
				data, _ := f.Contents()

				file, _ := os.Create(staticPath + ".html")
				defer file.Close()

				langLexer := lexers.Match(f.Name)
				if langLexer == nil {
					langLexer = lexers.Analyse(data)
					if langLexer == nil {
						langLexer = lexers.Fallback
					}
				}
				style := styles.Get("tokyonight-moon")
				if style == nil {
					style = styles.Fallback
				}
				formatter := htmlform.New(htmlform.Standalone(false), htmlform.LineNumbersInTable(true), htmlform.WithLineNumbers(true), htmlform.WithLinkableLineNumbers(true, ""))

				iterator, err := langLexer.Tokenise(nil, string(strings.TrimSpace(data)))
				var doc bytes.Buffer
				formatter.Format(&doc, style, iterator)
				// lines := strings.Split(doc.String(), "\n")
				// htmlLines := []template.HTML{}
				// for _, line := range lines {
				// 	htmlLines = append(htmlLines, template.HTML(line))
				// }

				config.Templates.ExecuteTemplate(file, "listing.tpl.html", StaticListing{StaticBase: StaticBase{Repo: filepath.Base(repo)}, FileName: f.Name, Contents: template.HTML(doc.String())})
				if err != nil {
					fmt.Printf("[error] %v\n", err)
				}
				fmt.Printf("Written %v\n", staticPath)

				if strings.HasSuffix(staticPath, "tree/README.md") {
					fmt.Printf("Writing Index\n")
					staticPath := filepath.Join(config.RepoDir, filepath.Base(repo), "index")
					dir := filepath.Dir(staticPath)
					os.MkdirAll(dir, 0755)
					file, _ := os.Create(staticPath + ".html")
					defer file.Close()
					config.Templates.ExecuteTemplate(file, "listing.tpl.html", StaticListing{StaticBase: StaticBase{Repo: filepath.Base(repo)}, FileName: f.Name, Contents: template.HTML(doc.String())})
				}

			}
		}
		return nil
	})

	staticCommits := []StaticCommit{}
	commits, _ := r.Log(&git.LogOptions{})
	commits.ForEach(func(c *object.Commit) error {
		staticCommits = append(staticCommits, StaticCommit{Hash: c.Hash.String(),
			Author:  c.Author.String(),
			Message: strings.Split(c.Message, "\n")[0],
			Date:    c.Committer.When.Local().Format("2006-02-01 15:04")})
		return nil
	})

	staticPath := filepath.Join(config.RepoDir, filepath.Base(repo), "commits", "index")
	dir := filepath.Dir(staticPath)
	os.MkdirAll(dir, 0755)
	file, _ := os.Create(staticPath + ".html")
	defer file.Close()
	config.Templates.ExecuteTemplate(file, "commits.tpl.html", StaticCommitListing{StaticBase: StaticBase{Repo: filepath.Base(repo)}, Commits: staticCommits})

	return nil

}

func MakeStaticDirListing(config *common.Config, repoBase string, dirpath string, entries []FileEntry) {
	staticPath := filepath.Join(config.RepoDir, repoBase, "tree", dirpath)
	dir := filepath.Dir(staticPath)
	os.MkdirAll(dir, 0755)

	slices.SortFunc(entries, func(a FileEntry, b FileEntry) int {
		if a.Dir && !b.Dir {
			return -1
		} else if b.Dir && !a.Dir {
			return 1
		}
		return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
	})

	fmt.Printf("writing index for %v\n", dirpath)
	file, _ := os.Create(filepath.Join(staticPath, "index.html"))
	defer file.Close()
	config.Templates.ExecuteTemplate(file, "dir.include.tpl.html", StaticDirListing{StaticBase: StaticBase{Repo: filepath.Base(repoBase)}, Path: dirpath, DirName: dirpath, Contents: entries})
}

type FileEntry struct {
	Dir     bool
	Name    string
	Path    string
	Message string
	Date    string
}

func WalkDir(config *common.Config, repopath string, toplevel string, repo *git.Repository, tree *object.Tree) {
	tw := object.NewTreeWalker(tree, false, make(map[plumbing.Hash]bool))
	defer tw.Close()
	dirListing := []FileEntry{}
	for {

		if _, entry, err := tw.Next(); err != nil {
			break
		} else {
			pathname := filepath.Join(toplevel, entry.Name)
			if !entry.Mode.IsFile() {

				subtree, err := tree.Tree(entry.Name)
				if err == nil {
					WalkDir(config, repopath, pathname, repo, subtree)
				}
			}

			dirListing = append(dirListing, FileEntry{Dir: !entry.Mode.IsFile(), Name: entry.Name, Path: pathname})
		}
	}

	fmt.Printf("checking %v\n", toplevel)

	if len(dirListing) > 100 {

	} else {
		for i, ls := range dirListing {
			commithash := LastestCommitHashFromFile(repopath, ls.Path)
			commit, _ := repo.CommitObject(commithash)
			fmt.Printf("got %v %v\n", ls.Path, commithash)
			firstLine := strings.Split(commit.Message, "\n")
			dirListing[i].Message = firstLine[0]
			dirListing[i].Date = commit.Author.When.Local().Format("2006-02-01 15:04")
		}
	}

	MakeStaticDirListing(config, filepath.Base(repopath), toplevel, dirListing)
}

func LastestCommitHashFromFile(repopath string, filepath string) plumbing.Hash {
	cmd := exec.Command("git", "log", "-n", "1", filepath)
	cmd.Dir = repopath
	output, _ := cmd.Output()
	lines := strings.Split(string(output), "\n")
	str := strings.Split(lines[0], " ")[1]
	return plumbing.NewHash(str)
}