package pgit import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "os" "path/filepath" "github.com/alecthomas/chroma/v2" "github.com/tdewolff/minify/v2" "github.com/tdewolff/minify/v2/css" ) func Style(theme chroma.Style) string { bg := theme.Get(chroma.Background) txt := theme.Get(chroma.Text) kw := theme.Get(chroma.Keyword) nv := theme.Get(chroma.NameVariable) cm := theme.Get(chroma.Comment) return fmt.Sprintf(`:root { --bg-color: %s; --text-color: %s; --border: %s; --link-color: %s; --hover: %s; --visited: %s; }`, bg.Background.String(), txt.Colour.String(), cm.Colour.String(), nv.Colour.String(), kw.Colour.String(), nv.Colour.String(), ) } func (c *Config) BundleCSS() (string, error) { c.Logger.Info("bundling CSS files") m := minify.New() m.AddFunc("text/css", css.Minify) var buf bytes.Buffer pgitCSS, err := StaticFS.ReadFile("static/pgit.css") if err != nil { return "", fmt.Errorf("failed to read pgit.css: %w", err) } buf.Write(pgitCSS) buf.WriteString("\n") varsCSS := Style(*c.Theme) buf.WriteString(varsCSS) buf.WriteString("\n") var syntaxBuf bytes.Buffer err = c.Formatter.WriteCSS(&syntaxBuf, c.Theme) if err != nil { return "", fmt.Errorf("failed to generate syntax.css: %w", err) } buf.Write(syntaxBuf.Bytes()) minified, err := m.Bytes("text/css", buf.Bytes()) if err != nil { return "", fmt.Errorf("failed to minify CSS: %w", err) } hash := sha256.Sum256(minified) hashStr := hex.EncodeToString(hash[:8]) filename := fmt.Sprintf("styles.%s.css", hashStr) outPath := filepath.Join(c.Outdir, filename) err = os.WriteFile(outPath, minified, 0644) if err != nil { return "", fmt.Errorf("failed to write CSS bundle: %w", err) } c.Logger.Info("CSS bundle created", "filename", filename, "size", len(minified)) return filename, nil }