Home

blog @2ce45f7862a29f85da5708052aeeacfcd5406b4e - refs - log -
-
https://git.jolheiser.com/blog.git
My nonexistent blog
blog / main.go
- raw
  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
//go:generate templ generate
//go:generate go run .
package main

import (
	"context"
	"embed"
	"flag"
	"fmt"
	iofs "io/fs"
	"os"
	"path/filepath"

	"github.com/alecthomas/chroma/v2/styles"
)

//go:embed articles/*
var articleFS embed.FS

func maine() error {
	fs := flag.NewFlagSet("blog", flag.ExitOnError)
	outFlag := fs.String("out", "out", "Output directory")
	fs.StringVar(outFlag, "o", *outFlag, "--out")
	if err := fs.Parse(os.Args[1:]); err != nil {
		return err
	}

	files, err := articleFS.ReadDir("articles")
	if err != nil {
		return err
	}

	articles := make(Articles)
	for _, file := range files {
		if filepath.Ext(file.Name()) != ".md" {
			continue
		}
		content, err := iofs.ReadFile(articleFS, fmt.Sprintf("articles/%s", file.Name()))
		if err != nil {
			return err
		}
		article, err := Parse(string(content))
		if err != nil {
			return err
		}
		articles[article.Category] = append(articles[article.Category], article)
		if err := writeArticle(*outFlag, article); err != nil {
			return err
		}
	}

	if err := writeCSS(*outFlag); err != nil {
		return err
	}

	fi, err := os.Create(filepath.Join(*outFlag, "index.html"))
	if err != nil {
		return err
	}
	defer fi.Close()

	return IndexTemplate(articles).Render(context.Background(), fi)
}

func writeArticle(out string, article Article) error {
	dest := filepath.Join(out, article.Slug(), "index.html")
	if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
		return err
	}

	fi, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer fi.Close()

	return ArticleTemplate(article).Render(context.Background(), fi)
}

func writeCSS(out string) error {
	fi, err := os.Create(filepath.Join(out, "chroma.css"))
	if err != nil {
		return err
	}
	defer fi.Close()

	if err := CSS.WriteCSS(fi, styles.Get("catpuccin-latte")); err != nil {
		return err
	}
	fi.WriteString("@media (prefers-color-scheme: dark) {")
	if err := CSS.WriteCSS(fi, styles.Get("catppuccin-mocha")); err != nil {
		return err
	}
	fi.WriteString("}")
	return nil
}

func main() {
	if err := maine(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}