aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <hello@eugenetriguba.com>2025-12-27 06:44:59 -0500
committerEugene Triguba <hello@eugenetriguba.com>2025-12-27 06:44:59 -0500
commit93670740c05def63ae4b02c99eb49391f663ff38 (patch)
tree77bbd8d664622154155fc06e2c4228cfac4fec04
parentAdd license (diff)
downloadssg-93670740c05def63ae4b02c99eb49391f663ff38.zip
Add initial version of ssg
-rw-r--r--.build.yml9
-rw-r--r--.gitignore6
-rw-r--r--CHANGELOG.md9
-rw-r--r--Makefile38
-rw-r--r--build.go53
-rw-r--r--filter.go39
-rw-r--r--filter_test.go93
-rw-r--r--go.mod10
-rw-r--r--go.sum6
-rw-r--r--init.go59
-rw-r--r--main.go26
-rw-r--r--man/ssg-build.159
-rw-r--r--man/ssg-help.132
-rw-r--r--man/ssg-init.145
-rw-r--r--man/ssg-serve.145
-rw-r--r--man/ssg-templates.583
-rw-r--r--man/ssg-version.111
-rw-r--r--man/ssg.150
-rw-r--r--serve.go32
-rw-r--r--site.go166
-rw-r--r--site_test.go222
-rw-r--r--version.go21
22 files changed, 1114 insertions, 0 deletions
diff --git a/.build.yml b/.build.yml
new file mode 100644
index 0000000..88d025d
--- /dev/null
+++ b/.build.yml
@@ -0,0 +1,9 @@
+image: alpine/edge
+packages:
+ - go
+sources:
+ - https://git.sr.ht/~eugenetriguba/ssg
+tasks:
+ - test: |
+ cd ssg
+ go test -v ./...
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b9b84cf
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+# Build
+/ssg
+/dist
+
+# macOS
+.DS_Store
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..25ed73c
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,9 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..d76913d
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,38 @@
+PREFIX ?= /usr/local
+BINDIR ?= $(PREFIX)/bin
+MANDIR ?= $(PREFIX)/share/man
+
+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
+
+.PHONY: all build install uninstall clean
+
+all: build
+
+build:
+ go build -ldflags "-X main.version=$(VERSION)" -o ssg
+
+install: build
+ install -d $(DESTDIR)$(BINDIR)
+ install -m 755 ssg $(DESTDIR)$(BINDIR)/
+ install -d $(DESTDIR)$(MANDIR)/man1
+ install -m 644 man/ssg.1 $(DESTDIR)$(MANDIR)/man1/
+ install -m 644 man/ssg-build.1 $(DESTDIR)$(MANDIR)/man1/
+ install -m 644 man/ssg-serve.1 $(DESTDIR)$(MANDIR)/man1/
+ install -m 644 man/ssg-init.1 $(DESTDIR)$(MANDIR)/man1/
+ install -m 644 man/ssg-version.1 $(DESTDIR)$(MANDIR)/man1/
+ install -m 644 man/ssg-help.1 $(DESTDIR)$(MANDIR)/man1/
+ install -d $(DESTDIR)$(MANDIR)/man5
+ install -m 644 man/ssg-templates.5 $(DESTDIR)$(MANDIR)/man5/
+
+uninstall:
+ rm -f $(DESTDIR)$(BINDIR)/ssg
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg.1
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg-build.1
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg-serve.1
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg-init.1
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg-version.1
+ rm -f $(DESTDIR)$(MANDIR)/man1/ssg-help.1
+ rm -f $(DESTDIR)$(MANDIR)/man5/ssg-templates.5
+
+clean:
+ rm -f ssg
diff --git a/build.go b/build.go
new file mode 100644
index 0000000..37f8a1d
--- /dev/null
+++ b/build.go
@@ -0,0 +1,53 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+
+ "git.sr.ht/~eugenetriguba/subcmd"
+)
+
+type buildCmd struct {
+ dataDir string
+ templatesDir string
+ staticDir string
+ outDir string
+ quiet bool
+}
+
+func (c *buildCmd) Name() string { return "build" }
+func (c *buildCmd) Synopsis() string { return "build the site" }
+
+func (c *buildCmd) Usage() string {
+ return "build [options]\n\nSee ssg-build(1) for details.\n"
+}
+
+func (c *buildCmd) SetFlags(f *flag.FlagSet) {
+ f.StringVar(&c.dataDir, "data", "data", "")
+ f.StringVar(&c.templatesDir, "templates", "templates", "")
+ f.StringVar(&c.staticDir, "static", "static", "")
+ f.StringVar(&c.outDir, "out", "dist", "")
+ f.BoolVar(&c.quiet, "q", false, "")
+}
+
+func (c *buildCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
+ site := &Site{
+ DataDir: c.dataDir,
+ TemplatesDir: c.templatesDir,
+ StaticDir: c.staticDir,
+ OutDir: c.outDir,
+ }
+
+ if !c.quiet {
+ site.Log = func(format string, a ...any) {
+ fmt.Printf(format+"\n", a...)
+ }
+ }
+
+ if err := site.Build(); err != nil {
+ fatal("%v", err)
+ }
+
+ return subcmd.ExitSuccess
+}
diff --git a/filter.go b/filter.go
new file mode 100644
index 0000000..48f3e67
--- /dev/null
+++ b/filter.go
@@ -0,0 +1,39 @@
+package main
+
+import "reflect"
+
+// filterFunc returns items from a slice where the given field equals the value.
+// Template usage: {{range filter .posts "draft" false}}
+func filterFunc(items any, field string, value any) []any {
+ var result []any
+
+ rv := reflect.ValueOf(items)
+ if rv.Kind() != reflect.Slice {
+ return result
+ }
+
+ for i := 0; i < rv.Len(); i++ {
+ item := rv.Index(i)
+ if item.Kind() == reflect.Interface {
+ item = item.Elem()
+ }
+
+ var fieldVal any
+ switch item.Kind() {
+ case reflect.Map:
+ if v := item.MapIndex(reflect.ValueOf(field)); v.IsValid() {
+ fieldVal = v.Interface()
+ }
+ case reflect.Struct:
+ if f := item.FieldByName(field); f.IsValid() {
+ fieldVal = f.Interface()
+ }
+ }
+
+ if reflect.DeepEqual(fieldVal, value) {
+ result = append(result, item.Interface())
+ }
+ }
+
+ return result
+}
diff --git a/filter_test.go b/filter_test.go
new file mode 100644
index 0000000..736b9fc
--- /dev/null
+++ b/filter_test.go
@@ -0,0 +1,93 @@
+package main
+
+import (
+ "testing"
+
+ "git.sr.ht/~eugenetriguba/checkmate/assert"
+)
+
+func TestFilterFunc_MapsByBoolField(t *testing.T) {
+ items := []map[string]any{
+ {"title": "Post 1", "draft": false},
+ {"title": "Post 2", "draft": true},
+ {"title": "Post 3", "draft": false},
+ }
+
+ got := filterFunc(items, "draft", false)
+
+ assert.Equal(t, len(got), 2)
+ assert.DeepEqual(t, got[0], map[string]any{"title": "Post 1", "draft": false})
+ assert.DeepEqual(t, got[1], map[string]any{"title": "Post 3", "draft": false})
+}
+
+func TestFilterFunc_MapsByStringField(t *testing.T) {
+ items := []map[string]any{
+ {"title": "Post 1", "category": "tech"},
+ {"title": "Post 2", "category": "news"},
+ {"title": "Post 3", "category": "tech"},
+ }
+
+ got := filterFunc(items, "category", "tech")
+
+ assert.Equal(t, len(got), 2)
+ assert.DeepEqual(t, got[0], map[string]any{"title": "Post 1", "category": "tech"})
+ assert.DeepEqual(t, got[1], map[string]any{"title": "Post 3", "category": "tech"})
+}
+
+func TestFilterFunc_NoMatches(t *testing.T) {
+ items := []map[string]any{
+ {"title": "Post 1", "category": "tech"},
+ }
+
+ got := filterFunc(items, "category", "news")
+
+ assert.Equal(t, len(got), 0)
+}
+
+func TestFilterFunc_MissingField(t *testing.T) {
+ items := []map[string]any{
+ {"title": "Post 1"},
+ {"title": "Post 2", "draft": false},
+ }
+
+ got := filterFunc(items, "draft", false)
+
+ assert.Equal(t, len(got), 1)
+ assert.DeepEqual(t, got[0], map[string]any{"title": "Post 2", "draft": false})
+}
+
+func TestFilterFunc_EmptySlice(t *testing.T) {
+ items := []map[string]any{}
+ got := filterFunc(items, "draft", false)
+ assert.Equal(t, len(got), 0)
+}
+
+func TestFilterFunc_NonSliceInput(t *testing.T) {
+ got := filterFunc("not a slice", "field", "value")
+ assert.Equal(t, len(got), 0)
+}
+
+func TestFilterFunc_NilInput(t *testing.T) {
+ got := filterFunc(nil, "field", "value")
+ assert.Equal(t, len(got), 0)
+}
+
+func TestFilterFunc_Structs(t *testing.T) {
+ type Post struct {
+ Title string
+ Draft bool
+ }
+ items := []Post{
+ {Title: "Post 1", Draft: false},
+ {Title: "Post 2", Draft: true},
+ {Title: "Post 3", Draft: false},
+ }
+
+ got := filterFunc(items, "Draft", false)
+
+ assert.Equal(t, len(got), 2)
+ post1 := got[0].(Post)
+ post2 := got[1].(Post)
+ assert.Equal(t, post1.Title, "Post 1")
+ assert.Equal(t, post2.Title, "Post 3")
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..6bdb531
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,10 @@
+module git.sr.ht/~eugenetriguba/ssg
+
+go 1.25.5
+
+require (
+ git.sr.ht/~eugenetriguba/checkmate v0.5.0
+ git.sr.ht/~eugenetriguba/subcmd v0.4.0
+)
+
+require github.com/google/go-cmp v0.6.0 // indirect
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..98bd965
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,6 @@
+git.sr.ht/~eugenetriguba/checkmate v0.5.0 h1:6AuloFbKgXCsEA7h4mOa8sdGaepKHSlegzHY9QMPmXU=
+git.sr.ht/~eugenetriguba/checkmate v0.5.0/go.mod h1:Pxv1PKcBSbOqmoEOZxOBJVv9dHUGU+zcwuwfnGqZEQk=
+git.sr.ht/~eugenetriguba/subcmd v0.4.0 h1:af3rDsbrDDS9Z/u9CHH/1VQOQf46FXrhV41o5TT9xYo=
+git.sr.ht/~eugenetriguba/subcmd v0.4.0/go.mod h1:esfBef99WFG9yXM9DLgmHVK0CGKzBPu/SAxrC1aPQQI=
+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
diff --git a/init.go b/init.go
new file mode 100644
index 0000000..46b2fc9
--- /dev/null
+++ b/init.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "git.sr.ht/~eugenetriguba/subcmd"
+)
+
+type initCmd struct{}
+
+func (c *initCmd) Name() string { return "init" }
+func (c *initCmd) Synopsis() string { return "initialize a new site" }
+func (c *initCmd) Usage() string {
+ return "init [directory]\n\nSee ssg-init(1) for details.\n"
+}
+func (c *initCmd) SetFlags(f *flag.FlagSet) {}
+func (c *initCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
+ dir := "."
+ if f.NArg() > 0 {
+ dir = f.Arg(0)
+ }
+
+ dirs := []string{
+ filepath.Join(dir, "data"),
+ filepath.Join(dir, "templates"),
+ filepath.Join(dir, "static"),
+ }
+
+ for _, d := range dirs {
+ if err := os.MkdirAll(d, 0755); err != nil {
+ fatal("creating %s: %v", d, err)
+ }
+ fmt.Println(d + "/")
+ }
+
+ indexPath := filepath.Join(dir, "templates", "index.html")
+ if _, err := os.Stat(indexPath); os.IsNotExist(err) {
+ index := `<!doctype html>
+<html>
+ <head>
+ <title>My Site</title>
+ </head>
+ <body>
+ <h1>Hello, world!</h1>
+ </body>
+</html>
+`
+ if err := os.WriteFile(indexPath, []byte(index), 0644); err != nil {
+ fatal("creating index.html: %v", err)
+ }
+ fmt.Println("templates/index.html")
+ }
+
+ return subcmd.ExitSuccess
+}
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..8b83f62
--- /dev/null
+++ b/main.go
@@ -0,0 +1,26 @@
+// ssg - a tiny static site generator
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "os"
+
+ "git.sr.ht/~eugenetriguba/subcmd"
+)
+
+func main() {
+ subcmd.Register(&buildCmd{}, "")
+ subcmd.Register(&serveCmd{}, "")
+ subcmd.Register(&initCmd{}, "")
+ subcmd.Register(&versionCmd{}, "")
+ subcmd.Register(subcmd.ManHelpCommand("ssg"), "")
+ flag.Parse()
+ os.Exit(int(subcmd.Execute(context.Background())))
+}
+
+func fatal(format string, args ...any) {
+ fmt.Fprintf(os.Stderr, "ssg: "+format+"\n", args...)
+ os.Exit(1)
+}
diff --git a/man/ssg-build.1 b/man/ssg-build.1
new file mode 100644
index 0000000..0ba504f
--- /dev/null
+++ b/man/ssg-build.1
@@ -0,0 +1,59 @@
+.TH SSG-BUILD 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg-build \- build the site
+.SH SYNOPSIS
+.B ssg build
+.RI [ options ]
+.SH DESCRIPTION
+Build the static site by rendering templates with data and copying static files.
+.PP
+Templates are processed using Go's html/template package. See
+.BR ssg-templates (5)
+for template syntax and available functions.
+.SH OPTIONS
+.TP
+.BI \-data " dir"
+Data directory containing JSON files. Default: data
+.TP
+.BI \-templates " dir"
+Templates directory containing HTML files. Default: templates
+.TP
+.BI \-static " dir"
+Static files directory. Default: static
+.TP
+.BI \-out " dir"
+Output directory. Default: dist
+.TP
+.B \-q
+Quiet mode. Only show errors.
+.SH EXAMPLES
+Build a site:
+.PP
+.RS
+.nf
+$ ssg build
+.fi
+.RE
+.PP
+Build to a custom output directory:
+.PP
+.RS
+.nf
+$ ssg build -out=public
+.fi
+.RE
+.PP
+Build with custom directories:
+.PP
+.RS
+.nf
+$ ssg build -data=content -templates=layouts -out=public
+.fi
+.RE
+.SH SEE ALSO
+.BR ssg-templates (5),
+.BR ssg-serve (1)
+.SH SSG
+Part of the
+.BR ssg (1)
+suite.
diff --git a/man/ssg-help.1 b/man/ssg-help.1
new file mode 100644
index 0000000..92f0d01
--- /dev/null
+++ b/man/ssg-help.1
@@ -0,0 +1,32 @@
+.TH SSG-HELP 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg-help \- show manual page
+.SH SYNOPSIS
+.B ssg help
+.RI [ command ]
+.SH DESCRIPTION
+Open the manual page for a command.
+.PP
+If no command is specified, opens the main
+.BR ssg (1)
+page.
+.SH EXAMPLES
+Show main documentation:
+.PP
+.RS
+.nf
+$ ssg help
+.fi
+.RE
+.PP
+Show build command documentation:
+.PP
+.RS
+.nf
+$ ssg help build
+.fi
+.RE
+.SH SSG
+Part of the
+.BR ssg (1)
+suite.
diff --git a/man/ssg-init.1 b/man/ssg-init.1
new file mode 100644
index 0000000..0f9db65
--- /dev/null
+++ b/man/ssg-init.1
@@ -0,0 +1,45 @@
+.TH SSG-INIT 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg-init \- initialize a new site
+.SH SYNOPSIS
+.B ssg init
+.RI [ directory ]
+.SH DESCRIPTION
+Create a new site with the standard directory structure:
+.PP
+.RS
+.nf
+data/
+templates/
+static/
+.fi
+.RE
+.PP
+If no directory is specified, initializes in the current directory.
+A sample
+.I templates/index.html
+is created if one does not exist.
+.SH EXAMPLES
+Initialize in the current directory:
+.PP
+.RS
+.nf
+$ ssg init
+.fi
+.RE
+.PP
+Initialize a new site:
+.PP
+.RS
+.nf
+$ ssg init mysite
+$ cd mysite
+$ ssg build
+.fi
+.RE
+.SH SEE ALSO
+.BR ssg-build (1)
+.SH SSG
+Part of the
+.BR ssg (1)
+suite.
diff --git a/man/ssg-serve.1 b/man/ssg-serve.1
new file mode 100644
index 0000000..15d8a3c
--- /dev/null
+++ b/man/ssg-serve.1
@@ -0,0 +1,45 @@
+.TH SSG-SERVE 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg-serve \- serve the site locally
+.SH SYNOPSIS
+.B ssg serve
+.RI [ options ]
+.SH DESCRIPTION
+Start a local HTTP server to preview the built site.
+.SH OPTIONS
+.TP
+.BI \-dir " dir"
+Directory to serve. Default: dist
+.TP
+.BI \-addr " address"
+Address to listen on. Default: :8080
+.SH EXAMPLES
+Serve the default output directory:
+.PP
+.RS
+.nf
+$ ssg serve
+.fi
+.RE
+.PP
+Serve on a different port:
+.PP
+.RS
+.nf
+$ ssg serve -addr=:3000
+.fi
+.RE
+.PP
+Build and serve:
+.PP
+.RS
+.nf
+$ ssg build && ssg serve
+.fi
+.RE
+.SH SEE ALSO
+.BR ssg-build (1)
+.SH SSG
+Part of the
+.BR ssg (1)
+suite.
diff --git a/man/ssg-templates.5 b/man/ssg-templates.5
new file mode 100644
index 0000000..2f1dbd6
--- /dev/null
+++ b/man/ssg-templates.5
@@ -0,0 +1,83 @@
+.TH SSG-TEMPLATES 5 "December 2025" "ssg" "File Formats"
+.SH NAME
+ssg-templates \- ssg template format
+.SH DESCRIPTION
+ssg templates use Go's
+.B html/template
+syntax. Each HTML file in the templates directory is processed and rendered
+to the output directory with the same filename.
+.SH DATA
+Data from JSON files in the data directory is made available to templates.
+Each file becomes a template variable named after the file (without the
+.I .json
+extension).
+.PP
+For example, if
+.I data/projects.json
+contains:
+.PP
+.RS
+.nf
+[
+ {"name": "foo", "url": "https://example.com/foo", "featured": true},
+ {"name": "bar", "url": "https://example.com/bar", "featured": false}
+]
+.fi
+.RE
+.PP
+It can be accessed in templates as
+.BR .projects :
+.PP
+.RS
+.nf
+{{range .projects}}
+ <li><a href="{{.url}}">{{.name}}</a></li>
+{{end}}
+.fi
+.RE
+.SH FUNCTIONS
+.SS filter
+The
+.B filter
+function returns items from an array where a field equals a value.
+.PP
+.RS
+.nf
+{{range filter .projects "featured" true}}
+ <li>{{.name}}</li>
+{{end}}
+.fi
+.RE
+.PP
+This would output only "foo" since it has
+.B featured
+set to
+.BR true .
+.SH SYNTAX
+Templates use Go's text/template syntax:
+.TP
+.B {{.field}}
+Output a field value.
+.TP
+.B {{range .items}}...{{end}}
+Iterate over a list.
+.TP
+.B {{if .condition}}...{{end}}
+Conditional rendering.
+.TP
+.B {{with .object}}...{{end}}
+Set dot to the object for the block.
+.PP
+See the Go
+.B html/template
+documentation for full syntax details.
+.SH FILES
+.TP
+.I data/*.json
+JSON data files. Each becomes a template variable.
+.TP
+.I templates/*.html
+HTML templates to render.
+.SH SEE ALSO
+.BR ssg (1),
+.BR ssg-build (1)
diff --git a/man/ssg-version.1 b/man/ssg-version.1
new file mode 100644
index 0000000..d5af6b6
--- /dev/null
+++ b/man/ssg-version.1
@@ -0,0 +1,11 @@
+.TH SSG-VERSION 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg-version \- print version
+.SH SYNOPSIS
+.B ssg version
+.SH DESCRIPTION
+Print the ssg version and exit.
+.SH SSG
+Part of the
+.BR ssg (1)
+suite.
diff --git a/man/ssg.1 b/man/ssg.1
new file mode 100644
index 0000000..a2d0621
--- /dev/null
+++ b/man/ssg.1
@@ -0,0 +1,50 @@
+.TH SSG 1 "December 2025" "ssg" "User Commands"
+.SH NAME
+ssg \- a tiny static site generator
+.SH SYNOPSIS
+.B ssg
+.I command
+.RI [ options ]
+.SH DESCRIPTION
+.B ssg
+is a minimal static site generator that reads JSON data files and renders
+Go templates to produce static HTML. Static assets are copied unchanged
+to the output directory.
+.SH COMMANDS
+.TP
+.BR ssg-build (1)
+Build the site.
+.TP
+.BR ssg-serve (1)
+Start a local HTTP server.
+.TP
+.BR ssg-init (1)
+Initialize a new site.
+.TP
+.BR ssg-version (1)
+Print the version.
+.TP
+.BR ssg-help (1)
+Show help for a command.
+.SH FILES
+.TP
+.I data/
+JSON data files. Each file becomes a template variable.
+.TP
+.I templates/
+HTML template files.
+.TP
+.I static/
+Static files copied unchanged.
+.TP
+.I dist/
+Default output directory.
+.SH SEE ALSO
+.BR ssg-build (1),
+.BR ssg-serve (1),
+.BR ssg-init (1),
+.BR ssg-version (1),
+.BR ssg-help (1),
+.BR ssg-templates (5)
+.SH AUTHOR
+Eugene Triguba <hello@eugenetriguba.com>
diff --git a/serve.go b/serve.go
new file mode 100644
index 0000000..8931113
--- /dev/null
+++ b/serve.go
@@ -0,0 +1,32 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "net/http"
+
+ "git.sr.ht/~eugenetriguba/subcmd"
+)
+
+type serveCmd struct {
+ dir string
+ addr string
+}
+
+func (c *serveCmd) Name() string { return "serve" }
+func (c *serveCmd) Synopsis() string { return "serve the site locally" }
+func (c *serveCmd) Usage() string {
+ return "serve [options]\n\nSee ssg-serve(1) for details.\n"
+}
+func (c *serveCmd) SetFlags(f *flag.FlagSet) {
+ f.StringVar(&c.dir, "dir", "dist", "")
+ f.StringVar(&c.addr, "addr", ":8080", "")
+}
+func (c *serveCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
+ fmt.Printf("Serving %s at http://localhost%s\n", c.dir, c.addr)
+ if err := http.ListenAndServe(c.addr, http.FileServer(http.Dir(c.dir))); err != nil {
+ fatal("%v", err)
+ }
+ return subcmd.ExitSuccess
+}
diff --git a/site.go b/site.go
new file mode 100644
index 0000000..7a94b2e
--- /dev/null
+++ b/site.go
@@ -0,0 +1,166 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "html/template"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// Site represents a static site with its configuration.
+type Site struct {
+ DataDir string
+ TemplatesDir string
+ StaticDir string
+ OutDir string
+ Log func(string, ...any)
+}
+
+// Build generates the complete site.
+func (s *Site) Build() error {
+ data, err := s.loadData()
+ if err != nil {
+ return err
+ }
+ if err := s.copyStatic(); err != nil {
+ return err
+ }
+ return s.render(data)
+}
+
+func (s *Site) loadData() (map[string]any, error) {
+ data := make(map[string]any)
+
+ entries, err := os.ReadDir(s.DataDir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return data, nil
+ }
+ return nil, fmt.Errorf("reading data directory: %w", err)
+ }
+
+ for _, entry := range entries {
+ if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
+ continue
+ }
+
+ name := strings.TrimSuffix(entry.Name(), ".json")
+ path := filepath.Join(s.DataDir, entry.Name())
+
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("opening %s: %w", path, err)
+ }
+
+ var v any
+ if err := json.NewDecoder(f).Decode(&v); err != nil {
+ f.Close()
+ return nil, fmt.Errorf("parsing %s: %w", path, err)
+ }
+ f.Close()
+
+ data[name] = v
+ s.log("data/%s.json", name)
+ }
+
+ return data, nil
+}
+
+func (s *Site) copyStatic() error {
+ if _, err := os.Stat(s.StaticDir); os.IsNotExist(err) {
+ return nil
+ }
+
+ err := filepath.WalkDir(s.StaticDir, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+
+ relPath, err := filepath.Rel(s.StaticDir, path)
+ if err != nil {
+ return err
+ }
+
+ destPath := filepath.Join(s.OutDir, relPath)
+
+ if d.IsDir() {
+ return os.MkdirAll(destPath, 0755)
+ }
+
+ src, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return err
+ }
+
+ info, err := d.Info()
+ if err != nil {
+ return err
+ }
+
+ return os.WriteFile(destPath, src, info.Mode())
+ })
+
+ if err != nil {
+ return fmt.Errorf("copying static files: %w", err)
+ }
+
+ s.log("static/")
+ return nil
+}
+
+func (s *Site) render(data map[string]any) error {
+ if err := os.MkdirAll(s.OutDir, 0755); err != nil {
+ return fmt.Errorf("creating output directory: %w", err)
+ }
+
+ funcs := template.FuncMap{
+ "filter": filterFunc,
+ }
+
+ entries, err := os.ReadDir(s.TemplatesDir)
+ if err != nil {
+ return fmt.Errorf("reading templates directory: %w", err)
+ }
+
+ for _, entry := range entries {
+ if entry.IsDir() || filepath.Ext(entry.Name()) != ".html" {
+ continue
+ }
+
+ tmplPath := filepath.Join(s.TemplatesDir, entry.Name())
+ outPath := filepath.Join(s.OutDir, entry.Name())
+
+ tmpl, err := template.New(entry.Name()).Funcs(funcs).ParseFiles(tmplPath)
+ if err != nil {
+ return fmt.Errorf("parsing %s: %w", tmplPath, err)
+ }
+
+ out, err := os.Create(outPath)
+ if err != nil {
+ return fmt.Errorf("creating %s: %w", outPath, err)
+ }
+
+ if err := tmpl.Execute(out, data); err != nil {
+ out.Close()
+ return fmt.Errorf("executing %s: %w", tmplPath, err)
+ }
+ out.Close()
+
+ s.log("%s", entry.Name())
+ }
+
+ return nil
+}
+
+func (s *Site) log(format string, args ...any) {
+ if s.Log != nil {
+ s.Log(format, args...)
+ }
+}
diff --git a/site_test.go b/site_test.go
new file mode 100644
index 0000000..9dfa03b
--- /dev/null
+++ b/site_test.go
@@ -0,0 +1,222 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "git.sr.ht/~eugenetriguba/checkmate/assert"
+)
+
+func TestSite_LoadData(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+ content := `{"title": "Test", "count": 42}`
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "config.json"), []byte(content), 0644))
+
+ site := &Site{DataDir: dataDir}
+ data, err := site.loadData()
+
+ assert.Nil(t, err)
+ assert.NotNil(t, data["config"])
+ config := data["config"].(map[string]any)
+ assert.Equal(t, config["title"], "Test")
+ assert.Equal(t, config["count"], float64(42))
+}
+
+func TestSite_LoadData_Array(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+ content := `[{"title": "Post 1"}, {"title": "Post 2"}]`
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "posts.json"), []byte(content), 0644))
+
+ site := &Site{DataDir: dataDir}
+ data, err := site.loadData()
+
+ assert.Nil(t, err)
+ assert.NotNil(t, data["posts"])
+ posts := data["posts"].([]any)
+ assert.Equal(t, len(posts), 2)
+}
+
+func TestSite_LoadData_EmptyDir(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+
+ site := &Site{DataDir: dataDir}
+ data, err := site.loadData()
+
+ assert.Nil(t, err)
+ assert.Equal(t, len(data), 0)
+}
+
+func TestSite_LoadData_NonExistentDir(t *testing.T) {
+ site := &Site{DataDir: "/nonexistent/path"}
+
+ data, err := site.loadData()
+
+ assert.Nil(t, err)
+ assert.Equal(t, len(data), 0)
+}
+
+func TestSite_LoadData_SkipsNonJSON(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "readme.txt"), []byte("text"), 0644))
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "config.json"), []byte(`{"key": "value"}`), 0644))
+
+ site := &Site{DataDir: dataDir}
+ data, err := site.loadData()
+
+ assert.Nil(t, err)
+ assert.Equal(t, len(data), 1)
+ assert.NotNil(t, data["config"])
+}
+
+func TestSite_LoadData_InvalidJSON(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "bad.json"), []byte("not json"), 0644))
+
+ site := &Site{DataDir: dataDir}
+ _, err := site.loadData()
+
+ assert.NotNil(t, err)
+}
+
+func TestSite_CopyStatic(t *testing.T) {
+ dir := t.TempDir()
+ staticDir := filepath.Join(dir, "static")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(staticDir, 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(staticDir, "style.css"), []byte("body {}"), 0644))
+
+ site := &Site{StaticDir: staticDir, OutDir: outDir}
+ err := site.copyStatic()
+
+ assert.Nil(t, err)
+ content, err := os.ReadFile(filepath.Join(outDir, "style.css"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(content), "body {}")
+}
+
+func TestSite_CopyStatic_NestedDirs(t *testing.T) {
+ dir := t.TempDir()
+ staticDir := filepath.Join(dir, "static")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(filepath.Join(staticDir, "css"), 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(staticDir, "css", "main.css"), []byte("h1 {}"), 0644))
+
+ site := &Site{StaticDir: staticDir, OutDir: outDir}
+ err := site.copyStatic()
+
+ assert.Nil(t, err)
+ content, err := os.ReadFile(filepath.Join(outDir, "css", "main.css"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(content), "h1 {}")
+}
+
+func TestSite_CopyStatic_NonExistentDir(t *testing.T) {
+ site := &Site{StaticDir: "/nonexistent/path", OutDir: t.TempDir()}
+ err := site.copyStatic()
+ assert.Nil(t, err)
+}
+
+func TestSite_Render(t *testing.T) {
+ dir := t.TempDir()
+ templatesDir := filepath.Join(dir, "templates")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(templatesDir, 0755))
+ tmpl := `<!doctype html><title>{{.config.title}}</title>`
+ assert.Nil(t, os.WriteFile(filepath.Join(templatesDir, "index.html"), []byte(tmpl), 0644))
+
+ site := &Site{TemplatesDir: templatesDir, OutDir: outDir}
+ data := map[string]any{
+ "config": map[string]any{"title": "My Site"},
+ }
+ err := site.render(data)
+
+ assert.Nil(t, err)
+ content, err := os.ReadFile(filepath.Join(outDir, "index.html"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(content), `<!doctype html><title>My Site</title>`)
+}
+
+func TestSite_Render_MultipleTemplates(t *testing.T) {
+ dir := t.TempDir()
+ templatesDir := filepath.Join(dir, "templates")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(templatesDir, 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(templatesDir, "index.html"), []byte("<h1>Home</h1>"), 0644))
+ assert.Nil(t, os.WriteFile(filepath.Join(templatesDir, "about.html"), []byte("<h1>About</h1>"), 0644))
+
+ site := &Site{TemplatesDir: templatesDir, OutDir: outDir}
+ err := site.render(map[string]any{})
+
+ assert.Nil(t, err)
+ index, err := os.ReadFile(filepath.Join(outDir, "index.html"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(index), "<h1>Home</h1>")
+ about, err := os.ReadFile(filepath.Join(outDir, "about.html"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(about), "<h1>About</h1>")
+}
+
+func TestSite_Render_WithFilter(t *testing.T) {
+ dir := t.TempDir()
+ templatesDir := filepath.Join(dir, "templates")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(templatesDir, 0755))
+ tmpl := `{{range filter .posts "draft" false}}{{.title}} {{end}}`
+ assert.Nil(t, os.WriteFile(filepath.Join(templatesDir, "index.html"), []byte(tmpl), 0644))
+
+ site := &Site{TemplatesDir: templatesDir, OutDir: outDir}
+ data := map[string]any{
+ "posts": []map[string]any{
+ {"title": "Post 1", "draft": false},
+ {"title": "Post 2", "draft": true},
+ {"title": "Post 3", "draft": false},
+ },
+ }
+ err := site.render(data)
+
+ assert.Nil(t, err)
+ content, err := os.ReadFile(filepath.Join(outDir, "index.html"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(content), "Post 1 Post 3 ")
+}
+
+func TestSite_Build(t *testing.T) {
+ dir := t.TempDir()
+ dataDir := filepath.Join(dir, "data")
+ templatesDir := filepath.Join(dir, "templates")
+ staticDir := filepath.Join(dir, "static")
+ outDir := filepath.Join(dir, "dist")
+ assert.Nil(t, os.MkdirAll(dataDir, 0755))
+ assert.Nil(t, os.MkdirAll(templatesDir, 0755))
+ assert.Nil(t, os.MkdirAll(staticDir, 0755))
+ assert.Nil(t, os.WriteFile(filepath.Join(dataDir, "site.json"), []byte(`{"name": "Test"}`), 0644))
+ assert.Nil(t, os.WriteFile(filepath.Join(templatesDir, "index.html"), []byte(`<h1>{{.site.name}}</h1>`), 0644))
+ assert.Nil(t, os.WriteFile(filepath.Join(staticDir, "style.css"), []byte("body {}"), 0644))
+
+ site := &Site{
+ DataDir: dataDir,
+ TemplatesDir: templatesDir,
+ StaticDir: staticDir,
+ OutDir: outDir,
+ }
+ err := site.Build()
+
+ assert.Nil(t, err)
+ html, err := os.ReadFile(filepath.Join(outDir, "index.html"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(html), "<h1>Test</h1>")
+ css, err := os.ReadFile(filepath.Join(outDir, "style.css"))
+ assert.Nil(t, err)
+ assert.Equal(t, string(css), "body {}")
+}
diff --git a/version.go b/version.go
new file mode 100644
index 0000000..5ba375b
--- /dev/null
+++ b/version.go
@@ -0,0 +1,21 @@
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "git.sr.ht/~eugenetriguba/subcmd"
+)
+
+var version = "dev"
+
+type versionCmd struct{}
+
+func (c *versionCmd) Name() string { return "version" }
+func (c *versionCmd) Synopsis() string { return "print version" }
+func (c *versionCmd) Usage() string { return "version: Print ssg version." }
+func (c *versionCmd) SetFlags(f *flag.FlagSet) {}
+func (c *versionCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
+ fmt.Println(version)
+ return subcmd.ExitSuccess
+}