Compare commits
3
Commits
637b431e97
...
next
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb74aa593d | ||
|
|
17796569b8 | ||
|
|
db3373c71d |
@@ -0,0 +1,83 @@
|
|||||||
|
# .dockerignore does NOT use .gitignore semantics. Docker matches with
|
||||||
|
# moby/patternmatcher: filepath.Match plus `**`, so `*` does not cross
|
||||||
|
# `/` and an unprefixed pattern is anchored at the context root. Every
|
||||||
|
# depth-independent pattern therefore needs `**/`, or `config/.env` and
|
||||||
|
# `certs/server.key` still ship while this file reads as solved. Only
|
||||||
|
# genuinely root-anchored entries go unprefixed. Never transplant these
|
||||||
|
# into .gitignore, where `**/` is wrong.
|
||||||
|
#
|
||||||
|
# Matching is case-sensitive, so secrets use character ranges rather
|
||||||
|
# than an ALL-CAPS twin, which would still miss `Server.Key`.
|
||||||
|
#
|
||||||
|
# Extend with this repo's own host-built artifacts, written anchored:
|
||||||
|
# `/myapp`, never `**/myapp`, which also matches `cmd/myapp/` and
|
||||||
|
# deletes the package directory from the context.
|
||||||
|
|
||||||
|
# .git is sent without its config. Without a VERSION build argument the
|
||||||
|
# stage that compiles runs `git describe --tags --always` on .git, which
|
||||||
|
# does not need .git/config; that file can hold a credential, such as a
|
||||||
|
# password in a remote URL or the token the CI checkout step stores there.
|
||||||
|
# Each submodule keeps a config with the same exposure in its git directory
|
||||||
|
# under .git/modules/, nested again for a submodule's own submodules, or in
|
||||||
|
# its own .git directory when it keeps one.
|
||||||
|
# KNOWN GAP: a submodule whose name has a `config` segment (`config`,
|
||||||
|
# `deploy/config`, `config/lib`) loses its whole git directory, because
|
||||||
|
# `**/.git/modules/**/config` also matches that segment's directory
|
||||||
|
# under .git/modules/. Go's version stamping then fails the build;
|
||||||
|
# nothing leaks. Name such a submodule without that segment:
|
||||||
|
# `git submodule add --name`.
|
||||||
|
**/.git/config
|
||||||
|
**/.git/modules/**/config
|
||||||
|
|
||||||
|
# Agent scratch: one full checkout of the repo per in-flight agent.
|
||||||
|
# Anchored because it occurs once where agents run at the repo root.
|
||||||
|
# KNOWN GAP: a repo running agents in subdirectories still ships
|
||||||
|
# `services/api/.claude/` and must add its own anchored entry.
|
||||||
|
.claude
|
||||||
|
|
||||||
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
|
# convention. Re-include a committed template with a negation if the
|
||||||
|
# build needs one: `!docs/example.env`.
|
||||||
|
**/*.[eE][nN][vV]
|
||||||
|
**/.[eE][nN][vV].*
|
||||||
|
**/.[eE][nN][vV][rR][cC]
|
||||||
|
|
||||||
|
# Private keys and the bundles carrying them. Public certificates
|
||||||
|
# (*.crt, *.cer) are deliberately absent: they are legitimate inputs.
|
||||||
|
**/*.[pP][eE][mM]
|
||||||
|
**/*.[kK][eE][yY]
|
||||||
|
**/*.[pP]12
|
||||||
|
**/*.[pP][fF][xX]
|
||||||
|
**/[iI][dD]_[rR][sS][aA]
|
||||||
|
**/[iI][dD]_[dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK]
|
||||||
|
**/[iI][dD]_[eE][dD]25519
|
||||||
|
**/[iI][dD]_[eE][dD]25519_[sS][kK]
|
||||||
|
|
||||||
|
# Dependencies: restored inside the image, never copied in.
|
||||||
|
**/node_modules
|
||||||
|
|
||||||
|
# OS metadata.
|
||||||
|
**/.DS_Store
|
||||||
|
**/Thumbs.db
|
||||||
|
|
||||||
|
# Editor state: never a build input, and it churns COPY.
|
||||||
|
**/*.swp
|
||||||
|
**/*.swo
|
||||||
|
**/*~
|
||||||
|
**/*.bak
|
||||||
|
**/.idea
|
||||||
|
**/.vscode
|
||||||
|
**/*.sublime-*
|
||||||
|
|
||||||
|
# This repository's host-built artifacts: the example program's binary,
|
||||||
|
# test binaries, coverage output, and the log yarn writes when an install
|
||||||
|
# fails.
|
||||||
|
/cmd/example/example
|
||||||
|
/*.test
|
||||||
|
/*.out
|
||||||
|
/yarn-error.log
|
||||||
|
|
||||||
|
# aider's files, among them a config file that can hold an API key.
|
||||||
|
**/.aider*
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.go]
|
||||||
|
indent_style = tab
|
||||||
@@ -1,12 +1,9 @@
|
|||||||
name: check
|
name: check
|
||||||
|
on: [push]
|
||||||
on:
|
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check:
|
check:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
# actions/checkout v4.2.2, 2026-02-22
|
||||||
- run: script/cibuild
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||||
|
- run: script/cibuild
|
||||||
|
|||||||
+56
-1
@@ -1,2 +1,57 @@
|
|||||||
.aider*
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Editors
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
*.bak
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.sublime-*
|
||||||
|
|
||||||
|
# Agent scratch (worktrees of this repo, created and destroyed by
|
||||||
|
# in-flight tooling). Unanchored: .gitignore patterns already match at
|
||||||
|
# every depth, so no prefix is wanted here. This is not a .dockerignore
|
||||||
|
# entry and must not be given a `**/` prefix on the way into one.
|
||||||
|
.claude/
|
||||||
|
|
||||||
|
# Node
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Secrets. Unanchored like every entry above, so each matches at every
|
||||||
|
# depth. Matching is case-sensitive on Linux, so names use character
|
||||||
|
# ranges rather than a lowercase form that misses `Server.Key`.
|
||||||
|
|
||||||
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
|
# convention. Only the templates `example.env` and `sample.env` are
|
||||||
|
# re-included below. A repository that commits any other template adds
|
||||||
|
# its own negation after these lines, for example `!.env.example`.
|
||||||
|
*.[eE][nN][vV]
|
||||||
|
.[eE][nN][vV].*
|
||||||
|
.[eE][nN][vV][rR][cC]
|
||||||
|
!example.env
|
||||||
|
!sample.env
|
||||||
|
|
||||||
|
# Private keys and the bundles carrying them.
|
||||||
|
*.[pP][eE][mM]
|
||||||
|
*.[kK][eE][yY]
|
||||||
|
*.[pP]12
|
||||||
|
*.[pP][fF][xX]
|
||||||
|
[iI][dD]_[rR][sS][aA]
|
||||||
|
[iI][dD]_[dD][sS][aA]
|
||||||
|
[iI][dD]_[eE][cC][dD][sS][aA]
|
||||||
|
[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK]
|
||||||
|
[iI][dD]_[eE][dD]25519
|
||||||
|
[iI][dD]_[eE][dD]25519_[sS][kK]
|
||||||
|
|
||||||
|
# This repository's own entries. Go: logs, coverage output, test
|
||||||
|
# binaries, and the example program's binary.
|
||||||
|
*.log
|
||||||
|
*.out
|
||||||
|
*.test
|
||||||
cmd/example/example
|
cmd/example/example
|
||||||
|
|
||||||
|
# aider's files, among them a config file that can hold an API key.
|
||||||
|
.aider*
|
||||||
|
|||||||
+67
-2
@@ -10,14 +10,21 @@ run:
|
|||||||
|
|
||||||
linters:
|
linters:
|
||||||
default: all
|
default: all
|
||||||
|
enable:
|
||||||
|
# Successor to the deprecated gomodguard. Named explicitly, rather than
|
||||||
|
# left to `default: all`, because it carries the module policy below.
|
||||||
|
- gomodguard_v2
|
||||||
disable:
|
disable:
|
||||||
# Genuinely incompatible with project patterns
|
# Genuinely incompatible with project patterns
|
||||||
- exhaustruct # Requires all struct fields
|
- exhaustruct # Requires all struct fields
|
||||||
- depguard # Dependency allow/block lists
|
- exhaustruct_v5 # Requires all struct fields (successor to exhaustruct)
|
||||||
- godot # Requires comments to end with periods
|
- godot # Requires comments to end with periods
|
||||||
- wsl # Deprecated, replaced by wsl_v5
|
|
||||||
- wrapcheck # Too verbose for internal packages
|
- wrapcheck # Too verbose for internal packages
|
||||||
- varnamelen # Short names like db, id are idiomatic Go
|
- varnamelen # Short names like db, id are idiomatic Go
|
||||||
|
# Deprecated: the warning is attached to the old name, so it is
|
||||||
|
# silenced by disabling that name, not by enabling the successor.
|
||||||
|
- wsl # Deprecated, replaced by wsl_v5
|
||||||
|
- gomodguard # Deprecated, replaced by gomodguard_v2
|
||||||
settings:
|
settings:
|
||||||
lll:
|
lll:
|
||||||
line-length: 88
|
line-length: 88
|
||||||
@@ -28,6 +35,64 @@ linters:
|
|||||||
max-complexity: 15
|
max-complexity: 15
|
||||||
dupl:
|
dupl:
|
||||||
threshold: 100
|
threshold: 100
|
||||||
|
depguard:
|
||||||
|
# Test-support code must not be compiled into the shipped binary. A
|
||||||
|
# test-support package exists to hand a test privileges the program
|
||||||
|
# itself must never have, so a file that is not a test must not import
|
||||||
|
# one. Test files, and the files inside a package whose directory name
|
||||||
|
# ends in `test`, are where that code belongs, and are exempt.
|
||||||
|
#
|
||||||
|
# The deny list below is the one part of this file a repository is
|
||||||
|
# expected to extend, and the only part it may. depguard matches an
|
||||||
|
# import path against a list of prefixes, so it cannot be told "any path
|
||||||
|
# whose last segment ends in test"; a repository's own test-support
|
||||||
|
# packages have to be named here one at a time, by full import path,
|
||||||
|
# under a module path that differs from repository to repository. Add
|
||||||
|
# them; change nothing else.
|
||||||
|
rules:
|
||||||
|
test-support:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "$all"
|
||||||
|
- "!$test"
|
||||||
|
- "!**/*test/**"
|
||||||
|
deny:
|
||||||
|
- pkg: net/http/httptest
|
||||||
|
desc: >-
|
||||||
|
Test-support code belongs in test files and in packages whose
|
||||||
|
directory name ends in test, not in the shipped binary.
|
||||||
|
# Only decisions already recorded in the Go package defaults are
|
||||||
|
# listed here. Every entry matches the module path exactly.
|
||||||
|
gomodguard_v2:
|
||||||
|
blocked:
|
||||||
|
- module: github.com/rs/zerolog
|
||||||
|
recommendations:
|
||||||
|
- log/slog
|
||||||
|
reason: "Structured logging is stdlib log/slog."
|
||||||
|
# One entry per pre-fork module path, because the later releases
|
||||||
|
# are separate paths. A prefix match would be shorter but would
|
||||||
|
# also reach github.com/go-redis/redismock, the test double for
|
||||||
|
# the successor these entries recommend.
|
||||||
|
- module: github.com/go-redis/redis
|
||||||
|
recommendations:
|
||||||
|
- github.com/redis/go-redis/v9
|
||||||
|
reason: "Pre-fork module; use the maintained go-redis v9."
|
||||||
|
- module: github.com/go-redis/redis/v7
|
||||||
|
recommendations:
|
||||||
|
- github.com/redis/go-redis/v9
|
||||||
|
reason: "Pre-fork module; use the maintained go-redis v9."
|
||||||
|
- module: github.com/go-redis/redis/v8
|
||||||
|
recommendations:
|
||||||
|
- github.com/redis/go-redis/v9
|
||||||
|
reason: "Pre-fork module; use the maintained go-redis v9."
|
||||||
|
- module: github.com/sergi/go-diff
|
||||||
|
recommendations:
|
||||||
|
- github.com/aymanbagabas/go-udiff
|
||||||
|
reason: "No unified diff output; use go-udiff."
|
||||||
|
- module: github.com/hexops/gotextdiff
|
||||||
|
recommendations:
|
||||||
|
- github.com/aymanbagabas/go-udiff
|
||||||
|
reason: "Unmaintained fork; use go-udiff."
|
||||||
|
|
||||||
issues:
|
issues:
|
||||||
max-issues-per-linter: 0
|
max-issues-per-linter: 0
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules/
|
||||||
|
yarn.lock
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"tabWidth": 4,
|
||||||
|
"proseWrap": "always"
|
||||||
|
}
|
||||||
+13
-5
@@ -1,11 +1,11 @@
|
|||||||
# Lint stage: format check + golangci-lint
|
# Lint stage. The format check is not here: it runs on the host, in
|
||||||
# golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-07
|
# script/fmt-check.
|
||||||
FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS lint
|
# golangci/golangci-lint:v2.14.0 (Debian-based), 2026-09-24
|
||||||
|
FROM golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make fmt-check
|
|
||||||
# Called directly: make lint is itself a docker build of this stage.
|
# Called directly: make lint is itself a docker build of this stage.
|
||||||
RUN golangci-lint run --config .golangci.yml ./...
|
RUN golangci-lint run --config .golangci.yml ./...
|
||||||
|
|
||||||
@@ -21,8 +21,16 @@ RUN go test -timeout 90s -race -cover ./... || \
|
|||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
go test -timeout 90s -race -v ./...; exit 1; }
|
go test -timeout 90s -race -v ./...; exit 1; }
|
||||||
|
|
||||||
# Final stage: the copies make a plain docker build run both stages above.
|
# Final stage: a development environment, set up by script/bootstrap.
|
||||||
|
# The copies make a plain docker build run both stages above. No stage
|
||||||
|
# compiles a binary, since simplelog is a library, so none declares the
|
||||||
|
# VERSION build argument that script/docker and script/cibuild pass.
|
||||||
# golang 1.22.12 (2025-02-04)
|
# golang 1.22.12 (2025-02-04)
|
||||||
FROM golang@sha256:1cf6c45ba39db9fd6db16922041d074a63c935556a05c5ccb62d181034df7f02
|
FROM golang@sha256:1cf6c45ba39db9fd6db16922041d074a63c935556a05c5ccb62d181034df7f02
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
COPY --from=lint /src/go.sum /dev/null
|
||||||
COPY --from=test /src/go.sum /dev/null
|
COPY --from=test /src/go.sum /dev/null
|
||||||
|
WORKDIR /src
|
||||||
|
COPY script/ script/
|
||||||
|
COPY go.mod go.sum package.json yarn.lock ./
|
||||||
|
RUN script/bootstrap
|
||||||
|
COPY . .
|
||||||
|
|||||||
@@ -3,35 +3,33 @@
|
|||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
simplelog is an opinionated logging package designed to facilitate easy and
|
simplelog is an opinionated logging package designed to facilitate easy and
|
||||||
structured logging in Go applications with an absolute minimum of
|
structured logging in Go applications with an absolute minimum of boilerplate.
|
||||||
boilerplate.
|
|
||||||
|
|
||||||
The idea is that you can add a single import line which replaces the
|
The idea is that you can add a single import line which replaces the stdlib
|
||||||
stdlib `log/slog` default handler, and solve the 90% case for logging.
|
`log/slog` default handler, and solve the 90% case for logging.
|
||||||
|
|
||||||
## Current Status
|
## Current Status
|
||||||
|
|
||||||
Released v1.0.0 2024-06-14. Works as intended. No known bugs.
|
Released v1.0.0 2024-06-14. Works as intended. No known bugs.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- if output is a tty, outputs pretty color logs
|
- if output is a tty, outputs pretty color logs
|
||||||
- if output is not a tty, outputs json
|
- if output is not a tty, outputs json
|
||||||
- supports delivering each log message via a webhook
|
- supports delivering each log message via a webhook
|
||||||
- emits every `slog` attribute: those passed to a log call, those
|
- emits every `slog` attribute: those passed to a log call, those accumulated
|
||||||
accumulated with `WithAttrs`, and those qualified by `WithGroup`.
|
with `WithAttrs`, and those qualified by `WithGroup`. `slog.Group` values
|
||||||
`slog.Group` values nest, and `slog.LogValuer` values are resolved. In
|
nest, and `slog.LogValuer` values are resolved. In json output attributes are
|
||||||
json output attributes are object fields (groups become nested objects);
|
object fields (groups become nested objects); in console output they are
|
||||||
in console output they are appended as `key=value` pairs, with grouped
|
appended as `key=value` pairs, with grouped keys written as `group.key=value`.
|
||||||
keys written as `group.key=value`. See
|
See [Attribute output](#attribute-output) for the details worth knowing
|
||||||
[Attribute output](#attribute-output) for the details worth knowing
|
- reports a record that could not be delivered as an error from the handler's
|
||||||
- reports a record that could not be delivered as an error from the
|
`Handle` method. See [When delivery fails](#when-delivery-fails) for how to
|
||||||
handler's `Handle` method. See
|
receive it
|
||||||
[When delivery fails](#when-delivery-fails) for how to receive it
|
|
||||||
|
|
||||||
## Planned Features
|
## Planned Features
|
||||||
|
|
||||||
- supports delivering logs via tcp RELP (e.g. to remote rsyslog using imrelp)
|
- supports delivering logs via tcp RELP (e.g. to remote rsyslog using imrelp)
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -49,9 +47,9 @@ go get sneak.berlin/go/simplelog
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Below is an example of how to use SimpleLog in a Go application. This
|
Below is an example of how to use SimpleLog in a Go application. This example is
|
||||||
example is provided in the form of a `main.go` file, which demonstrates
|
provided in the form of a `main.go` file, which demonstrates logging at various
|
||||||
logging at various levels using structured logging syntax.
|
levels using structured logging syntax.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -73,61 +71,58 @@ func main() {
|
|||||||
## Attribute output
|
## Attribute output
|
||||||
|
|
||||||
Attributes reach every handler: the ones passed to the log call, the ones
|
Attributes reach every handler: the ones passed to the log call, the ones
|
||||||
accumulated with `WithAttrs`, and the ones qualified by the groups open at
|
accumulated with `WithAttrs`, and the ones qualified by the groups open at the
|
||||||
the time they were attached. `slog.Group` values nest, and
|
time they were attached. `slog.Group` values nest, and `slog.LogValuer` values
|
||||||
`slog.LogValuer` values are resolved to the value they stand for. A few
|
are resolved to the value they stand for. A few behaviours are worth knowing
|
||||||
behaviours are worth knowing before you rely on them.
|
before you rely on them.
|
||||||
|
|
||||||
**Your values are never modified.** Whatever you log is read and rendered,
|
**Your values are never modified.** Whatever you log is read and rendered, never
|
||||||
never written to. A map or a slice you pass to `slog.Any` comes back from
|
written to. A map or a slice you pass to `slog.Any` comes back from the logger
|
||||||
the logger exactly as you handed it over, even when a group later uses the
|
exactly as you handed it over, even when a group later uses the same key.
|
||||||
same key.
|
|
||||||
|
|
||||||
**Durations are nanoseconds in json, and readable on the console.** The
|
**Durations are nanoseconds in json, and readable on the console.** The json and
|
||||||
json and webhook payloads emit a `slog.Duration` as a number of
|
webhook payloads emit a `slog.Duration` as a number of nanoseconds, matching
|
||||||
nanoseconds, matching `slog.NewJSONHandler`, so a consumer can compare and
|
`slog.NewJSONHandler`, so a consumer can compare and aggregate the field without
|
||||||
aggregate the field without parsing it. The console line emits the same
|
parsing it. The console line emits the same duration as `3s`, matching
|
||||||
duration as `3s`, matching `slog.NewTextHandler`, because a person reads
|
`slog.NewTextHandler`, because a person reads it.
|
||||||
it.
|
|
||||||
|
|
||||||
**The json payload is an object, with the consequences an object has.**
|
**The json payload is an object, with the consequences an object has.** The
|
||||||
The record's own fields are named `Time`, `Level`, `Message` and `PC`, and
|
record's own fields are named `Time`, `Level`, `Message` and `PC`, and they own
|
||||||
they own those names: an attribute keyed after one of them is dropped from
|
those names: an attribute keyed after one of them is dropped from the json and
|
||||||
the json and webhook output. A key logged more than once keeps its last
|
webhook output. A key logged more than once keeps its last value there for the
|
||||||
value there for the same reason, with one exception: when both are
|
same reason, with one exception: when both are `slog.Group` values sharing a
|
||||||
`slog.Group` values sharing a key, the two groups are merged into one
|
key, the two groups are merged into one object holding the members of both,
|
||||||
object holding the members of both, rather than the second replacing the
|
rather than the second replacing the first. Neither the collision nor the merge
|
||||||
first. Neither the collision nor the merge applies to the console output,
|
applies to the console output, which is a line of text: every pair appears, in
|
||||||
which is a line of text: every pair appears, in order. If you need a field
|
order. If you need a field called `message`, pick a key that does not collide -
|
||||||
called `message`, pick a key that does not collide - the collision is
|
the collision is silent.
|
||||||
silent.
|
|
||||||
|
|
||||||
**Empty things follow the `slog.Handler` contract.** An empty `Attr` is
|
**Empty things follow the `slog.Handler` contract.** An empty `Attr` is ignored,
|
||||||
ignored, an empty group is elided along with its key, a group with an
|
an empty group is elided along with its key, a group with an empty key is
|
||||||
empty key is inlined into its parent, and `WithGroup("")` returns the
|
inlined into its parent, and `WithGroup("")` returns the handler unchanged.
|
||||||
handler unchanged.
|
|
||||||
|
|
||||||
## When delivery fails
|
## When delivery fails
|
||||||
|
|
||||||
Every handler returns an error from `Handle` when it could not deliver
|
Every handler returns an error from `Handle` when it could not deliver the
|
||||||
the record:
|
record:
|
||||||
|
|
||||||
- `ConsoleHandler` and `JSONHandler` return the error from their write to
|
- `ConsoleHandler` and `JSONHandler` return the error from their write to
|
||||||
stdout, wrapped, so `errors.Is` still matches the original
|
stdout, wrapped, so `errors.Is` still matches the original
|
||||||
- `WebhookHandler` returns an error when the request fails, and also when
|
- `WebhookHandler` returns an error when the request fails, and also when the
|
||||||
the server answers with a status outside 2xx, a redirect included,
|
server answers with a status outside 2xx, a redirect included, since it does
|
||||||
since it does not follow redirects
|
not follow redirects. A request that has not finished after 5 seconds fails
|
||||||
- `MultiplexHandler`, which simplelog installs as the default, passes the
|
with a timeout error, so a webhook server that never answers holds up a log
|
||||||
record to every handler it holds even after one of them fails, then
|
call for 5 seconds at most
|
||||||
returns all their errors joined with `errors.Join` (nil if none failed)
|
- `MultiplexHandler`, which simplelog installs as the default, passes the record
|
||||||
|
to every handler it holds even after one of them fails, then returns all their
|
||||||
|
errors joined with `errors.Join` (nil if none failed)
|
||||||
|
|
||||||
`slog.Info`, `slog.Error` and the other `slog.Logger` methods throw that
|
`slog.Info`, `slog.Error` and the other `slog.Logger` methods throw that error
|
||||||
error away. That is how `log/slog` works, and simplelog cannot change it.
|
away. That is how `log/slog` works, and simplelog cannot change it. To find out
|
||||||
To find out whether a record was delivered, build a `slog.Record` and pass
|
whether a record was delivered, build a `slog.Record` and pass it to the handler
|
||||||
it to the handler yourself, for example
|
yourself, for example `slog.Default().Handler().Handle(ctx, record)`, then check
|
||||||
`slog.Default().Handler().Handle(ctx, record)`, then check the error it
|
the error it returns. Console output takes the file and line from the record's
|
||||||
returns. Console output takes the file and line from the record's `PC`,
|
`PC`, which you set with `runtime.Callers` as the `log/slog` documentation
|
||||||
which you set with `runtime.Callers` as the `log/slog` documentation
|
|
||||||
shows. A record whose `PC` is zero prints `???:0` instead.
|
shows. A record whose `PC` is zero prints `???:0` instead.
|
||||||
|
|
||||||
## Entrypoints
|
## Entrypoints
|
||||||
@@ -139,9 +134,12 @@ development workflow, and the Makefile targets are thin shims that call them.
|
|||||||
The scripts are POSIX sh (not bash) so they run in minimal containers such as
|
The scripts are POSIX sh (not bash) so they run in minimal containers such as
|
||||||
alpine. We provide:
|
alpine. We provide:
|
||||||
|
|
||||||
- `script/bootstrap` — install all dependencies (go if missing, then
|
- `script/bootstrap` — install all dependencies (go if missing, goimports with
|
||||||
`go mod download`); golangci-lint is not installed, since it runs only in
|
`go install` at a pinned commit unless the installed one already reports the
|
||||||
Docker
|
pinned version, then `go mod download`; node through nvm at a pinned version
|
||||||
|
if node is missing, yarn at a pinned version if it is missing, then the
|
||||||
|
`prettier` that `package.json` and `yarn.lock` pin); golangci-lint is not
|
||||||
|
installed, since it runs only in Docker
|
||||||
- `script/setup` — set up the repo for development after a fresh clone: runs
|
- `script/setup` — set up the repo for development after a fresh clone: runs
|
||||||
`script/bootstrap`, then `script/install-precommit`
|
`script/bootstrap`, then `script/install-precommit`
|
||||||
- `script/projectname` — output the project name (our own extension); used by
|
- `script/projectname` — output the project name (our own extension); used by
|
||||||
@@ -149,23 +147,23 @@ alpine. We provide:
|
|||||||
- `script/test` — run the test suite under the race detector in Docker by
|
- `script/test` — run the test suite under the race detector in Docker by
|
||||||
building only the `test` stage of the `Dockerfile`, without the build cache,
|
building only the `test` stage of the `Dockerfile`, without the build cache,
|
||||||
so every run tests; the image is tagged `simplelog-test`
|
so every run tests; the image is tagged `simplelog-test`
|
||||||
- `script/lint` — run golangci-lint in Docker by building only the `lint`
|
- `script/lint` — run golangci-lint in Docker by building only the `lint` stage
|
||||||
stage of the `Dockerfile` (which also runs the format check), without the
|
of the `Dockerfile`, without the build cache, so every run lints; the image is
|
||||||
build cache, so every run lints; the image is tagged `simplelog-lint`
|
tagged `simplelog-lint`
|
||||||
- `script/fmt` — format all files with goimports (writes)
|
- `script/fmt` — format all files (writes): Go with the goimports that
|
||||||
- `script/fmt-check` — check formatting (read-only); fails if `gofmt -l`
|
`script/bootstrap` installs, then every `*.md` file with `prettier`
|
||||||
reports files
|
- `script/fmt-check` — check formatting (read-only); fails if `gofmt -l` reports
|
||||||
|
files, or if `prettier` would change any `*.md` file
|
||||||
- `script/check` — run all checks: `test`, `lint`, `fmt-check` (our own
|
- `script/check` — run all checks: `test`, `lint`, `fmt-check` (our own
|
||||||
extension)
|
extension)
|
||||||
- `script/docker` — build the Docker image without the build cache, tagged
|
- `script/docker` — build the Docker image without the build cache, tagged via
|
||||||
via `script/projectname` (byte-identical across repos); it also passes the
|
`script/projectname` (byte-identical across repos); it also passes the output
|
||||||
output of `git describe` as the `VERSION` build argument, which is ignored
|
of `git describe` as the `VERSION` build argument, which is ignored because
|
||||||
because this `Dockerfile` does not declare it
|
this `Dockerfile` does not declare it
|
||||||
- `script/cibuild` — cd to the repo root and build the Docker image without the
|
- `script/cibuild` — what CI runs: `script/bootstrap`, then `script/check`, then
|
||||||
build cache, tagged via `script/projectname` (what CI runs; the image build
|
the same image build as `script/docker` (byte-identical across repos)
|
||||||
runs the checks)
|
- `script/precommit` — run by the git pre-commit hook (our own extension); runs
|
||||||
- `script/precommit` — run by the git pre-commit hook (our own extension);
|
a `go mod tidy` guard, then `script/check`
|
||||||
runs a `go mod tidy` guard, then `script/check`
|
|
||||||
- `script/install-precommit` — installs the git pre-commit hook (our own
|
- `script/install-precommit` — installs the git pre-commit hook (our own
|
||||||
extension); `make hooks` shims to it
|
extension); `make hooks` shims to it
|
||||||
|
|
||||||
|
|||||||
+357
-86
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Repository Policies
|
title: Repository Policies
|
||||||
last_modified: 2026-07-06
|
last_modified: 2026-10-04
|
||||||
---
|
---
|
||||||
|
|
||||||
This document covers repository structure, tooling, and workflow standards. Code
|
This document covers repository structure, tooling, and workflow standards. Code
|
||||||
@@ -60,17 +60,28 @@ style conventions are in separate documents:
|
|||||||
prerequisite since nvm requires bash. yarn is then pinned via
|
prerequisite since nvm requires bash. yarn is then pinned via
|
||||||
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
|
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
|
||||||
always exact versions. `script/cibuild` runs the CI build: it changes to the
|
always exact versions. `script/cibuild` runs the CI build: it changes to the
|
||||||
repo root and runs `docker build .`; the Gitea workflow calls it. Four further
|
repo root, runs `script/bootstrap`, runs `script/check`, and builds the image
|
||||||
scripts are our own extensions to the standard: `script/check` runs
|
with the version; the Gitea workflow calls it. **`script/cibuild` runs
|
||||||
`script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is
|
`script/bootstrap` first**, because the workflow checks out the repo and runs
|
||||||
what the git pre-commit hook runs, and it calls `script/check`;
|
nothing else, while `script/fmt-check` runs the formatter on the host: on a
|
||||||
`script/install-precommit` installs the git pre-commit hook (the `make hooks`
|
pristine checkout with nothing installed the run dies there, after the
|
||||||
target shims to it); and `script/projectname` (literally that filename) simply
|
containerised gates have passed. **The bootstrap alone is not enough**:
|
||||||
outputs the project's name. Scripts that need the name call
|
`script/bootstrap` installs node and yarn under nvm and leaves neither on the
|
||||||
`script/projectname` — e.g. `script/docker` assembles its image tag from it —
|
`PATH` of the shell that called it, so a bare `yarn` still exits 127. The host
|
||||||
so those scripts stay byte-identical across all repos. Repo-type-specific
|
entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore
|
||||||
pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in
|
source nvm for the pinned node version before invoking it, exactly as
|
||||||
`script/precommit`, not in the hook itself. Model scripts are at
|
`script/bootstrap`'s own install step does. A runner carrying nothing but
|
||||||
|
docker and git then gets through `script/check`. Four further scripts are our
|
||||||
|
own extensions to the standard: `script/check` runs `script/test`,
|
||||||
|
`script/lint` and `script/fmt-check`; `script/precommit` is what the git
|
||||||
|
pre-commit hook runs, and it calls `script/check`; `script/install-precommit`
|
||||||
|
installs the git pre-commit hook (the `make hooks` target shims to it); and
|
||||||
|
`script/projectname` (literally that filename) simply outputs the project's
|
||||||
|
name. Scripts that need the name call `script/projectname` — e.g.
|
||||||
|
`script/docker` assembles its image tag from it — so those scripts stay
|
||||||
|
byte-identical across all repos. Repo-type-specific pre-commit extras (e.g.
|
||||||
|
`go mod tidy` verification in Go repos) belong in `script/precommit`, not in
|
||||||
|
the hook itself. Model scripts are at
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
|
||||||
must document the provided scripts in an **Entrypoints** section (see the
|
must document the provided scripts in an **Entrypoints** section (see the
|
||||||
README requirements below).
|
README requirements below).
|
||||||
@@ -89,87 +100,198 @@ style conventions are in separate documents:
|
|||||||
contributor should be able to understand the entire development workflow by
|
contributor should be able to understand the entire development workflow by
|
||||||
reading the Makefile.
|
reading the Makefile.
|
||||||
|
|
||||||
- Every repo should have a `Dockerfile`. All Dockerfiles must run `make check`
|
- Every repo should have a `Dockerfile`, and it carries the repo's gates: a
|
||||||
as a build step so the build fails if the branch is not green. For non-server
|
`lint` phase and a `test` phase, with the final stage depending on both so the
|
||||||
repos, the Dockerfile should bring up a development environment and run
|
image cannot be built unless they pass. For non-server repos the final stage
|
||||||
`make check`. For server repos, `make check` should run as an early build
|
brings up a development environment; for server repos it is the runtime image.
|
||||||
stage before the final image is assembled. Dockerfiles install development
|
The gate phases and the build stage start from their pinned base images and
|
||||||
prerequisites by running `script/bootstrap` rather than duplicating installs
|
install what those images lack either inline, as the canonical Go `Dockerfile`
|
||||||
inline; COPY `script/` and the dependency manifests (`package.json` +
|
below does for `git`, or by running `script/bootstrap`, as the `prompts`
|
||||||
`yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap
|
repo's own `Dockerfile` does for its yarn packages. The development
|
||||||
layer stays cached until dependencies change.
|
environment stage installs development prerequisites by running
|
||||||
|
`script/bootstrap` rather than duplicating its installs inline. A stage that
|
||||||
|
runs `script/bootstrap` COPYs `script/` and the dependency manifests
|
||||||
|
(`package.json` + `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it.
|
||||||
|
|
||||||
- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go
|
- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is
|
||||||
repos use a multistage build where linting runs in an independent stage based
|
no separate lint file. `script/lint` and `script/test` each build one phase
|
||||||
on the `golangci/golangci-lint` image (pinned by hash). This stage runs
|
and nothing else:
|
||||||
`make fmt-check` and `make lint` before the full build begins. The build stage
|
|
||||||
then declares an explicit dependency on the lint stage via
|
|
||||||
`COPY --from=lint /src/go.sum /dev/null`, which forces BuildKit to complete
|
|
||||||
linting before proceeding to compilation and tests. This ensures lint failures
|
|
||||||
surface in seconds rather than minutes, without blocking on dependency
|
|
||||||
download or compilation in the build stage.
|
|
||||||
|
|
||||||
The standard pattern for a Go repo Dockerfile is:
|
```sh
|
||||||
|
docker build --no-cache --target lint -t "$(script/projectname)-lint" .
|
||||||
|
docker build --no-cache --target test -t "$(script/projectname)-test" .
|
||||||
|
```
|
||||||
|
|
||||||
|
**A stage that is not the last one in the file is built only when the final
|
||||||
|
stage's chain depends on it, or when `--target` names it.** That is why the
|
||||||
|
two gates are always invoked by name here, and why the final stage carries a
|
||||||
|
`COPY --from=` of a harmless file from each of them: without that edge a
|
||||||
|
plain `docker build .` builds the last stage alone and exits 0 having linted
|
||||||
|
and tested nothing.
|
||||||
|
|
||||||
|
**Every `docker build` in `script/` is tagged**, here and in
|
||||||
|
`script/cibuild` and `script/docker`. An untagged build leaves a dangling
|
||||||
|
image behind on every invocation, on every developer host and every CI
|
||||||
|
runner; a tagged one replaces the previous image.
|
||||||
|
|
||||||
|
Inside a phase the tool is invoked directly — `golangci-lint`, `go test`,
|
||||||
|
`eslint`, `prettier` — never through `make lint` or `script/test`, which are
|
||||||
|
themselves a `docker build` and would recurse into a daemon that does not
|
||||||
|
exist in a build step. Formatting is the exception and stays on the host:
|
||||||
|
`script/fmt` writes the working tree, and `script/fmt-check` is its
|
||||||
|
read-only twin.
|
||||||
|
|
||||||
|
**No lint verdict may come from a host invocation of the linter.** On a
|
||||||
|
shared host golangci-lint reads a result cache keyed on file content rather
|
||||||
|
than location, so a second checkout of the same content is served the first
|
||||||
|
one's findings, and a host-global lock in `$TMPDIR` makes concurrent runs
|
||||||
|
exit non-zero with `parallel golangci-lint is running` — a status a caller
|
||||||
|
cannot tell from real findings. Both have produced wrong verdicts in this
|
||||||
|
org, in both directions. A container has its own cache, its own `TMPDIR` and
|
||||||
|
a digest-pinned binary, so neither is reachable.
|
||||||
|
|
||||||
|
- **Any build that runs checks is built with `--no-cache`.** Docker invalidates
|
||||||
|
a `COPY` layer only when the copied content changes, so on an unchanged tree
|
||||||
|
the check `RUN` is served from cache, nothing executes, and the build still
|
||||||
|
exits 0. Every `docker build` in `script/` therefore passes `--no-cache`:
|
||||||
|
`script/lint`, `script/test`, `script/cibuild` and `script/docker` are the
|
||||||
|
four, and there is no fifth — `script/check` runs the two gate phases and
|
||||||
|
`script/fmt-check`, and builds no image of its own. A bare `docker build .` is
|
||||||
|
not evidence that anything ran: a sub-second build reporting success is a
|
||||||
|
cache hit, not a result. Never invalidate by pruning — `docker builder prune`
|
||||||
|
and friends destroy a build cache shared with every other build on the host.
|
||||||
|
When a check is added or changed, prove it works by planting a defect it must
|
||||||
|
catch and watching the run fail on it, then revert the defect. A green run
|
||||||
|
alone shows neither that the check ran nor that it covers what it should.
|
||||||
|
|
||||||
|
- **The gate phases are separate stages, and the build stage depends on both.**
|
||||||
|
The lint phase is based on the `golangci/golangci-lint` image (pinned by
|
||||||
|
hash), so lint failures surface in seconds rather than after a full compile,
|
||||||
|
and the test phase is based on the Debian Go image. The canonical Go repo
|
||||||
|
`Dockerfile`:
|
||||||
|
|
||||||
```dockerfile
|
```dockerfile
|
||||||
# Lint stage — fast feedback on formatting and lint issues
|
# Lint phase
|
||||||
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD
|
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD
|
||||||
FROM golangci/golangci-lint@sha256:... AS lint
|
FROM golangci/golangci-lint@sha256:... AS lint
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make fmt-check
|
RUN golangci-lint run --config .golangci.yml ./...
|
||||||
RUN make lint
|
|
||||||
|
|
||||||
# Build stage
|
# Test phase. -race needs cgo and so a C compiler, which the Debian Go
|
||||||
# golang:1.x-alpine, YYYY-MM-DD
|
# image ships and the alpine one does not.
|
||||||
FROM golang@sha256:... AS builder
|
# golang:1.x, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS test
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
# Force BuildKit to run the lint stage before proceeding
|
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
|
||||||
|
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make test
|
RUN go test -timeout 90s -race -cover ./... || \
|
||||||
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
|
go test -timeout 90s -race -v ./...; exit 1; }
|
||||||
|
|
||||||
ARG VERSION=dev
|
# Build stage. Nothing is wanted from either phase above; the copies
|
||||||
RUN CGO_ENABLED=0 go build -trimpath \
|
# are what make BuildKit build them first, so this stage cannot run
|
||||||
-ldflags="-s -w -X main.Version=${VERSION}" \
|
# unless lint and test passed.
|
||||||
-o /app ./cmd/app/
|
# golang:1.x-alpine, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS builder
|
||||||
|
COPY --from=lint /src/go.sum /dev/null
|
||||||
|
COPY --from=test /src/go.sum /dev/null
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
# A tar-stream context keeps the sender's file owners, which git refuses.
|
||||||
|
RUN git config --system --add safe.directory /src
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
|
||||||
# Runtime stage
|
# The VERSION build arg when one is given, otherwise
|
||||||
|
# `git describe --tags --always` on the .git in the build context. With
|
||||||
|
# .git present, a version that is still empty, dev or unknown fails the
|
||||||
|
# build: git is missing or could not read the checkout.
|
||||||
|
ARG VERSION
|
||||||
|
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \
|
||||||
|
if [ -e .git ]; then \
|
||||||
|
case "$VERSION" in ""|dev|unknown) \
|
||||||
|
echo "version is '$VERSION' although .git is present" >&2; \
|
||||||
|
exit 1 ;; \
|
||||||
|
esac; \
|
||||||
|
fi; \
|
||||||
|
CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags="-s -w -X main.Version=${VERSION}" \
|
||||||
|
-o /app ./cmd/app/
|
||||||
|
|
||||||
|
# Runtime stage, and the last one
|
||||||
FROM alpine@sha256:...
|
FROM alpine@sha256:...
|
||||||
COPY --from=builder /app /usr/local/bin/app
|
COPY --from=builder /app /usr/local/bin/app
|
||||||
ENTRYPOINT ["app"]
|
ENTRYPOINT ["app"]
|
||||||
```
|
```
|
||||||
|
|
||||||
Key points:
|
Key points:
|
||||||
- The lint stage uses the `golangci/golangci-lint` image directly (it
|
- The lint phase uses the `golangci/golangci-lint` image directly (it has
|
||||||
includes both Go and the linter), so there is no need to install the
|
both Go and the linter), so nothing needs installing.
|
||||||
linter separately.
|
- `COPY --from=<phase> /src/go.sum /dev/null` is a no-op copy whose only
|
||||||
- `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates
|
purpose is the ordering edge. BuildKit runs stages in parallel by default,
|
||||||
a stage dependency. BuildKit runs stages in parallel by default; without
|
and a stage nothing depends on is not built at all, so without these two
|
||||||
this line, the build stage would not wait for lint to finish and a lint
|
lines a red gate would not fail the build.
|
||||||
failure might not fail the overall build.
|
- Keep the runtime stage last, and if you add a stage after it, give it the
|
||||||
|
same two copies. A plain `docker build .` builds the last stage's chain
|
||||||
|
and nothing else.
|
||||||
- If the project uses `//go:embed` directives that reference build artifacts
|
- If the project uses `//go:embed` directives that reference build artifacts
|
||||||
(e.g. a web frontend compiled in a separate stage), the lint stage must
|
(e.g. a web frontend compiled in a separate stage), the lint phase must
|
||||||
create placeholder files so the embed directives resolve. Example:
|
create placeholder files so the embed directives resolve. Example:
|
||||||
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
|
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
|
||||||
The lint stage should not depend on the actual build output — it exists to
|
- If the project requires CGO or system libraries for linting, install them
|
||||||
fail fast.
|
in the lint phase. The `golangci/golangci-lint` image is Debian-based and
|
||||||
- If the project requires CGO or system libraries for linting (e.g.
|
has no `apk`, so install with `apt-get` under the Debian package name
|
||||||
`vips-dev`), install them in the lint stage with `apk add`.
|
(`libvips-dev`, where alpine says `vips-dev`), and delete the package
|
||||||
- The build stage runs `make test` after compilation setup. Tests run in the
|
lists in the same `RUN`, so the layer does not keep them:
|
||||||
build stage, not the lint stage, because they may require compiled
|
|
||||||
artifacts or heavier dependencies.
|
```dockerfile
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends libvips-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
```
|
||||||
|
|
||||||
|
- `.dockerignore` lets `.git` into the build context. It keeps out every git
|
||||||
|
`config` at any depth (`**/.git/config`, `**/.git/modules/**/config`): the
|
||||||
|
repository's own, each submodule's under `.git/modules/`, and that of a
|
||||||
|
submodule keeping its own `.git` directory. `git describe` does not need
|
||||||
|
them, and each can hold a credential: a password in a remote URL, or the
|
||||||
|
token the CI checkout step stores there. A submodule whose name has a
|
||||||
|
`config` segment (`config`, `deploy/config`, `config/lib`) loses its whole
|
||||||
|
git directory to `**/.git/modules/**/config`, and Go's version stamping
|
||||||
|
then fails the build: give it a name without that segment
|
||||||
|
(`git submodule add --name`). The stage that compiles has `git` (the
|
||||||
|
Debian Go image has it; an alpine one needs `apk add --no-cache git`) and
|
||||||
|
takes the version from the `VERSION` build argument when one is given,
|
||||||
|
otherwise from `git describe --tags --always`. That gives the tag on a
|
||||||
|
tagged commit; on a later commit, the tag, the number of commits since it
|
||||||
|
and the short commit (`v1.2.3-4-gabc1234`); and the short commit when no
|
||||||
|
tag is reachable. The stage that compiles also marks its working directory
|
||||||
|
safe for git (`git config --system --add safe.directory /src`): a context
|
||||||
|
sent as a tar stream keeps the sender's file owners, and git refuses a
|
||||||
|
checkout owned by another user, so the version would come out empty.
|
||||||
|
`ARG VERSION` has no default, and the build fails if the context carries
|
||||||
|
`.git` and the version still comes out empty, `dev` or `unknown`. A plain
|
||||||
|
`docker build .` with no build arguments must succeed; a Dockerfile that
|
||||||
|
refuses an empty build argument drops that refusal and keeps the argument.
|
||||||
|
|
||||||
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
||||||
runs `script/cibuild` (which runs `docker build .`) on push. Since the
|
runs `script/cibuild` on push, and checks out the repo as its only other step.
|
||||||
Dockerfile already runs `make check`, a successful build implies all checks
|
That script bootstraps, runs the gate phases, and then builds the image, so a
|
||||||
pass.
|
successful run means every check passed; a bare `docker build .` does not
|
||||||
|
carry the same guarantee, because its gate phases may come from the cache. The
|
||||||
|
image build is uncached and so runs the gate phases a second time. That is the
|
||||||
|
price of the rule above, and it is worth paying: the image that ships is built
|
||||||
|
from a run of its own gates rather than from a cache entry. A separate
|
||||||
|
workflow limited to `main` by a `branches` list under `on: push` cannot be
|
||||||
|
checked by review: to try a change to it, add the feature branch to that list
|
||||||
|
and push, then remove the branch from the list again before merging. Keep any
|
||||||
|
job in it that publishes behind `if: github.ref_name == 'main'`, so the run
|
||||||
|
from the feature branch publishes nothing.
|
||||||
|
|
||||||
- Use platform-standard formatters: `black` for Python, `prettier` for
|
- Use platform-standard formatters: `black` for Python, `prettier` for
|
||||||
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
||||||
@@ -189,14 +311,21 @@ style conventions are in separate documents:
|
|||||||
module under test to verify it compiles/parses. There is no excuse for
|
module under test to verify it compiles/parses. There is no excuse for
|
||||||
`make test` to be a no-op.
|
`make test` to be a no-op.
|
||||||
|
|
||||||
- `make test` must complete in under 20 seconds. Add a 30-second timeout in the
|
- `make test` must complete in under 60 seconds. That is the hard cap, and a
|
||||||
Makefile.
|
suite that exceeds it fails. Under 20 seconds is the target. A suite between
|
||||||
|
20 and 60 seconds is still green, but the overage must be filed as an
|
||||||
|
improvement bug against that repo. Add a 90-second timeout to the test
|
||||||
|
invocation (`go test -timeout 90s`). The backstop deliberately sits above the
|
||||||
|
hard cap so that it catches a genuinely hung test rather than a merely slow
|
||||||
|
one.
|
||||||
|
|
||||||
- **`make test` should use the conditional verbose rerun pattern.** Run tests
|
- **The test command should use the conditional verbose rerun pattern.** Run
|
||||||
without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to
|
tests without `-v` (verbose) first. If tests fail, automatically rerun with
|
||||||
show full output. This keeps CI logs and `docker build` output clean on
|
`-v` to show full output. This keeps CI logs and `docker build` output clean
|
||||||
success (just package/suite summaries) while providing full diagnostic detail
|
on success (just package/suite summaries) while providing full diagnostic
|
||||||
on failure (every test case, every assertion). The general shell pattern:
|
detail on failure (every test case, every assertion). The command lives in the
|
||||||
|
`test` phase of the `Dockerfile`, since `script/test` builds that phase; the
|
||||||
|
Makefile form below is the same pattern for any repo-local invocation:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@@ -209,11 +338,26 @@ style conventions are in separate documents:
|
|||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@go test -timeout 30s -race -cover ./... || \
|
@go test -count=1 -timeout 90s -race -cover ./... || \
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
go test -timeout 30s -race -v ./...; exit 1; }
|
go test -count=1 -timeout 90s -race -v ./...; exit 1; }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`-count=1` is required on both invocations: it defeats Go's test _result_
|
||||||
|
cache, so neither run can report a stored pass in place of running the
|
||||||
|
tests. It leaves the build cache alone, so it costs the runtime of the suite
|
||||||
|
and no recompilation.
|
||||||
|
|
||||||
|
That cache is Go's own, separate from Docker's layer cache. Go stores a
|
||||||
|
passing result in its cache directory (`GOCACHE`), and when the same tests
|
||||||
|
run again on unchanged code it prints that result, marked `(cached)`,
|
||||||
|
without running them. That matters on a developer's machine, where this
|
||||||
|
target runs and the directory lasts from one run to the next. The `test`
|
||||||
|
phase of the `Dockerfile` needs no `-count=1`: its base image holds no
|
||||||
|
result for this repo's tests and nothing before its `go test` step runs a
|
||||||
|
test, so there is nothing to replay. `--no-cache` (above) is what makes that
|
||||||
|
step run on an unchanged tree.
|
||||||
|
|
||||||
Python example:
|
Python example:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
@@ -239,10 +383,84 @@ style conventions are in separate documents:
|
|||||||
must be in `.gitignore`. No exceptions.
|
must be in `.gitignore`. No exceptions.
|
||||||
|
|
||||||
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
|
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
|
||||||
editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`.
|
editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`),
|
||||||
Fetch the standard `.gitignore` from
|
language build artifacts, and `node_modules/`. Fetch the standard `.gitignore`
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when
|
||||||
a new repo.
|
setting up a new repo. These patterns are written to `.gitignore`'s own
|
||||||
|
semantics, in which an unanchored pattern already matches at every depth; they
|
||||||
|
are not a `.dockerignore` and must not be transplanted into one unmodified.
|
||||||
|
|
||||||
|
- **`.dockerignore` does not use `.gitignore` semantics, and copying patterns
|
||||||
|
across unmodified leaves secrets in the build context.** Docker matches with
|
||||||
|
`moby/patternmatcher`: `filepath.Match` semantics plus a `**` extension, so
|
||||||
|
`*` does not cross `/` and a pattern without a leading `**/` is anchored at
|
||||||
|
the build-context root. A `.dockerignore` listing `.env`, `*.pem` and `*.key`
|
||||||
|
therefore excludes only the copies at the repository root, while `config/.env`
|
||||||
|
and `certs/server.key` still reach the context and can land in an image layer
|
||||||
|
— which is more dangerous than a short file with no secret patterns at all,
|
||||||
|
because it reads as solved and stops anyone looking. Give every
|
||||||
|
depth-independent pattern the `**/` prefix and leave only genuinely
|
||||||
|
root-anchored entries unprefixed: `.claude`, and the repo's own host-built
|
||||||
|
binary, written `/myapp` and never `**/myapp`, which would also match
|
||||||
|
`cmd/myapp/` and delete the package directory from the context. Matching is
|
||||||
|
case-sensitive, and an ALL-CAPS twin per pattern still misses `Server.Key`, so
|
||||||
|
secret names use character ranges — `**/*.[kK][eE][yY]`, `**/*.[pP][eE][mM]`,
|
||||||
|
and likewise for `.envrc` and the extensionless SSH keys. Where such a pattern
|
||||||
|
also catches something the build needs, re-include it with a negation
|
||||||
|
(`!docs/example.env`); deleting the pattern reopens the exposure for every
|
||||||
|
other file it covers. Fetch the standard `.dockerignore` from
|
||||||
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.dockerignore` and extend
|
||||||
|
it with the repo's own artifacts.
|
||||||
|
|
||||||
|
- **In-repo agent scratch belongs in both files, written to each file's own
|
||||||
|
semantics.** `.claude/` holds one worktree per in-flight agent — an entire
|
||||||
|
additional checkout of the repo — so under `COPY . .` the build context
|
||||||
|
inflates by a multiple of the repo and another session's unreviewed work can
|
||||||
|
be copied into an image layer. In `.gitignore` the entry is `.claude/`,
|
||||||
|
unanchored. In `.dockerignore` it is `.claude`, anchored and with **no** `**/`
|
||||||
|
prefix, because the prefixed form would also delete any nested directory of
|
||||||
|
that name from the build. Anchoring carries a known gap that the canonical
|
||||||
|
`.dockerignore` states in its own comment, since consuming repos receive the
|
||||||
|
file and not the tracker: the directory is created in the agent's working
|
||||||
|
directory, so a repo running agents in subdirectories still ships
|
||||||
|
`services/api/.claude/` and must add its own anchored entry there.
|
||||||
|
|
||||||
|
- **A plain `docker build .` of a clone stamps the version that
|
||||||
|
`git describe --tags --always` gives**, derived from the `.git` in the build
|
||||||
|
context as the canonical `Dockerfile` above shows. Without its failure check,
|
||||||
|
a missing `git` or an unreadable checkout would leave `-X main.Version=` empty
|
||||||
|
and the build would still exit 0. `script/docker` and `script/cibuild` pass
|
||||||
|
the version they compute on the host; it takes precedence. They do this
|
||||||
|
byte-identically across repos:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Own line: a failing command substitution inside an argument does not
|
||||||
|
# trip `set -e`, so the inline form degrades to an empty constant.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$(script/projectname)" .
|
||||||
|
```
|
||||||
|
|
||||||
|
`--always` makes an untagged repo yield an abbreviated commit hash rather
|
||||||
|
than failing, and the `[ -n "$version" ]` line is the single place the
|
||||||
|
fallback is applied — a live check that fires on a build from an export with
|
||||||
|
no `.git` and on a repository with no commits yet. Do not fold it into the
|
||||||
|
substitution as `|| echo unknown`, which makes the guard unreachable. The
|
||||||
|
Dockerfile's side is `ARG VERSION` in the stage that compiles, declared
|
||||||
|
there because `ARG` is stage-scoped; passing `VERSION` to a repo whose
|
||||||
|
Dockerfile declares no such `ARG` is ignored and costs nothing, which is why
|
||||||
|
the scripts stay byte-identical. One consequence for CI: the standard
|
||||||
|
checkout action clones shallow and fetches no tags, so a repo that embeds a
|
||||||
|
tag-derived version must set `fetch-depth: 0` on its checkout step.
|
||||||
|
|
||||||
|
- **Verify `.dockerignore` by enumerating the image, not by reading the
|
||||||
|
patterns.** Plant files at the root _and_ at least two directories deep, build
|
||||||
|
a probe image that does `COPY . .`, and list what actually landed
|
||||||
|
(`docker run --rm --entrypoint find IMAGE /app`). The `transferring context`
|
||||||
|
size is not a substitute: a nested secret is a few bytes, and BuildKit
|
||||||
|
transfers only the delta from the previous build.
|
||||||
|
|
||||||
- **No build artifacts in version control.** Code-derived data (compiled
|
- **No build artifacts in version control.** Code-derived data (compiled
|
||||||
bundles, minified output, generated assets) must never be committed to the
|
bundles, minified output, generated assets) must never be committed to the
|
||||||
@@ -258,9 +476,56 @@ style conventions are in separate documents:
|
|||||||
- Make all changes on a feature branch. You can do whatever you want on a
|
- Make all changes on a feature branch. You can do whatever you want on a
|
||||||
feature branch.
|
feature branch.
|
||||||
|
|
||||||
- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only
|
- `.golangci.yml` is standardized. The vendored copy in a consuming repo must
|
||||||
manually by the user. Fetch from
|
_NEVER_ be modified by an agent: fetch it from
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`.
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it
|
||||||
|
byte-identical, so that no repo can quietly loosen its own linting. Linter
|
||||||
|
configuration changes are made to the canonical copy in the `prompts` repo and
|
||||||
|
reach consuming repos by re-vendoring; an agent may open a PR against
|
||||||
|
canonical, which only the user merges. One list is exempt from byte-identity,
|
||||||
|
because it cannot be written once for every repo: the `deny` list of the
|
||||||
|
`test-support` depguard rule, where a repo names its own test-support packages
|
||||||
|
by full import path. A repo adds entries there and changes nothing else, and a
|
||||||
|
re-vendor carries its entries forward. The canonical golangci-lint version is
|
||||||
|
v2.14.0 (released 2026-09-24), pinned as the digest of the lint phase's base
|
||||||
|
image
|
||||||
|
(`golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f`,
|
||||||
|
which reports `2.14.0 built with go1.27.0 from 114493f9`). A module's `go`
|
||||||
|
directive must not name a newer Go minor version than the one golangci-lint
|
||||||
|
was built with, or golangci-lint refuses to lint it: this release lints
|
||||||
|
`go 1.27.1` but not `go 1.28`. That digest is the only pin, since no repo
|
||||||
|
installs golangci-lint on the host. A repo sets the lint phase digest to the
|
||||||
|
one named here and re-vendors `.golangci.yml` in the same commit, whichever of
|
||||||
|
the two prompted the change: the canonical copy can name linters that an older
|
||||||
|
golangci-lint rejects, and a newer golangci-lint can add linters that
|
||||||
|
`default: all` switches on until the canonical copy disables them.
|
||||||
|
|
||||||
|
- **`script/bootstrap` installs a pinned tool by comparing versions, never by
|
||||||
|
testing presence.** An `if ! command -v <tool>; then install; fi` guard tests
|
||||||
|
`PATH` only, so on an already-provisioned machine the pin is inert and a
|
||||||
|
version bump is a silent no-op — while the Dockerfile, installing into a clean
|
||||||
|
image, gets the pinned version, so a local `make check` and `make docker` can
|
||||||
|
disagree about what the tool even is. The canonical form:
|
||||||
|
- compares the installed version against the pin over the **whole** version
|
||||||
|
token; a parser that stops at the first `-` reports `2.12.2` for a host
|
||||||
|
running `2.12.2-rc1` and skips the install;
|
||||||
|
- treats absent, non-zero, empty or unrecognised `--version` output as a
|
||||||
|
mismatch, so the failure direction is a redundant install and never a
|
||||||
|
skipped one;
|
||||||
|
- after installing, re-resolves the binary the way callers do — `hash -r`,
|
||||||
|
then through `PATH`, not through the directory the installer wrote to —
|
||||||
|
and fails naming the resolved path, since an install that a shadowing
|
||||||
|
binary hides succeeds while changing nothing any caller sees;
|
||||||
|
- is actually called, and prints the version on both success paths: a
|
||||||
|
function defined and never invoked has the same exit status and the same
|
||||||
|
empty output as one that worked.
|
||||||
|
|
||||||
|
Keep it POSIX sh: no arrays, no `[[`, no `grep -P`.
|
||||||
|
|
||||||
|
A Go tool a repo needs on the host is installed with `go install` pinned to
|
||||||
|
a commit hash (`go install <package>@<commit hash>`). It is never tracked as
|
||||||
|
a `go.mod` tool dependency or through a `tools.go` file, either of which
|
||||||
|
pulls the tool's own dependencies into the repo's `go.mod` and `go.sum`.
|
||||||
|
|
||||||
- When pinning images or packages by hash, add a comment above the reference
|
- When pinning images or packages by hash, add a comment above the reference
|
||||||
with the version and date (YYYY-MM-DD).
|
with the version and date (YYYY-MM-DD).
|
||||||
@@ -374,12 +639,14 @@ style conventions are in separate documents:
|
|||||||
settings.
|
settings.
|
||||||
|
|
||||||
- Avoid putting files in the repo root unless necessary. Root should contain
|
- Avoid putting files in the repo root unless necessary. Root should contain
|
||||||
only project-level config files (`README.md`, `Makefile`, `Dockerfile`,
|
only project-level config files (`README.md`, `AGENTS.md`, `Makefile`,
|
||||||
`LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and
|
`Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`,
|
||||||
language-specific config). Everything else goes in a subdirectory. Canonical
|
and language-specific config). Everything else goes in a subdirectory.
|
||||||
subdirectory names:
|
Canonical subdirectory names:
|
||||||
- `bin/` — executable scripts and tools
|
- `bin/` — executable scripts and tools
|
||||||
- `cmd/` — Go command entrypoints
|
- `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose
|
||||||
|
body is a single call into `internal/` or `pkg/`, no project logic in
|
||||||
|
`cmd/`
|
||||||
- `configs/` — configuration templates and examples
|
- `configs/` — configuration templates and examples
|
||||||
- `deploy/` — deployment manifests (k8s, compose, terraform)
|
- `deploy/` — deployment manifests (k8s, compose, terraform)
|
||||||
- `docs/` — documentation and markdown (README.md stays in root)
|
- `docs/` — documentation and markdown (README.md stays in root)
|
||||||
@@ -406,3 +673,7 @@ style conventions are in separate documents:
|
|||||||
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
||||||
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
|
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
|
||||||
- Python: `pyproject.toml`
|
- Python: `pyproject.toml`
|
||||||
|
|
||||||
|
- Guidance for coding agents lives in one `AGENTS.md` at the repository root. It
|
||||||
|
is never committed under a file or directory named after one agent tool, such
|
||||||
|
as `CLAUDE.md` or `.claude/`, and never split into separate memory files.
|
||||||
|
|||||||
@@ -1,79 +1,89 @@
|
|||||||
# Workflow
|
# Workflow
|
||||||
|
|
||||||
* branch (from `main`)
|
- branch (from `main`)
|
||||||
* do the work in Next Step
|
- do the work in Next Step
|
||||||
* move Next Step to the top of Completed Steps
|
- move Next Step to the top of Completed Steps
|
||||||
* move the top item of Future Steps into Next Step
|
- move the top item of Future Steps into Next Step
|
||||||
* commit (`TODO.md` changes in the same commit as the work)
|
- commit (`TODO.md` changes in the same commit as the work)
|
||||||
* merge to `main` if the branch is not protected, otherwise open a PR
|
- merge to `main` if the branch is not protected, otherwise open a PR
|
||||||
* push
|
- push
|
||||||
|
|
||||||
# Status
|
# Status
|
||||||
|
|
||||||
1.0+
|
1.0+
|
||||||
|
|
||||||
Tagged v1.0.0 (2024-06-14) and 1.0.1 (2026-02-08). In post-1.0
|
Tagged v1.0.0 (2024-06-14) and 1.0.1 (2026-02-08). In post-1.0 maintenance; the
|
||||||
maintenance; the library is referenced by the Go styleguide.
|
library is referenced by the Go styleguide.
|
||||||
|
|
||||||
# Next Step
|
# Next Step
|
||||||
|
|
||||||
Bring the Makefile up to policy in one commit: add fmt-check, check, and
|
Restructure README.md into the standard sections: Description, Getting Started,
|
||||||
hooks targets (test/lint/fmt/docker exist) and add the missing policy
|
Rationale, Design, TODO, License, Author
|
||||||
files it depends on: .golangci.yml, REPO_POLICIES.md, .editorconfig,
|
|
||||||
.dockerignore, and .gitea/workflows/check.yml running make check.
|
|
||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
* 2026-10-06: the console handler takes the file and line it prints from
|
- 2026-10-06: `make fmt` and `make fmt-check` also format Markdown, with
|
||||||
the record's `PC` instead of counting stack frames, so they name the
|
`prettier` at the standard settings, pinned through `package.json` and
|
||||||
call site whether the record came through a `slog.Logger` or straight
|
`yarn.lock`; `script/bootstrap` installs node and yarn for it, and the
|
||||||
to `Handle`
|
existing Markdown was formatted once
|
||||||
* 2026-10-06: the tests run under the race detector, in Docker:
|
- 2026-10-06: re-vendored the standard files from `sneak/prompts` at commit
|
||||||
`script/test` builds the `test` stage of the `Dockerfile`, which runs
|
`dd4027b`: `REPO_POLICIES.md`, the CI workflow, `.gitignore`, and
|
||||||
`go test -race`, and a new final stage makes a plain `docker build`
|
`.golangci.yml` together with the lint stage's new image, plus the
|
||||||
run both the `lint` and `test` stages
|
`.editorconfig` and `.dockerignore` this repo lacked, which finishes the
|
||||||
* 2026-10-06: the linter runs only in Docker: `script/lint` builds the
|
Makefile and policy-files step. `script/cibuild` now bootstraps and runs
|
||||||
`lint` stage of the `Dockerfile`, every `docker build` in `script/`
|
`script/check` before building the image, the format check runs only on the
|
||||||
runs without the build cache, and `script/bootstrap` no longer
|
host, the last `Dockerfile` stage runs `script/bootstrap`, which installs
|
||||||
installs golangci-lint
|
goimports at a pinned commit
|
||||||
* 2026-10-06: every handler now returns a failed delivery from `Handle`
|
- 2026-10-06: a webhook request now times out after 5 seconds, so a server that
|
||||||
instead of discarding it: console and JSON return the stdout write
|
never answers no longer stops every log call; the webhook handler also reads
|
||||||
error, the webhook also fails on a non-2xx answer, and the multiplex
|
each answer to the end so its connection is reused
|
||||||
delivers to every handler and returns their errors joined
|
- 2026-10-06: the console handler takes the file and line it prints from the
|
||||||
* 2026-08-10: fixed every handler discarding slog attributes: console,
|
record's `PC` instead of counting stack frames, so they name the call site
|
||||||
JSON and webhook handlers now emit record attributes, accumulate
|
whether the record came through a `slog.Logger` or straight to `Handle`
|
||||||
WithAttrs without mutating the receiver, and honour WithGroup;
|
- 2026-10-06: the tests run under the race detector, in Docker: `script/test`
|
||||||
slog.Group values nest and LogValuer values are resolved; console
|
builds the `test` stage of the `Dockerfile`, which runs `go test -race`, and a
|
||||||
keys and values holding invalid UTF-8 are quoted
|
new final stage makes a plain `docker build` run both the `lint` and `test`
|
||||||
* 2026-08-07: added canonical `.golangci.yml` (v2 schema), pinned the
|
stages
|
||||||
`Dockerfile` lint stage to golangci-lint v2.12.2 (tag+digest), and
|
- 2026-10-06: the linter runs only in Docker: `script/lint` builds the `lint`
|
||||||
fixed all findings the v1→v2 jump surfaced without changing any
|
stage of the `Dockerfile`, every `docker build` in `script/` runs without the
|
||||||
exported signatures or behavior
|
build cache, and `script/bootstrap` no longer installs golangci-lint
|
||||||
- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints,
|
- 2026-10-06: every handler now returns a failed delivery from `Handle` instead
|
||||||
Makefile shims, README Entrypoints section
|
of discarding it: console and JSON return the stdout write error, the webhook
|
||||||
* 2026-02-08: fixed JSONHandler deadlock from recursive log.Println,
|
also fails on a non-2xx answer, and the multiplex delivers to every handler
|
||||||
with regression test; tagged 1.0.1
|
and returns their errors joined
|
||||||
* 2024-06-14: 1.0 prep: lint and fmt enforced in Docker build, call
|
- 2026-08-10: fixed every handler discarding slog attributes: console, JSON and
|
||||||
stack depth fix so log locations report correctly, example script,
|
webhook handlers now emit record attributes, accumulate WithAttrs without
|
||||||
removed non-building RELP code; tagged v1.0.0
|
mutating the receiver, and honour WithGroup; slog.Group values nest and
|
||||||
* 2024-05-22: module path moved to sneak.berlin/go/simplelog
|
LogValuer values are resolved; console keys and values holding invalid UTF-8
|
||||||
* 2024-05-14: initial library: slog-based console, JSON, webhook, and
|
are quoted
|
||||||
RELP handlers, MultiplexHandler, caller file/line info, UTC ISO
|
- 2026-08-07: added canonical `.golangci.yml` (v2 schema), pinned the
|
||||||
timestamps, level-colored output
|
`Dockerfile` lint stage to golangci-lint v2.12.2 (tag+digest), and fixed all
|
||||||
|
findings the v1→v2 jump surfaced without changing any exported signatures or
|
||||||
|
behavior
|
||||||
|
|
||||||
|
* 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, Makefile
|
||||||
|
shims, README Entrypoints section
|
||||||
|
|
||||||
|
- 2026-02-08: fixed JSONHandler deadlock from recursive log.Println, with
|
||||||
|
regression test; tagged 1.0.1
|
||||||
|
- 2024-06-14: 1.0 prep: lint and fmt enforced in Docker build, call stack depth
|
||||||
|
fix so log locations report correctly, example script, removed non-building
|
||||||
|
RELP code; tagged v1.0.0
|
||||||
|
- 2024-05-22: module path moved to sneak.berlin/go/simplelog
|
||||||
|
- 2024-05-14: initial library: slog-based console, JSON, webhook, and RELP
|
||||||
|
handlers, MultiplexHandler, caller file/line info, UTC ISO timestamps,
|
||||||
|
level-colored output
|
||||||
|
|
||||||
# Future Steps
|
# Future Steps
|
||||||
|
|
||||||
* Restructure README.md into the standard sections: Description,
|
- Delete the old plain TODO file once this TODO.md lands
|
||||||
Getting Started, Rationale, Design, TODO, License, Author
|
- Add .aider.\* to .gitignore and remove the stray aider artifacts from the
|
||||||
* Delete the old plain TODO file once this TODO.md lands
|
working tree
|
||||||
* Add .aider.* to .gitignore and remove the stray aider artifacts from
|
- Pick one tag scheme before the next release (v1.0.0 vs 1.0.1 are inconsistent)
|
||||||
the working tree
|
- Tag v1.0.2, with the leading v, once the attribute fix lands, so consuming
|
||||||
* Pick one tag scheme before the next release (v1.0.0 vs 1.0.1 are
|
repos can move off pseudo-version pins in one step
|
||||||
inconsistent)
|
- Fix RELP output to cache (from old TODO)
|
||||||
* Tag v1.0.2, with the leading v, once the attribute fix lands, so
|
- Re-add RELP delivery over TCP to remote rsyslog imrelp; removed 2024-06-14
|
||||||
consuming repos can move off pseudo-version pins in one step
|
because it did not build (README planned feature)
|
||||||
* Fix RELP output to cache (from old TODO)
|
- Add regex filtering for webhook logs (from old TODO)
|
||||||
* Re-add RELP delivery over TCP to remote rsyslog imrelp; removed
|
- Better console output format (from old TODO)
|
||||||
2024-06-14 because it did not build (README planned feature)
|
|
||||||
* Add regex filtering for webhook logs (from old TODO)
|
|
||||||
* Better console output format (from old TODO)
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -160,3 +161,103 @@ func TestWebhookHandlerReturnsErrorOnRedirect(t *testing.T) {
|
|||||||
t.Fatalf("Handle returned %v, want an error for the redirect", err)
|
t.Fatalf("Handle returned %v, want an error for the redirect", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A server that accepts the request and never answers must not hold up
|
||||||
|
// the log call: Handle gives up after webhookTimeout and says why.
|
||||||
|
func TestWebhookHandlerTimesOutOnServerThatNeverAnswers(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
testEnded := make(chan struct{})
|
||||||
|
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(
|
||||||
|
func(_ http.ResponseWriter, _ *http.Request) {
|
||||||
|
<-testEnded
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
// server.Close waits for running requests, so the server's handler
|
||||||
|
// is released first.
|
||||||
|
defer func() {
|
||||||
|
close(testEnded)
|
||||||
|
server.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
handler, err := NewWebhookHandler(server.URL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewWebhookHandler: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle runs in a goroutine so that a lost timeout fails the test
|
||||||
|
// instead of hanging the test run.
|
||||||
|
handleErr := make(chan error, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
handleErr <- handler.Handle(context.Background(), errorTestRecord())
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err = <-handleErr:
|
||||||
|
case <-time.After(webhookTimeout + time.Second):
|
||||||
|
t.Fatal("Handle did not return within webhookTimeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
var netErr net.Error
|
||||||
|
if !errors.As(err, &netErr) || !netErr.Timeout() {
|
||||||
|
t.Fatalf("Handle returned %v, want a timeout error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A server that sends a 2xx status and then never finishes the answer
|
||||||
|
// must not hold up the log call either: reading the answer counts toward
|
||||||
|
// webhookTimeout, and Handle returns the read's error.
|
||||||
|
func TestWebhookHandlerTimesOutOnServerThatStallsTheAnswer(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
testEnded := make(chan struct{})
|
||||||
|
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(
|
||||||
|
func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
|
// Flush sends the status now; the answer stays unfinished
|
||||||
|
// until the test ends.
|
||||||
|
err := http.NewResponseController(w).Flush()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("flush the status: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
<-testEnded
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
// server.Close waits for running requests, so the server's handler
|
||||||
|
// is released first.
|
||||||
|
defer func() {
|
||||||
|
close(testEnded)
|
||||||
|
server.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
handler, err := NewWebhookHandler(server.URL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewWebhookHandler: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle runs in a goroutine so that a lost timeout fails the test
|
||||||
|
// instead of hanging the test run.
|
||||||
|
handleErr := make(chan error, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
handleErr <- handler.Handle(context.Background(), errorTestRecord())
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err = <-handleErr:
|
||||||
|
case <-time.After(webhookTimeout + time.Second):
|
||||||
|
t.Fatal("Handle did not return within webhookTimeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
var netErr net.Error
|
||||||
|
if !errors.As(err, &netErr) || !netErr.Timeout() {
|
||||||
|
t.Fatalf("Handle returned %v, want a timeout error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"private": true,
|
||||||
|
"devDependencies": {
|
||||||
|
"prettier": "3.8.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
-1
@@ -2,11 +2,26 @@
|
|||||||
# script/bootstrap: install all dependencies needed to build and develop
|
# script/bootstrap: install all dependencies needed to build and develop
|
||||||
# this repo. Idempotent: every install is guarded by a check so already
|
# this repo. Idempotent: every install is guarded by a check so already
|
||||||
# installed tools are skipped. Base tooling comes from nix, apt, brew,
|
# installed tools are skipped. Base tooling comes from nix, apt, brew,
|
||||||
# or apk (detected in that order); assumes nothing is present.
|
# or apk (detected in that order); assumes nothing is present. Node is
|
||||||
|
# used directly if installed; otherwise it is installed at a pinned
|
||||||
|
# version via nvm (installing nvm itself first, from a hash-verified
|
||||||
|
# release archive, never curl | sh).
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
|
# Pinned versions, 2026-07-06
|
||||||
|
NODE_VERSION="22.17.0"
|
||||||
|
NVM_VERSION="0.40.3"
|
||||||
|
# sha256 of https://github.com/nvm-sh/nvm/archive/refs/tags/v0.40.3.tar.gz
|
||||||
|
NVM_SHA256="5f4d6aaa04a177dc93c985e31dbc411ab6b8c6e1e21d8015dbc1372625fcd1d0"
|
||||||
|
YARN_VERSION="1.22.22"
|
||||||
|
|
||||||
|
# goimports from golang.org/x/tools v0.30.0, 2025-02-10: the last release
|
||||||
|
# that Go 1.22, the Go of go.mod and the Dockerfile, can build.
|
||||||
|
GOIMPORTS_COMMIT="09747cdf594a7924dcecb506312be3bd6e437962"
|
||||||
|
GOIMPORTS_VERSION="v0.30.0"
|
||||||
|
|
||||||
PKGMGR=""
|
PKGMGR=""
|
||||||
SUDO=""
|
SUDO=""
|
||||||
|
|
||||||
@@ -47,6 +62,98 @@ missing() {
|
|||||||
! command -v "$1" >/dev/null 2>&1
|
! command -v "$1" >/dev/null 2>&1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Print the golang.org/x/tools version that the goimports on PATH was
|
||||||
|
# built from, or nothing. goimports has no --version flag; `go version -m`
|
||||||
|
# prints the module versions Go records in every binary it builds.
|
||||||
|
goimports_version() {
|
||||||
|
bin="$(command -v goimports)" || return 0
|
||||||
|
go version -m "$bin" 2>/dev/null |
|
||||||
|
awk '$1 == "mod" && $2 == "golang.org/x/tools" { print $3 }'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Install goimports at the pinned commit unless the one on PATH already
|
||||||
|
# reports the pinned version. go install writes to GOBIN, or to the bin
|
||||||
|
# directory of GOPATH when GOBIN is unset, which need not be on the
|
||||||
|
# caller's PATH; script/fmt puts that directory first on PATH the same
|
||||||
|
# way, so the check here sees the goimports that script/fmt runs.
|
||||||
|
ensure_goimports() {
|
||||||
|
gobin="$(go env GOBIN)"
|
||||||
|
PATH="${gobin:-$(go env GOPATH)/bin}:$PATH"
|
||||||
|
if [ "$(goimports_version)" != "$GOIMPORTS_VERSION" ]; then
|
||||||
|
go install "golang.org/x/tools/cmd/goimports@$GOIMPORTS_COMMIT"
|
||||||
|
hash -r
|
||||||
|
if [ "$(goimports_version)" != "$GOIMPORTS_VERSION" ]; then
|
||||||
|
echo "bootstrap: goimports on PATH is not $GOIMPORTS_VERSION" \
|
||||||
|
"after installing it: $(command -v goimports || echo none)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
echo "goimports $GOIMPORTS_VERSION at $(command -v goimports)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# verify_sha256 <file> <expected-hash>
|
||||||
|
verify_sha256() {
|
||||||
|
if command -v sha256sum >/dev/null 2>&1; then
|
||||||
|
actual="$(sha256sum "$1" | cut -d' ' -f1)"
|
||||||
|
else
|
||||||
|
actual="$(shasum -a 256 "$1" | cut -d' ' -f1)"
|
||||||
|
fi
|
||||||
|
if [ "$actual" != "$2" ]; then
|
||||||
|
echo "bootstrap: sha256 mismatch for $1" >&2
|
||||||
|
echo " expected: $2" >&2
|
||||||
|
echo " actual: $actual" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# nvm is a bash script; run a command in a bash with nvm loaded
|
||||||
|
nvm_sh() {
|
||||||
|
bash -c ". \"\$HOME/.nvm/nvm.sh\" && $*"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_nvm() {
|
||||||
|
[ -s "$HOME/.nvm/nvm.sh" ] && return 0
|
||||||
|
# nvm prerequisites; nvm itself requires bash
|
||||||
|
if missing bash; then pkg_install bash bash bash bash; fi
|
||||||
|
if missing curl; then pkg_install curl curl curl curl; fi
|
||||||
|
if missing git; then pkg_install git git git git; fi
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
curl -fsSL -o "$tmp/nvm.tar.gz" \
|
||||||
|
"https://github.com/nvm-sh/nvm/archive/refs/tags/v${NVM_VERSION}.tar.gz"
|
||||||
|
verify_sha256 "$tmp/nvm.tar.gz" "$NVM_SHA256"
|
||||||
|
mkdir -p "$HOME/.nvm"
|
||||||
|
tar -xzf "$tmp/nvm.tar.gz" -C "$HOME/.nvm" --strip-components=1
|
||||||
|
rm -rf "$tmp"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_node() {
|
||||||
|
if ! missing node; then return 0; fi
|
||||||
|
ensure_nvm
|
||||||
|
nvm_sh "nvm install $NODE_VERSION"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_yarn() {
|
||||||
|
if ! missing yarn; then return 0; fi
|
||||||
|
if ! missing corepack; then
|
||||||
|
corepack enable
|
||||||
|
corepack prepare "yarn@$YARN_VERSION" --activate
|
||||||
|
elif [ -s "$HOME/.nvm/nvm.sh" ]; then
|
||||||
|
nvm_sh "nvm use $NODE_VERSION >/dev/null && corepack enable && \
|
||||||
|
corepack prepare yarn@$YARN_VERSION --activate"
|
||||||
|
else
|
||||||
|
npm install -g "yarn@$YARN_VERSION"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
install_js_deps() {
|
||||||
|
if missing yarn && [ -s "$HOME/.nvm/nvm.sh" ]; then
|
||||||
|
nvm_sh "nvm use $NODE_VERSION >/dev/null && cd \"$ROOT\" && \
|
||||||
|
yarn install --frozen-lockfile"
|
||||||
|
else
|
||||||
|
yarn install --frozen-lockfile
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
|
|
||||||
@@ -55,9 +162,14 @@ main() {
|
|||||||
|
|
||||||
if missing go; then pkg_install go golang go go; fi
|
if missing go; then pkg_install go golang go go; fi
|
||||||
# golangci-lint is not installed: it runs only in docker (script/lint).
|
# golangci-lint is not installed: it runs only in docker (script/lint).
|
||||||
|
ensure_goimports
|
||||||
|
|
||||||
go mod download
|
go mod download
|
||||||
|
|
||||||
|
ensure_node
|
||||||
|
ensure_yarn
|
||||||
|
install_js_deps
|
||||||
|
|
||||||
echo "bootstrap complete"
|
echo "bootstrap complete"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -1,6 +1,8 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/check: run all checks (test, lint, fmt-check). Our own
|
# script/check: run all checks (test, lint, fmt-check). Our own
|
||||||
# extension to scripts-to-rule-them-all. Must not modify any files.
|
# extension to scripts-to-rule-them-all. test and lint are Docker
|
||||||
|
# phases; fmt-check is native, because a formatter writes the working
|
||||||
|
# tree. Must not modify any files.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
|||||||
+17
-4
@@ -1,7 +1,10 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/cibuild: run the CI build. The Dockerfile runs the format check,
|
# script/cibuild: run the CI build. It bootstraps first: a CI runner
|
||||||
# the linter and the tests, so a successful build means they all pass.
|
# checks out and runs this and nothing else, and script/fmt-check runs
|
||||||
# --no-cache because a cached check step is a check that did not run.
|
# the formatter on the host, which a pristine checkout cannot do.
|
||||||
|
# --no-cache for the same reason as script/docker: the gate phases the
|
||||||
|
# final stage depends on are RUN steps, and a cached one is a check that
|
||||||
|
# did not run.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
@@ -9,7 +12,17 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
|||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
docker build --no-cache -t "$("$SCRIPT_DIR/projectname")" .
|
"$SCRIPT_DIR/bootstrap"
|
||||||
|
"$SCRIPT_DIR/check"
|
||||||
|
# Own line: a failing command substitution inside an argument does
|
||||||
|
# not trip `set -e`, so the inline form degrades silently to an
|
||||||
|
# empty constant. The VERSION build argument takes precedence over
|
||||||
|
# the version a build stage derives from the .git in the context.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$("$SCRIPT_DIR/projectname")" .
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+2
-3
@@ -12,9 +12,8 @@ main() {
|
|||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
# Own line: a failing command substitution inside an argument does
|
# Own line: a failing command substitution inside an argument does
|
||||||
# not trip `set -e`, so the inline form degrades silently to an
|
# not trip `set -e`, so the inline form degrades silently to an
|
||||||
# empty constant. VERSION is computed here because .dockerignore
|
# empty constant. The VERSION build argument takes precedence over
|
||||||
# excludes .git, so `git describe` in a build stage yields an empty
|
# the version a build stage derives from the .git in the context.
|
||||||
# version without failing.
|
|
||||||
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
[ -n "$version" ] || version="unknown"
|
[ -n "$version" ] || version="unknown"
|
||||||
docker build --no-cache \
|
docker build --no-cache \
|
||||||
|
|||||||
+26
-1
@@ -1,12 +1,37 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/fmt: format all files (writes).
|
# script/fmt: format all files (writes): Go with the goimports that
|
||||||
|
# script/bootstrap installs, then Markdown with prettier. It puts Go's bin
|
||||||
|
# directory first on PATH, as script/bootstrap does, so it runs that
|
||||||
|
# goimports even when the directory is not on the caller's PATH.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
|
# Must match the pin in script/bootstrap.
|
||||||
|
NODE_VERSION="22.17.0"
|
||||||
|
|
||||||
|
# script/bootstrap installs node and yarn under nvm and leaves neither
|
||||||
|
# on the PATH of the shell that called it, so resolve the pinned
|
||||||
|
# toolchain here the way bootstrap's own install step does. nvm is a
|
||||||
|
# bash script, hence the subshell.
|
||||||
|
run_yarn() {
|
||||||
|
if command -v yarn >/dev/null 2>&1; then
|
||||||
|
exec yarn "$@"
|
||||||
|
fi
|
||||||
|
if [ ! -s "$HOME/.nvm/nvm.sh" ]; then
|
||||||
|
echo "fmt: no yarn; run script/bootstrap first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null &&
|
||||||
|
shift && exec yarn "$@"' bash "$NODE_VERSION" "$@"
|
||||||
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
|
gobin="$(go env GOBIN)"
|
||||||
|
PATH="${gobin:-$(go env GOPATH)/bin}:$PATH"
|
||||||
goimports -l -w .
|
goimports -l -w .
|
||||||
|
run_yarn run prettier --write '**/*.md' --tab-width 4 --prose-wrap always
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+22
-1
@@ -1,10 +1,30 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/fmt-check: check formatting (read-only). Fails and lists the
|
# script/fmt-check: check formatting (read-only). Fails and lists the
|
||||||
# offending files if gofmt would reformat anything.
|
# offending files if gofmt would reformat any Go file; otherwise fails if
|
||||||
|
# prettier would reformat any Markdown file.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
|
# Must match the pin in script/bootstrap.
|
||||||
|
NODE_VERSION="22.17.0"
|
||||||
|
|
||||||
|
# script/bootstrap installs node and yarn under nvm and leaves neither
|
||||||
|
# on the PATH of the shell that called it, so resolve the pinned
|
||||||
|
# toolchain here the way bootstrap's own install step does. nvm is a
|
||||||
|
# bash script, hence the subshell.
|
||||||
|
run_yarn() {
|
||||||
|
if command -v yarn >/dev/null 2>&1; then
|
||||||
|
exec yarn "$@"
|
||||||
|
fi
|
||||||
|
if [ ! -s "$HOME/.nvm/nvm.sh" ]; then
|
||||||
|
echo "fmt-check: no yarn; run script/bootstrap first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null &&
|
||||||
|
shift && exec yarn "$@"' bash "$NODE_VERSION" "$@"
|
||||||
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
unformatted="$(gofmt -l .)"
|
unformatted="$(gofmt -l .)"
|
||||||
@@ -13,6 +33,7 @@ main() {
|
|||||||
echo "$unformatted"
|
echo "$unformatted"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
run_yarn run prettier --check '**/*.md' --tab-width 4 --prose-wrap always
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+19
-1
@@ -6,15 +6,22 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// errWebhookStatus is returned when the webhook answers with a status
|
// errWebhookStatus is returned when the webhook answers with a status
|
||||||
// outside 2xx.
|
// outside 2xx.
|
||||||
var errWebhookStatus = errors.New("webhook did not accept the record")
|
var errWebhookStatus = errors.New("webhook did not accept the record")
|
||||||
|
|
||||||
|
// webhookTimeout bounds each webhook request, reading the answer
|
||||||
|
// included. Handle runs inside the log call, so a server that never
|
||||||
|
// answers would otherwise hold that call up for good.
|
||||||
|
const webhookTimeout = 5 * time.Second
|
||||||
|
|
||||||
// WebhookHandler POSTs each log record as JSON to a configured webhook
|
// WebhookHandler POSTs each log record as JSON to a configured webhook
|
||||||
// URL.
|
// URL.
|
||||||
type WebhookHandler struct {
|
type WebhookHandler struct {
|
||||||
@@ -34,6 +41,7 @@ func NewWebhookHandler(webhookURL string) (*WebhookHandler, error) {
|
|||||||
return &WebhookHandler{
|
return &WebhookHandler{
|
||||||
webhookURL: webhookURL,
|
webhookURL: webhookURL,
|
||||||
client: &http.Client{
|
client: &http.Client{
|
||||||
|
Timeout: webhookTimeout,
|
||||||
// Following a redirect can resend the request as a GET
|
// Following a redirect can resend the request as a GET
|
||||||
// without the record, so Handle gets the redirect answer
|
// without the record, so Handle gets the redirect answer
|
||||||
// itself and returns it as an error.
|
// itself and returns it as an error.
|
||||||
@@ -80,7 +88,8 @@ func (w *WebhookHandler) WithGroup(name string) slog.Handler {
|
|||||||
|
|
||||||
// Handle marshals the record, with its attributes, to one JSON object and
|
// Handle marshals the record, with its attributes, to one JSON object and
|
||||||
// POSTs it to the webhook URL. It returns an error when the request fails
|
// POSTs it to the webhook URL. It returns an error when the request fails
|
||||||
// or the server answers with a status outside 2xx.
|
// or runs past webhookTimeout, or when the server answers with a status
|
||||||
|
// outside 2xx.
|
||||||
func (w *WebhookHandler) Handle(ctx context.Context, record slog.Record) error {
|
func (w *WebhookHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||||
jsonData, err := json.Marshal(recordToMap(record, w.attrs))
|
jsonData, err := json.Marshal(recordToMap(record, w.attrs))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -106,6 +115,15 @@ func (w *WebhookHandler) Handle(ctx context.Context, record slog.Record) error {
|
|||||||
|
|
||||||
defer func() { _ = response.Body.Close() }()
|
defer func() { _ = response.Body.Close() }()
|
||||||
|
|
||||||
|
// The answer is read to the end so the client can reuse the
|
||||||
|
// connection for the next record. The read counts toward
|
||||||
|
// webhookTimeout, so a server that sends its status and then stalls
|
||||||
|
// fails here.
|
||||||
|
_, err = io.Copy(io.Discard, response.Body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error reading webhook answer: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
if response.StatusCode < http.StatusOK ||
|
if response.StatusCode < http.StatusOK ||
|
||||||
response.StatusCode >= http.StatusMultipleChoices {
|
response.StatusCode >= http.StatusMultipleChoices {
|
||||||
return fmt.Errorf("%w: %s", errWebhookStatus, response.Status)
|
return fmt.Errorf("%w: %s", errWebhookStatus, response.Status)
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||||
|
# yarn lockfile v1
|
||||||
|
|
||||||
|
|
||||||
|
prettier@3.8.1:
|
||||||
|
version "3.8.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.1.tgz#edf48977cf991558f4fcbd8a3ba6015ba2a3a173"
|
||||||
|
integrity sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==
|
||||||
Reference in New Issue
Block a user