main
 1package generator
 2
 3import (
 4	"fmt"
 5	"os"
 6	"path/filepath"
 7	"sort"
 8
 9	"mokhan.ca/xlgmokha/gitmal/internal/git"
10	"mokhan.ca/xlgmokha/gitmal/internal/templates"
11)
12
13func GenerateBranches(branches []git.Ref, defaultBranch string, params Params) error {
14	outDir := params.OutputDir
15	if err := os.MkdirAll(outDir, 0o755); err != nil {
16		return err
17	}
18
19	entries := make([]templates.BranchEntry, 0, len(branches))
20	for _, b := range branches {
21		entries = append(entries, templates.BranchEntry{
22			Name:        b.String(),
23			Href:        filepath.ToSlash(filepath.Join("blob", b.DirName()) + "/index.html"),
24			IsDefault:   b.String() == defaultBranch,
25			CommitsHref: filepath.ToSlash(filepath.Join("commits", b.DirName(), "index.html")),
26		})
27	}
28
29	// Ensure default branch is shown at the top of the list.
30	// Keep remaining branches sorted alphabetically for determinism.
31	sort.SliceStable(entries, func(i, j int) bool {
32		if entries[i].IsDefault != entries[j].IsDefault {
33			return entries[i].IsDefault && !entries[j].IsDefault
34		}
35		return entries[i].Name < entries[j].Name
36	})
37
38	f, err := os.Create(filepath.Join(outDir, "branches.html"))
39	if err != nil {
40		return err
41	}
42	defer f.Close()
43
44	// RootHref from root page is just ./
45	rootHref := "./"
46
47	err = templates.BranchesTemplate.ExecuteTemplate(f, "layout.gohtml", templates.BranchesParams{
48		LayoutParams: templates.LayoutParams{
49			Title:         fmt.Sprintf("Branches %s %s", Dot, params.Name),
50			Name:          params.Name,
51			RootHref:      rootHref,
52			CurrentRefDir: params.DefaultRef.DirName(),
53			Selected:      "branches",
54			Year:          currentYear(),
55		},
56		Branches: entries,
57	})
58	if err != nil {
59		return err
60	}
61
62	return nil
63}