oficina / calendar Public

Clone
git clone https://amadan.net/oficina/calendar

Plain git — no account needed to clone.

Download

Download this file

1// Package guardstest turns the prose rules in AGENTS.md into tests.
2//
3// CARLOS's own rule: "a guard a shell step can satisfy is a guard a
4// shell step can be wrong about — put guards inside the test binary."
5// Every rule here is one AGENTS.md states, and the point is that
6// nobody has to remember it.
7//
8// There is no production code in this package.
9package guardstest
10
11import (
12 "go/ast"
13 "go/parser"
14 "go/token"
15 "os"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "strings"
20 "testing"
21)
22
23// repoRoot is found from this file's own path, never from the working
24// directory: `go test ./...` and a run from an editor have different
25// working directories and only one of them would be right.
26func repoRoot(t *testing.T) string {
27 t.Helper()
28 _, file, _, ok := runtime.Caller(0)
29 if !ok {
30 t.Fatal("runtime.Caller failed")
31 }
32 return filepath.Dir(filepath.Dir(filepath.Dir(file)))
33}
34
35// walk visits every file under root with one of the given extensions,
36// skipping the directories that hold nothing we wrote.
37func walk(t *testing.T, root string, exts []string, fn func(path string, body []byte)) {
38 t.Helper()
39 err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
40 if err != nil {
41 return err
42 }
43 if info.IsDir() {
44 switch info.Name() {
45 case ".git", "node_modules", "releases", ".claude", "vendor":
46 return filepath.SkipDir
47 }
48 return nil
49 }
50 for _, ext := range exts {
51 if strings.HasSuffix(path, ext) {
52 b, err := os.ReadFile(path)
53 if err != nil {
54 return err
55 }
56 fn(path, b)
57 return nil
58 }
59 }
60 return nil
61 })
62 if err != nil {
63 t.Fatalf("walk: %v", err)
64 }
65}
66
67// The 300-line cap, on everything we write.
68//
69// Exemptions are by EXACT PATH and each carries its reason. The
70// vendored scripts are rastrillo's, delivered by the scaffold and
71// pinned byte-for-byte by vendored_test.go — editing them to satisfy a
72// line cap would break that pin, which is the more valuable guard.
73var lineCapExempt = map[string]string{
74 "internal/calendar/static/datetime.js": "vendored from rastrillo; pinned byte-for-byte",
75 "internal/calendar/static/rastrillo.js": "rastrillo's, written from estilo's busy by scripts/writeestilo; pinned byte-for-byte",
76 "internal/calendar/static/select.js": "vendored from rastrillo; pinned byte-for-byte",
77 "internal/calendar/static/tokens.css": "vendored from rastrillo; pinned byte-for-byte",
78 "internal/calendar/static/theme.css": "written from estilo by scripts/writeestilo; pinned byte-for-byte",
79 "internal/calendar/static/busy.js": "estilo's, written by scripts/writeestilo; pinned byte-for-byte",
80}
81
82func TestNoFileExceedsTheLineCap(t *testing.T) {
83 const cap = 300
84 root := repoRoot(t)
85 walk(t, root, []string{".go", ".js"}, func(path string, body []byte) {
86 rel, _ := filepath.Rel(root, path)
87 rel = filepath.ToSlash(rel)
88 if _, ok := lineCapExempt[rel]; ok {
89 return
90 }
91 if n := len(strings.Split(string(body), "\n")); n > cap {
92 t.Errorf("%s is %d lines, cap is %d — split it", rel, n, cap)
93 }
94 })
95}
96
97// An exemption for a file that no longer exists proves nothing, and
98// quietly accumulates. Sheets shipped a walk that skipped vendor/ and
99// therefore proved nothing at all; this is the test that catches the
100// equivalent here.
101func TestEveryLineCapExemptionIsLive(t *testing.T) {
102 root := repoRoot(t)
103 for rel, reason := range lineCapExempt {
104 if _, err := os.Stat(filepath.Join(root, rel)); err != nil {
105 t.Errorf("line-cap exemption %q (%s) names a file that does not exist", rel, reason)
106 }
107 }
108}
109
110// sessions.UserID returns (0, false) under the magic-link plugin,
111// because the Subject is a verified address rather than a numeric id.
112// Every owner-scoped query built on it silently filters to person 0 —
113// a calendar that looks empty rather than broken, which is the more
114// expensive failure.
115//
116// An AST walk rather than a grep, so this comment — which names the
117// call it forbids — does not need an exemption from its own rule.
118func TestNeverSessionsUserID(t *testing.T) {
119 root := repoRoot(t)
120 fset := token.NewFileSet()
121
122 walk(t, root, []string{".go"}, func(path string, body []byte) {
123 rel, _ := filepath.Rel(root, path)
124 f, err := parser.ParseFile(fset, path, body, 0)
125 if err != nil {
126 return // a file that does not parse is the compiler's problem
127 }
128 // Only if the file actually imports the sessions package.
129 imported := ""
130 for _, im := range f.Imports {
131 if p := strings.Trim(im.Path.Value, `"`); p == "amadan.net/rastrillo/rastrillo/sessions" || p == preMoveRastrillo+"/sessions" {
132 imported = "sessions"
133 if im.Name != nil {
134 imported = im.Name.Name
135 }
136 }
137 }
138 if imported == "" {
139 return
140 }
141 ast.Inspect(f, func(n ast.Node) bool {
142 sel, ok := n.(*ast.SelectorExpr)
143 if !ok || sel.Sel.Name != "UserID" {
144 return true
145 }
146 if id, ok := sel.X.(*ast.Ident); ok && id.Name == imported {
147 t.Errorf("%s calls %s.UserID — use auth.From(r), and CurrentPerson(r) for the id",
148 filepath.ToSlash(rel), imported)
149 }
150 return true
151 })
152 })
153}
154
155// A cgo SQLite driver would break CGO_ENABLED=0, and the failure is a
156// binary that will not build for the platform rather than one that
157// misbehaves — but it is cheap to catch here and expensive to discover
158// at ship time.
159func TestNoCgoSQLiteDriver(t *testing.T) {
160 root := repoRoot(t)
161 forbidden := []string{"gorm.io/driver/sqlite", "github.com/mattn/go-sqlite3", "glebarez"}
162 walk(t, root, []string{".go", ".mod"}, func(path string, body []byte) {
163 rel, _ := filepath.Rel(root, path)
164 if strings.HasSuffix(rel, "guards_test.go") {
165 return // this file names them in order to forbid them
166 }
167 for _, f := range forbidden {
168 if strings.Contains(string(body), f) {
169 t.Errorf("%s references %s — the stack is cgo-free", filepath.ToSlash(rel), f)
170 }
171 }
172 })
173}
174
175// Every var(--rst-*) this app's own CSS uses must actually be declared
176// by the vendored token or theme files.
177//
178// Written because an invented token name is invisible: the property
179// falls back to nothing, the element renders unstyled-ish, and nobody
180// notices until a screen looks slightly wrong on a canary.
181func TestEveryTokenWeUseIsDefined(t *testing.T) {
182 root := repoRoot(t)
183 static := filepath.Join(root, "internal", "calendar", "static")
184
185 declared := map[string]bool{}
186 for _, name := range []string{"tokens.css", "theme.css"} {
187 b, err := os.ReadFile(filepath.Join(static, name))
188 if err != nil {
189 t.Fatalf("read %s: %v", name, err)
190 }
191 for _, m := range regexp.MustCompile(`(--rst-[A-Za-z0-9-]+)\s*:`).FindAllStringSubmatch(string(b), -1) {
192 declared[m[1]] = true
193 }
194 }
195 if len(declared) < 20 {
196 t.Fatalf("only %d tokens found in the vendored CSS; the parse is wrong, so this test proves nothing", len(declared))
197 }
198
199 used := regexp.MustCompile(`var\((--rst-[A-Za-z0-9-]+)`)
200 for _, name := range []string{"calendar.css"} {
201 b, err := os.ReadFile(filepath.Join(static, name))
202 if err != nil {
203 t.Fatalf("read %s: %v", name, err)
204 }
205 for _, m := range used.FindAllStringSubmatch(string(b), -1) {
206 if !declared[m[1]] {
207 t.Errorf("%s uses %s, which no vendored stylesheet declares", name, m[1])
208 }
209 }
210 }
211}
212
213// This app's own components take cal-. rst- is the framework's
214// namespace and a future release may claim a name we took; estilo- is
215// the suite's, and a month grid is not a suite component until a second
216// app copies one.
217func TestOurCSSDoesNotClaimAnotherPrefix(t *testing.T) {
218 root := repoRoot(t)
219 b, err := os.ReadFile(filepath.Join(root, "internal", "calendar", "static", "calendar.css"))
220 if err != nil {
221 t.Fatalf("read calendar.css: %v", err)
222 }
223 // Selectors only. var(--rst-*) is a token reference and entirely
224 // correct — this app is meant to use the framework's tokens.
225 bad := regexp.MustCompile(`\[\s*(rst|estilo)-|\.(rst|estilo)-`)
226 for _, m := range bad.FindAllString(string(b), -1) {
227 t.Errorf("calendar.css defines a selector for another namespace: %q — this app's prefix is cal-", m)
228 }
229}
230
231// Seven rastrillo utilities keep the class spelling and have no
232// attribute twin. Written in attribute position they silently do
233// nothing — the failure that put a visible "sr-only" label in sheets'
234// toolbar.
235func TestUtilitiesAreNeverWrittenAsAttributes(t *testing.T) {
236 root := repoRoot(t)
237 utilities := []string{"rst-sr-only", "rst-mono", "rst-grow", "rst-m-hide", "rst-danger", "rst-nm", "rst-cell-mut"}
238 walk(t, filepath.Join(root, "internal", "calendar", "templates"), []string{".html"},
239 func(path string, body []byte) {
240 rel, _ := filepath.Rel(root, path)
241 for _, u := range utilities {
242 // In attribute position it appears as a bare word
243 // preceded by whitespace inside a tag, never as
244 // class="...".
245 bare := regexp.MustCompile(`<[^>]*\s` + regexp.QuoteMeta(u) + `[\s=>]`)
246 for _, m := range bare.FindAllString(string(body), -1) {
247 if strings.Contains(m, `class=`) {
248 continue
249 }
250 t.Errorf("%s writes %s in attribute position (%q); it is a class-only utility",
251 filepath.ToSlash(rel), u, strings.TrimSpace(m))
252 }
253 }
254 })
255}
256
257// preMoveRastrillo is rastrillo's module path before it moved to
258// amadan.net/rastrillo/rastrillo (v0.25.0). Nothing after v0.23.0 was
259// released under it, so code importing it gets no rastrillo fix, and
260// its own vendored-asset check cannot tell. That is how Calendar kept
261// zooming iOS on every tap for a month after rastrillo fixed it
262// (polish audit r3, item 1).
263const preMoveRastrillo = "github.com/carlosframework/rastrillo"
264
265// preMoveAllowed is the one file that may still import it, and why:
266// rastrillo/native's server takes the old path's *sessions.Sessions.
267// Delete the entry when native/server moves.
268var preMoveAllowed = map[string]string{
269 "internal/calendar/native.go": preMoveRastrillo + "/sessions",
270}
271
272// TestNoPreMoveRastrillo fails on any import of rastrillo's old module
273// path outside preMoveAllowed.
274func TestNoPreMoveRastrillo(t *testing.T) {
275 root := repoRoot(t)
276 fset := token.NewFileSet()
277 walk(t, root, []string{".go"}, func(path string, body []byte) {
278 rel, _ := filepath.Rel(root, path)
279 rel = filepath.ToSlash(rel)
280 f, err := parser.ParseFile(fset, path, body, parser.ImportsOnly)
281 if err != nil {
282 return // a file that does not parse is the compiler's problem
283 }
284 for _, im := range f.Imports {
285 imp := strings.Trim(im.Path.Value, `"`)
286 if (imp == preMoveRastrillo || strings.HasPrefix(imp, preMoveRastrillo+"/")) && preMoveAllowed[rel] != imp {
287 t.Errorf("%s: imports %q, rastrillo's frozen pre-move path; use amadan.net/rastrillo/rastrillo", rel, imp)
288 }
289 }
290 })
291}
292