code.pablomurad.com

patchwork

Publishes the revisions of your pages as a feed, with notes and readable diffs, written in Go

internal/config/config.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Package config loads patchwork.yaml.
package config

import (
	_ "embed"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"
	// Distroless images and some Windows machines ship no zoneinfo.
	_ "time/tzdata"

	"gopkg.in/yaml.v3"

	"git.pablomurad.com/pablo/patchwork/internal/doc"
	"git.pablomurad.com/pablo/patchwork/internal/slug"
)

// Example is the commented config written by `patchwork init`.
//
//go:embed example.yaml
var Example []byte

// Config is a parsed patchwork.yaml.
type Config struct {
	Site        Site        `yaml:"site"`
	Source      Source      `yaml:"source"`
	Frontmatter Frontmatter `yaml:"frontmatter"`
	Publish     Publish     `yaml:"publish"`
	Watch       Watch       `yaml:"watch"`
	DB          string      `yaml:"db"`
	HTTP        HTTP        `yaml:"http"`
	Feeds       Feeds       `yaml:"feeds"`

	// Dir is the directory relative paths in the file resolve against.
	Dir string `yaml:"-"`
}

type Site struct {
	Title    string `yaml:"title"`
	BaseURL  string `yaml:"base_url"`
	Timezone string `yaml:"timezone"`
	Author   string `yaml:"author"`
	// TagAuthority is the "domain,year" part of tag: URIs used as feed
	// entry ids. It must never change once feeds are public.
	TagAuthority string    `yaml:"tag_authority"`
	PageURL      string    `yaml:"page_url"`
	VersionURL   string    `yaml:"version_url"`
	HistoryURL   string    `yaml:"history_url"`
	Feeds        SiteFeeds `yaml:"feeds"`
}

// SiteFeeds are the public paths where the host serves Patchwork's feeds.
// Feeds must point at themselves with their public URL, not at Patchwork's
// internal address.
type SiteFeeds struct {
	Atom     string `yaml:"atom"`
	JSON     string `yaml:"json"`
	PageAtom string `yaml:"page_atom"`
	PageJSON string `yaml:"page_json"`
}

type Source struct {
	Mode    string   `yaml:"mode"`
	Path    string   `yaml:"path"`
	Include []string `yaml:"include"`
	Exclude []string `yaml:"exclude"`
	Slug    string   `yaml:"slug"`
}

type Frontmatter struct {
	NoteKey     string   `yaml:"note_key"`
	KindKey     string   `yaml:"kind_key"`
	MaturityKey string   `yaml:"maturity_key"`
	DateKey     string   `yaml:"date_key"`
	DiffKeys    []string `yaml:"diff_keys"`
}

type Publish struct {
	FoldWindow Duration `yaml:"fold_window"`
}

type Watch struct {
	Debounce Duration `yaml:"debounce"`
	Poll     Duration `yaml:"poll"`
}

type HTTP struct {
	Addr string `yaml:"addr"`
}

type Feeds struct {
	Limit         int `yaml:"limit"`
	ExcerptBlocks int `yaml:"excerpt_blocks"`
}

// Duration reads Go duration strings such as "20m" or "3s".
type Duration struct{ time.Duration }

func (d *Duration) UnmarshalYAML(n *yaml.Node) error {
	var s string
	if err := n.Decode(&s); err != nil {
		return err
	}
	v, err := time.ParseDuration(s)
	if err != nil {
		return fmt.Errorf("line %d: %w", n.Line, err)
	}
	d.Duration = v
	return nil
}

func (d Duration) MarshalYAML() (any, error) { return d.String(), nil }

// Load reads a config file, fills defaults, applies PATCHWORK_* environment
// overrides and validates the result.
func Load(path string) (*Config, error) {
	raw, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	c := Default()
	dec := yaml.NewDecoder(strings.NewReader(string(raw)))
	dec.KnownFields(true)
	// io.EOF means an empty file: all defaults.
	if err := dec.Decode(c); err != nil && !errors.Is(err, io.EOF) {
		return nil, fmt.Errorf("%s: %w", path, err)
	}
	abs, err := filepath.Abs(path)
	if err != nil {
		return nil, err
	}
	c.Dir = filepath.Dir(abs)
	c.applyEnv()
	c.resolvePaths()
	if err := c.Validate(); err != nil {
		return nil, fmt.Errorf("%s: %w", path, err)
	}
	return c, nil
}

// Default returns the built-in configuration.
func Default() *Config {
	o := doc.DefaultOptions()
	return &Config{
		Site: Site{
			Timezone:   "UTC",
			PageURL:    "/{slug}",
			VersionURL: "/{slug}/v/{n}",
			HistoryURL: "/{slug}/history",
			Feeds: SiteFeeds{
				Atom:     "/revisions.atom",
				JSON:     "/revisions.json",
				PageAtom: "/{slug}/revisions.atom",
				PageJSON: "/{slug}/revisions.json",
			},
		},
		Source: Source{
			Mode:    "folder",
			Path:    ".",
			Include: []string{"**/*.md", "**/*.markdown"},
			Exclude: []string{".*", "*~", "*.tmp", "*.filepart", "*.part", "*.swp"},
			Slug:    "path",
		},
		Frontmatter: Frontmatter{
			NoteKey: o.NoteKey, KindKey: o.KindKey, MaturityKey: o.MaturityKey,
			DateKey: "date", DiffKeys: o.DiffKeys,
		},
		Publish: Publish{FoldWindow: Duration{20 * time.Minute}},
		Watch:   Watch{Debounce: Duration{3 * time.Second}, Poll: Duration{60 * time.Second}},
		DB:      defaultDB(),
		HTTP:    HTTP{Addr: "127.0.0.1:8080"},
		Feeds:   Feeds{Limit: 50, ExcerptBlocks: 6},
	}
}

// defaultDB keeps the database on a local disk: SQLite's locking is not
// safe on network shares.
func defaultDB() string {
	if dir, err := os.UserCacheDir(); err == nil {
		return filepath.Join(dir, "patchwork", "patchwork.db")
	}
	return "patchwork.db"
}

func (c *Config) applyEnv() {
	set := func(dst *string, key string) {
		if v, ok := os.LookupEnv(key); ok {
			*dst = v
		}
	}
	set(&c.DB, "PATCHWORK_DB")
	set(&c.Source.Path, "PATCHWORK_SOURCE_PATH")
	set(&c.HTTP.Addr, "PATCHWORK_HTTP_ADDR")
	set(&c.Site.BaseURL, "PATCHWORK_BASE_URL")
}

func (c *Config) resolvePaths() {
	if !filepath.IsAbs(c.Source.Path) {
		c.Source.Path = filepath.Join(c.Dir, c.Source.Path)
	}
	if !filepath.IsAbs(c.DB) {
		c.DB = filepath.Join(c.Dir, c.DB)
	}
}

// Validate checks values that would otherwise fail later or silently.
func (c *Config) Validate() error {
	var errs []error
	if c.Source.Mode != "folder" {
		errs = append(errs, fmt.Errorf("source.mode %q is not supported yet (want folder)", c.Source.Mode))
	}
	if _, err := slug.Lookup(c.Source.Slug); err != nil {
		errs = append(errs, fmt.Errorf("source.slug: %w", err))
	}
	if _, err := time.LoadLocation(c.Site.Timezone); err != nil {
		errs = append(errs, fmt.Errorf("site.timezone: %w", err))
	}
	if c.Site.BaseURL != "" && !strings.HasPrefix(c.Site.BaseURL, "http://") && !strings.HasPrefix(c.Site.BaseURL, "https://") {
		errs = append(errs, fmt.Errorf("site.base_url must start with http:// or https://"))
	}
	if c.Frontmatter.NoteKey == "" {
		errs = append(errs, errors.New("frontmatter.note_key is empty"))
	}
	for _, p := range append(append([]string{}, c.Source.Include...), c.Source.Exclude...) {
		if _, err := filepath.Match(strings.TrimPrefix(p, "**/"), "x"); err != nil {
			errs = append(errs, fmt.Errorf("bad pattern %q: %w", p, err))
		}
	}
	if c.Publish.FoldWindow.Duration < 0 || c.Watch.Debounce.Duration < 0 || c.Watch.Poll.Duration < 0 {
		errs = append(errs, errors.New("durations must not be negative"))
	}
	if c.Feeds.Limit <= 0 || c.Feeds.ExcerptBlocks <= 0 {
		errs = append(errs, errors.New("feeds.limit and feeds.excerpt_blocks must be positive"))
	}
	return errors.Join(errs...)
}

// DocOptions are the frontmatter keys in the form the doc package takes.
func (c *Config) DocOptions() doc.Options {
	return doc.Options{
		NoteKey: c.Frontmatter.NoteKey, KindKey: c.Frontmatter.KindKey,
		MaturityKey: c.Frontmatter.MaturityKey, DiffKeys: c.Frontmatter.DiffKeys,
	}
}

// Location is the site's time zone. Validate has already checked it.
func (c *Config) Location() *time.Location {
	loc, err := time.LoadLocation(c.Site.Timezone)
	if err != nil {
		return time.UTC
	}
	return loc
}