summaryrefslogtreecommitdiff
path: root/internal/generator/branches.go
blob: ec3b188b02bc7a4f8a679ee65c9bfb2f3528291f (plain)
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
package generator

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"

	"mokhan.ca/xlgmokha/gitmal/internal/git"
	"mokhan.ca/xlgmokha/gitmal/internal/templates"
)

func GenerateBranches(branches []git.Ref, defaultBranch string, params Params) error {
	outDir := params.OutputDir
	if err := os.MkdirAll(outDir, 0o755); err != nil {
		return err
	}

	entries := make([]templates.BranchEntry, 0, len(branches))
	for _, b := range branches {
		entries = append(entries, templates.BranchEntry{
			Name:        b.String(),
			Href:        filepath.ToSlash(filepath.Join("blob", b.DirName()) + "/index.html"),
			IsDefault:   b.String() == defaultBranch,
			CommitsHref: filepath.ToSlash(filepath.Join("commits", b.DirName(), "index.html")),
		})
	}

	// Ensure default branch is shown at the top of the list.
	// Keep remaining branches sorted alphabetically for determinism.
	sort.SliceStable(entries, func(i, j int) bool {
		if entries[i].IsDefault != entries[j].IsDefault {
			return entries[i].IsDefault && !entries[j].IsDefault
		}
		return entries[i].Name < entries[j].Name
	})

	f, err := os.Create(filepath.Join(outDir, "branches.html"))
	if err != nil {
		return err
	}
	defer f.Close()

	// RootHref from root page is just ./
	rootHref := "./"

	err = templates.BranchesTemplate.ExecuteTemplate(f, "layout.gohtml", templates.BranchesParams{
		LayoutParams: templates.LayoutParams{
			Title:         fmt.Sprintf("Branches %s %s", Dot, params.Name),
			Name:          params.Name,
			RootHref:      rootHref,
			CurrentRefDir: params.DefaultRef.DirName(),
			Selected:      "branches",
		},
		Branches: entries,
	})
	if err != nil {
		return err
	}

	return nil
}