1package main
  2
  3import (
  4	"bytes"
  5	"context"
  6	"fmt"
  7	"html/template"
  8	"io"
  9	"os"
 10	"path/filepath"
 11	"runtime"
 12	"sort"
 13	"strings"
 14	"sync"
 15
 16	"github.com/alecthomas/chroma/v2"
 17	"github.com/alecthomas/chroma/v2/formatters/html"
 18	"github.com/alecthomas/chroma/v2/lexers"
 19	"github.com/alecthomas/chroma/v2/styles"
 20
 21	"github.com/antonmedv/gitmal/pkg/git"
 22	"github.com/antonmedv/gitmal/pkg/gitdiff"
 23	"github.com/antonmedv/gitmal/pkg/progress_bar"
 24	"github.com/antonmedv/gitmal/pkg/templates"
 25)
 26
 27// generate the stylesheet for a particular named style
 28func generateStyleCSS(w io.Writer, styleName string) error {
 29	style := styles.Get(styleName)
 30	if style == nil {
 31		return fmt.Errorf("unknown style: %s", styleName)
 32	}
 33
 34	formatter := html.New(
 35		html.WithClasses(true),
 36		html.WithAllClasses(true),
 37		html.WithCSSComments(false),
 38		html.WithCustomCSS(map[chroma.TokenType]string{
 39			chroma.GenericInserted: "display: block;",
 40			chroma.GenericDeleted:  "display: block;",
 41		}),
 42	)
 43
 44	if err := formatter.WriteCSS(w, style); err != nil {
 45		return err
 46	}
 47
 48	return nil
 49}
 50
 51func generateCommitsCSS(writer io.Writer, params Params) error {
 52
 53	if _, err := io.WriteString(writer, "@media screen and (prefers-color-scheme: light), print {\n"); err != nil {
 54		return err
 55	}
 56
 57	if err := generateStyleCSS(writer, params.LightStyle); err != nil {
 58		return err
 59	}
 60
 61	if _, err := io.WriteString(writer, "\n}\n@media screen and (prefers-color-scheme: dark) {\n"); err != nil {
 62		return err
 63	}
 64
 65	if err := generateStyleCSS(writer, params.DarkStyle); err != nil {
 66		return err
 67	}
 68
 69	if _, err := io.WriteString(writer, "\n}\n"); err != nil {
 70		return err
 71	}
 72
 73	return nil
 74}
 75
 76func generateCommits(commits map[string]git.Commit, params Params) error {
 77	outDir := filepath.Join(params.OutputDir, "commit")
 78	if err := os.MkdirAll(outDir, 0o755); err != nil {
 79		return err
 80	}
 81
 82	list := make([]git.Commit, 0, len(commits))
 83	for _, c := range commits {
 84		list = append(list, c)
 85	}
 86
 87	workers := runtime.NumCPU()
 88	if workers < 1 {
 89		workers = 1
 90	}
 91
 92	ctx, cancel := context.WithCancel(context.Background())
 93	defer cancel()
 94
 95	jobs := make(chan git.Commit)
 96	errCh := make(chan error, 1)
 97	var wg sync.WaitGroup
 98
 99	p := progress_bar.NewProgressBar("commits", len(list))
100
101	workerFn := func() {
102		defer wg.Done()
103		for {
104			select {
105			case <-ctx.Done():
106				return
107			case c, ok := <-jobs:
108				if !ok {
109					return
110				}
111				if err := generateCommitPage(c, params); err != nil {
112					select {
113					case errCh <- err:
114						cancel()
115					default:
116					}
117					return
118				}
119				p.Inc()
120			}
121		}
122	}
123
124	wg.Add(workers)
125	for i := 0; i < workers; i++ {
126		go workerFn()
127	}
128
129	go func() {
130		defer close(jobs)
131		for _, c := range list {
132			select {
133			case <-ctx.Done():
134				return
135			case jobs <- c:
136			}
137		}
138	}()
139
140	done := make(chan struct{})
141	go func() {
142		wg.Wait()
143		close(done)
144	}()
145
146	var err error
147	select {
148	case err = <-errCh:
149		cancel()
150		<-done
151	case <-done:
152	}
153
154	p.Done()
155	return err
156}
157
158func generateCommitPage(commit git.Commit, params Params) error {
159	diff, err := git.CommitDiff(commit.Hash, params.RepoDir)
160	if err != nil {
161		return err
162	}
163
164	files, _, err := gitdiff.Parse(strings.NewReader(diff))
165	if err != nil {
166		return err
167	}
168
169	style := styles.Get(params.LightStyle)
170	if style == nil {
171		return fmt.Errorf("unknown style: %s", params.LightStyle)
172	}
173
174	formatter := html.New(
175		html.WithClasses(true),
176		html.WithCSSComments(false),
177		html.WithCustomCSS(map[chroma.TokenType]string{
178			chroma.GenericInserted: "display: block;",
179			chroma.GenericDeleted:  "display: block;",
180		}),
181	)
182
183	lexer := lexers.Get("diff")
184	if lexer == nil {
185		return fmt.Errorf("failed to get lexer for diff")
186	}
187
188	outPath := filepath.Join(params.OutputDir, "commit", commit.Hash+".html")
189
190	f, err := os.Create(outPath)
191	if err != nil {
192		return err
193	}
194	rootHref := filepath.ToSlash("../")
195
196	fileTree := buildFileTree(files)
197
198	// Create a stable order for files that matches the file tree traversal
199	// so that the per-file views appear in the same order as the sidebar tree.
200	fileOrder := make(map[string]int)
201	{
202		// Preorder traversal (dirs first, then files), respecting sortNode ordering
203		var idx int
204		var walk func(nodes []*templates.FileTree)
205		walk = func(nodes []*templates.FileTree) {
206			for _, n := range nodes {
207				if n.IsDir {
208					// Children are already sorted by sortNode
209					walk(n.Children)
210					continue
211				}
212				if n.Path == "" {
213					continue
214				}
215				if _, ok := fileOrder[n.Path]; !ok {
216					fileOrder[n.Path] = idx
217					idx++
218				}
219			}
220		}
221		walk(fileTree)
222	}
223
224	// Prepare per-file views
225	var filesViews []templates.FileView
226	for _, f := range files {
227		path := f.NewName
228		if f.IsDelete {
229			path = f.OldName
230		}
231		if path == "" {
232			continue
233		}
234
235		var fileDiff strings.Builder
236		for _, frag := range f.TextFragments {
237			fileDiff.WriteString(frag.String())
238		}
239
240		it, err := lexer.Tokenise(nil, fileDiff.String())
241		if err != nil {
242			return err
243		}
244		var buf bytes.Buffer
245		if err := formatter.Format(&buf, style, it); err != nil {
246			return err
247		}
248
249		filesViews = append(filesViews, templates.FileView{
250			Path:       path,
251			OldName:    f.OldName,
252			NewName:    f.NewName,
253			IsNew:      f.IsNew,
254			IsDelete:   f.IsDelete,
255			IsRename:   f.IsRename,
256			IsBinary:   f.IsBinary,
257			HasChanges: f.TextFragments != nil,
258			HTML:       template.HTML(buf.String()),
259		})
260	}
261
262	// Sort file views to match the file tree order. If for some reason a path
263	// is missing in the order map (shouldn't happen), fall back to case-insensitive
264	// alphabetical order by full path.
265	sort.Slice(filesViews, func(i, j int) bool {
266		oi, iok := fileOrder[filesViews[i].Path]
267		oj, jok := fileOrder[filesViews[j].Path]
268		if iok && jok {
269			return oi < oj
270		}
271		if iok != jok {
272			return iok // known order first
273		}
274		return filesViews[i].Path < filesViews[j].Path
275	})
276
277	currentRef := params.DefaultRef
278	if !commit.Branch.IsEmpty() {
279		currentRef = commit.Branch
280	}
281
282	err = templates.CommitTemplate.ExecuteTemplate(f, "layout.gohtml", templates.CommitParams{
283		LayoutParams: templates.LayoutParams{
284			Title:         fmt.Sprintf("%s %s %s@%s", commit.Subject, dot, params.Name, commit.ShortHash),
285			Name:          params.Name,
286			RootHref:      rootHref,
287			CurrentRefDir: currentRef.DirName(),
288			Selected:      "commits",
289			AssetNames:    params.AssetNames,
290		},
291		Commit:    commit,
292		FileTree:  fileTree,
293		FileViews: filesViews,
294	})
295	if err != nil {
296		_ = f.Close()
297		return err
298	}
299	if err := f.Close(); err != nil {
300		return err
301	}
302	return nil
303}
304
305func buildFileTree(files []*gitdiff.File) []*templates.FileTree {
306	// Use a synthetic root (not rendered), collect top-level nodes in a map first.
307	root := &templates.FileTree{IsDir: true, Name: "", Path: "", Children: nil}
308
309	for _, f := range files {
310		path := f.NewName
311		if f.IsDelete {
312			path = f.OldName
313		}
314
315		path = filepath.ToSlash(strings.TrimPrefix(path, "./"))
316		if path == "" {
317			continue
318		}
319		parts := strings.Split(path, "/")
320
321		parent := root
322		accum := ""
323		if len(parts) > 1 {
324			for i := 0; i < len(parts)-1; i++ {
325				if accum == "" {
326					accum = parts[i]
327				} else {
328					accum = accum + "/" + parts[i]
329				}
330				parent = findOrCreateDir(parent, parts[i], accum)
331			}
332		}
333
334		fileName := parts[len(parts)-1]
335		node := &templates.FileTree{
336			Name:     fileName,
337			Path:     path,
338			IsDir:    false,
339			IsNew:    f.IsNew,
340			IsDelete: f.IsDelete,
341			IsRename: f.IsRename,
342			OldName:  f.OldName,
343			NewName:  f.NewName,
344		}
345		parent.Children = append(parent.Children, node)
346	}
347
348	sortNode(root)
349	return root.Children
350}
351
352func findOrCreateDir(parent *templates.FileTree, name, path string) *templates.FileTree {
353	for _, ch := range parent.Children {
354		if ch.IsDir && ch.Name == name {
355			return ch
356		}
357	}
358	node := &templates.FileTree{IsDir: true, Name: name, Path: path}
359	parent.Children = append(parent.Children, node)
360	return node
361}
362
363func sortNode(n *templates.FileTree) {
364	if len(n.Children) == 0 {
365		return
366	}
367	sort.Slice(n.Children, func(i, j int) bool {
368		a, b := n.Children[i], n.Children[j]
369		if a.IsDir != b.IsDir {
370			return a.IsDir && !b.IsDir // dirs first
371		}
372		return strings.ToLower(a.Name) < strings.ToLower(b.Name)
373	})
374	for _, ch := range n.Children {
375		if ch.IsDir {
376			sortNode(ch)
377		}
378	}
379}