Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ Output goes to `my-site/public/`. Open `index.html` to see it.

To change the page, edit `my-site/pages/index/content.md` and run `inkssg build my-site` again.

## Dev server

```
inkssg serve my-site
```

Builds the site, serves it at `http://localhost:3000`, watches your sources, and reloads the browser on every change. Pass `--addr :4000` to use a different port.

## Use as a library

```
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Note: `ink.yaml` is optional in v0.1. Add it only when you need site-wide data (

## v0.2 — Polish + daily iteration

- [ ] `inkssg serve` — local server with file watcher and auto-rebuild
- [x] `inkssg serve` — local server with file watcher and auto-rebuild
- [ ] Options: `FromConfig`, `WithTheme`, `WithOutputDir`, `WithPagesDir`
- [ ] Hooks: `BeforeBuild`, `AfterBuild`
- [ ] CSS/JS minification
Expand Down
33 changes: 30 additions & 3 deletions cmd/inkssg/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"runtime/debug"
"strings"

"github.com/snowztech/inkssg"
)
Expand Down Expand Up @@ -47,17 +48,43 @@ func main() {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
case "serve":
path, addr := parseServeArgs(os.Args[2:])
if err := inkssg.Serve(path, inkssg.ServeOptions{Addr: addr}); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
default:
usage()
os.Exit(1)
}
}

func parseServeArgs(args []string) (path, addr string) {
path = "."
addr = ":3000"
for i := 0; i < len(args); i++ {
switch args[i] {
case "--addr":
if i+1 < len(args) {
addr = args[i+1]
i++
}
default:
if !strings.HasPrefix(args[i], "-") {
path = args[i]
}
}
}
return path, addr
}

func usage() {
fmt.Println("inkssg — a small static site generator")
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" inkssg new [path] scaffold a new site")
fmt.Println(" inkssg build [path] build the site into ./public")
fmt.Println(" inkssg version print version")
fmt.Println(" inkssg new [path] scaffold a new site")
fmt.Println(" inkssg build [path] build the site into ./public")
fmt.Println(" inkssg serve [path] [--addr] build, serve, watch, live-reload")
fmt.Println(" inkssg version print version")
}
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,8 @@ require (
github.com/yuin/goldmark v1.8.2
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/fsnotify/fsnotify v1.10.0 // indirect
golang.org/x/sys v0.13.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/fsnotify/fsnotify v1.10.0 h1:Xx/5Ydg9CeBDX/wi4VJqStNtohYjitZhhlHt4h3St1M=
github.com/fsnotify/fsnotify v1.10.0/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
170 changes: 170 additions & 0 deletions livereload.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package inkssg

import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
)

const reloadPath = "/__inkssg/reload"

const reloadScript = `<script>
(function(){
if (window.__inkssgReload) return;
window.__inkssgReload = true;
var es = new EventSource("` + reloadPath + `");
es.onmessage = function(e){ if (e.data === "reload") location.reload(); };
})();
</script>`

// reloader fans out reload pings to connected SSE clients.
type reloader struct {
mu sync.Mutex
clients map[chan struct{}]struct{}
}

func newReloader() *reloader {
return &reloader{clients: map[chan struct{}]struct{}{}}
}

func (r *reloader) subscribe() chan struct{} {
ch := make(chan struct{}, 1)
r.mu.Lock()
r.clients[ch] = struct{}{}
r.mu.Unlock()
return ch
}

func (r *reloader) unsubscribe(ch chan struct{}) {
r.mu.Lock()
delete(r.clients, ch)
r.mu.Unlock()
}

func (r *reloader) broadcast() {
r.mu.Lock()
defer r.mu.Unlock()
for ch := range r.clients {
select {
case ch <- struct{}{}:
default:
}
}
}

func serveSSE(r *reloader) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")

ch := r.subscribe()
defer r.unsubscribe(ch)

fmt.Fprintf(w, ": connected\n\n")
flusher.Flush()

ctx := req.Context()
ping := time.NewTicker(30 * time.Second)
defer ping.Stop()

for {
select {
case <-ctx.Done():
return
case <-ch:
fmt.Fprintf(w, "data: reload\n\n")
flusher.Flush()
case <-ping.C:
fmt.Fprintf(w, ": ping\n\n")
flusher.Flush()
}
}
}
}

// htmlInjector wraps a file server so HTML responses get the reload script
// inserted before </body>. Non-HTML files pass through untouched.
type htmlInjector struct {
root string
next http.Handler
}

func (h *htmlInjector) ServeHTTP(w http.ResponseWriter, r *http.Request) {
urlPath := r.URL.Path
if urlPath == "/" || strings.HasSuffix(urlPath, "/") {
urlPath += "index.html"
}
if !strings.HasSuffix(urlPath, ".html") {
h.next.ServeHTTP(w, r)
return
}

clean := filepath.Clean(strings.TrimPrefix(urlPath, "/"))
abs := filepath.Join(h.root, clean)
rel, err := filepath.Rel(h.root, abs)
if err != nil || strings.HasPrefix(rel, "..") {
http.NotFound(w, r)
return
}

data, err := os.ReadFile(abs)
if err != nil {
h.next.ServeHTTP(w, r)
return
}

out := injectReloadScript(data)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Write(out)
}

func injectReloadScript(html []byte) []byte {
closing := []byte("</body>")
idx := bytes.LastIndex(html, closing)
if idx < 0 {
return append(html, []byte(reloadScript)...)
}
out := make([]byte, 0, len(html)+len(reloadScript))
out = append(out, html[:idx]...)
out = append(out, []byte(reloadScript)...)
out = append(out, html[idx:]...)
return out
}

func runServer(ctx context.Context, addr, root string, r *reloader) error {
mux := http.NewServeMux()
mux.Handle(reloadPath, serveSSE(r))
mux.Handle("/", &htmlInjector{root: root, next: http.FileServer(http.Dir(root))})

srv := &http.Server{Addr: addr, Handler: mux}

errCh := make(chan error, 1)
go func() {
errCh <- srv.ListenAndServe()
}()

select {
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return srv.Shutdown(shutdownCtx)
case err := <-errCh:
if err == http.ErrServerClosed {
return nil
}
return err
}
}
73 changes: 73 additions & 0 deletions serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package inkssg

import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
)

type ServeOptions struct {
Addr string
}

func Serve(dir string, opts ...ServeOptions) error {
o := ServeOptions{Addr: ":3000"}
if len(opts) > 0 {
if opts[0].Addr != "" {
o.Addr = opts[0].Addr
}
}

if dir == "" {
dir = "."
}
absDir, err := filepath.Abs(dir)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}

site, err := NewSite(absDir)
if err != nil {
return err
}
if err := site.Build(); err != nil {
return err
}

outAbs, err := filepath.Abs(filepath.Join(absDir, site.Output))
if err != nil {
return fmt.Errorf("resolve output: %w", err)
}

rl := newReloader()

rebuild := func() error {
start := time.Now()
s, err := NewSite(absDir)
if err != nil {
return err
}
if err := s.Build(); err != nil {
return err
}
fmt.Printf("↻ rebuilt in %s\n", time.Since(start).Round(time.Millisecond))
rl.broadcast()
return nil
}

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()

go func() {
if err := watch(ctx, absDir, outAbs, rebuild); err != nil {
fmt.Fprintf(os.Stderr, "watcher stopped: %v\n", err)
}
}()

fmt.Printf("inkssg serving %s on http://localhost%s\n", absDir, o.Addr)
return runServer(ctx, o.Addr, filepath.Join(absDir, site.Output), rl)
}
Loading
Loading