onwrite

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2026 License: MIT

README

onwrite

Format-on-save, for everything that isn't an editor.

onwrite applies your project's own formatters and lint fixers to source files the moment something writes them — a shell heredoc, sed -i, a generator script, or an AI coding agent's file tool.

ci license


The problem

Editors have had format-on-save for twenty years. Press save, prettier runs, the file is correct before you have looked away.

Everything else has nothing.

When an agent writes a file with cat > src/config.ts <<EOF, or a script rewrites something with sed -i, the result lands on disk exactly as typed: unformatted, unlinted, and wrong in a way that will be discovered later. Later is the expensive part. The pre-commit hook rejects the commit. CI goes red. Or the agent notices three steps on, and spends turns doing this:

$ npx prettier --write src/config.ts src/server.ts
$ npx eslint --fix src/
$ gofmt -w ./internal/...
$ ruff check --fix .
$ npx prettier --write src/config.ts     # again, eslint moved things

Every one of those turns is waste. The tooling to prevent it already exists in the repository. It just never runs at the moment of the write.

Pre-commit hooks (husky, lint-staged) are too late — the turns are already spent. Editor plugins do not apply; there is no editor. And the generic watchers (watchexec, entr, onchange, chokidar-cli) can be composed into something that half works, which is why everybody hand-rolls it and everybody gets the same three edge cases wrong.

Before
$ cat > src/config.ts <<'EOF'
var  port=3000
export function  start( ){console.log("listening on",port)}
EOF

$ cat src/config.ts
var  port=3000
export function  start( ){console.log("listening on",port)}
After
$ onwrite run -- bash -c 'cat > src/config.ts <<EOF
var  port=3000
export function  start( ){console.log("listening on",port)}
EOF'
onwrite: formatted src/config.ts (eslint, prettier)
onwrite: 1 file(s) formatted in 210ms

$ cat src/config.ts
const port = 3000;
export function start() {
  console.log('listening on', port);
}

No configuration was involved. onwrite found the repository's own .prettierrc and eslint.config.mjs, used the prettier and eslint pinned in node_modules, ran the fixer before the formatter, and wrote the file once. The single quotes come from that project's prettier config, not from onwrite.


Install

# macOS and Linux
curl -fsSL https://raw.githubusercontent.com/amartya-dev/onwrite/main/scripts/install.sh | sh

# or with Go
go install github.com/amartya-dev/onwrite/cmd/onwrite@latest

Or download a binary from the releases page. It is a single static binary with no runtime and no dependencies.


Use

onwrite run -- <command> — the one to reach for

Runs a command, notices which files changed while it ran, and formats those.

$ onwrite run -- ./scripts/codegen.sh
$ onwrite run -- python manage.py makemigrations
$ onwrite run -- claude -p "add a health check endpoint"

This is the most reliable mode and the best default for agents. There is no watcher, no debounce to tune, and no partial-write race to lose: by the time onwrite looks, the command has exited and every file it wrote is complete. Nothing is left running afterwards.

stdin, stdout, stderr and the exit code all pass straight through, so it can be dropped in front of anything without changing its behaviour.

onwrite watch — a daemon
$ onwrite watch
onwrite: watching /home/me/api (37 directories, 4 tool(s): ruff-check, eslint, ruff-format, prettier)
onwrite: formatted src/routes.ts (eslint, prettier)
onwrite: formatted api/models.py (ruff-check, ruff-format)

Use this when the writes come from somewhere you cannot wrap: several terminals, a long-lived agent session, a tool you do not control.

onwrite fix — one shot
$ onwrite fix src/server.ts
$ onwrite fix src/ internal/
$ onwrite fix --all --dry-run
onwrite doctor — why isn't it doing anything?
$ onwrite doctor
root      /home/me/api
config    none (zero-config)

Will run 5 tool(s), in this order:

  ID           LANG    KIND       FOUND VIA                   EXTENSIONS
  ruff-check   python  fixer      .venv/bin/ruff              .py .pyi
  eslint       js      fixer      node_modules/.bin/eslint    .js .jsx .ts .tsx ...
  ruff-format  python  formatter  .venv/bin/ruff              .py .pyi
  prettier     js      formatter  node_modules/.bin/prettier  .js .jsx .ts .tsx ...
  gofmt        go      formatter  PATH                        .go

onwrite doctor --all lists every tool onwrite knows and says why each one was or was not selected.


Claude Code

onwrite hook --install     # writes .claude/settings.json
onwrite hook --print       # show the JSON without writing it

The adapter is a thin translation layer; the core is agent-agnostic and works for anyone driving a shell. But it does one thing a plain external formatter cannot, and it matters more than it sounds.

It tells the agent what it changed. A formatter that rewrites files behind an agent's back leaves the model holding a stale copy of a file it just wrote. That desync is a real, filed problem in other harnesses — it is why people disable format-on-save when working with agents (zed#55295, cline#5165). Because a PostToolUse hook may return additionalContext, onwrite can say so out loud:

onwrite reformatted these files after your edit. Their contents on disk now
differ from what you wrote, so re-read them before editing again:
  - src/config.ts (eslint, prettier)

And when a formatter refuses a file, that is the fastest possible signal that the file does not parse, so the agent hears about that too:

onwrite could not format these files, and left them unchanged. A formatter
failing this way almost always means the file does not parse:
  - src/server.ts (prettier: SyntaxError: Unexpected token (12:3))

The installed hook matches both file-writing tools and Bash. For Write and Edit the file is named in the event, so exactly that file is formatted. For Bash — heredocs, sed -i, python one-liners, the cases this project exists for — onwrite formats everything that changed since the hook last ran. If a bash step changed more than --max-sweep files (200 by default) it does nothing, on the grounds that a branch checkout or a build is not an edit.

When onwrite has nothing to say, it says nothing. The hook is silent on the overwhelming majority of tool calls.


What it runs

Nothing of its own. onwrite has no formatting opinions and ships no config. It detects what your project already uses and delegates.

Language Tools Detected from
JS / TS / JSON / CSS / Markdown / YAML biome, dprint, prettier, eslint --fix biome.json, dprint.json, .prettierrc*, eslint.config.*, .eslintrc*, or the dependency in package.json
Python ruff format, ruff check --fix, black, isort ruff.toml, [tool.ruff], [tool.black], [tool.isort]
Go gofmt, goimports, golangci-lint fmt the toolchain; .golangci.yml for the last
Rust rustfmt Cargo.toml, rustfmt.toml
Shell shfmt .editorconfig, or the binary
C / C++ / Obj-C clang-format .clang-format
Terraform terraform fmt any *.tf
TOML taplo .taplo.toml
Lua stylua stylua.toml
Zig zig fmt build.zig

Three rules govern all of it:

A binary on PATH is not permission to use it. If a project has no prettier config and no prettier dependency, onwrite will not run prettier on it, even if prettier is installed. Reformatting somebody's repository to a standard they never chose is a worse outcome than doing nothing.

Your pinned version wins. Binaries are resolved from node_modules/.bin, .venv/bin and friends before PATH, so a repo gets the version it pinned.

Competing formatters never both run. biome, dprint and prettier share one mutual-exclusion group; a project configured for biome gets biome and prettier is not invoked. Fixers run before formatters so the formatter has the last word on layout.

Adding a language is a config entry, not a fork — see Configuration.


How it avoids destroying your files

This program writes to source files, so the interesting engineering is all in what it refuses to do. The design turns on one decision:

A formatter is never given your file. Content goes in on stdin, comes back on stdout, and onwrite performs a single atomic write at the end — only if every formatter in the chain succeeded.

Nearly every formatter supports this (prettier --stdin-filepath, gofmt, ruff format --stdin-filename, biome --stdin-file-path, and ESLint via --fix-dry-run --format json). Treating the chain as a pure function, rather than as a sequence of tools each rewriting the file in place, removes most of the ways this can go wrong:

Partial writes. A large heredoc is not atomic. Fire mid-write and a naive formatter reads a truncated file, "formats" it, and writes the mangled result back — destroying work. onwrite gets this right three times over: the debounce timer resets on every event; after it fires, the file is read twice a settle apart and must agree; and if both of those were somehow defeated, a truncated file does not parse, so the formatter exits non-zero and nothing is written at all. A file that cannot be formatted is left exactly as its author left it.

Write loops. The formatter writes the file, the watcher fires, the formatter runs again. onwrite remembers the exact bytes it wrote and drops any event whose content matches. This is identity, not a timing window — which matters, because the usual fix ("ignore events for 500ms after running") also swallows genuine edits that land during the window. A real edit arriving one microsecond after onwrite's own write is still formatted.

Atomic writes. Every write is to a temporary file in the same directory, fsynced, then renamed over the target. A reader at any instant sees the complete old contents or the complete new contents — never a mixture, never an empty file. Permission bits are carried over, so formatting an executable script does not silently make it unexecutable.

Bailing out rather than guessing. Symlinks are skipped, because rewriting through one would replace the link with a regular file. Binary files, empty files and files over 4 MB are skipped. A tool that exits 0 but prints nothing is treated as a failure, because trusting it would empty your file. A tool that hangs is killed — along with its whole process group, since node_modules/.bin entries and pyenv shims are wrappers whose grandchildren would otherwise hold the pipe open forever.

Never touching what it shouldn't. .gitignore is honoured, including nested ignore files, negations and .git/info/exclude. On top of that sits a deny-list — .git, node_modules, vendor, dist, target, __pycache__, .venv and the rest — that applies even when a repository has committed them.

All of this is tested, not asserted. See internal/engine/engine_test.go and internal/watch/watch_test.go: the write-loop test asserts the formatter is spawned exactly once, and the partial-write tests write a file in timed chunks and check it is never damaged.


Prior art, honestly

This was researched before it was written, because "use X" would have been a better answer than another tool. Here is what exists.

Nothing standalone does this. The polyglot formatters and the file watchers are two halves that have never been joined in a distributable binary.

  • treefmt dispatches formatters by file type but has no watch mode. The request (#509) has been open since January 2025 and both implementation attempts were abandoned.

  • dprint, topiary: polyglot, no watch mode.

  • watchexec, entr, onchange, chokidar-cli, watchman: excellent watchers with no formatter knowledge. None can distinguish the formatter's own write from a real one — the closest is watchexec's --on-busy-update=do-nothing, which is a time window and drops real edits that arrive during it. cargo-watch, the folk idiom for this, was archived in January 2025.

  • Biome is the closest single tool, and worth checking before you install anything else — it has a daemon, an LSP and a --watch flag. But watch mode is deliberately read-only. Verified directly:

    $ biome format --write --watch .
    × Incompatible arguments --watch and --write.
      Applying code fixes is not available in watch mode.
    

    Biome has the watcher, the formatter and the daemon, and a considered policy against combining them. It is also JS/TS/JSON/CSS-only.

  • Prettier has no watch mode (#575, open since 2017); its docs point you at onchange.

  • ruff check --watch --fix genuinely applies lint fixes on change, but there is no ruff format --watch, it re-checks the whole project on every event, and it has no self-write suppression.

In the agent space, the good implementations are welded inside one agent. opencode has an excellent built-in formatter that re-reads the file and returns it to the model — genuinely the best solution to this problem, if you use opencode, and it is off by default. @gotgenes/pi-autoformat solves the same product problem for Pi, and argues in its README that zero-config defaults are the wrong call. Claude Code, Cursor, Goose and Codex all ship the event and tell you to write the formatter yourself; Anthropic's own docs use jq | xargs prettier --write as the worked example, which is precisely the naive version that eats truncated files.

The standalone Claude Code format hooks that do exist (ryanlewis/claude-format-hook and a dozen cookbook repos) are all under ten stars and unmaintained. fast-format-x shares the positioning but is a git-diff-scoped batch command requiring a YAML config, with no watch and no command wrapping.

Wrap-a-command had no prior art at all. Every "changed files" tool is git-scoped — staged, dirty, diff against a base. Scoping to what this process just wrote appears to be new, and it is the part of onwrite that most deserves to exist.

If your project is JS-only and already on Biome, or you are on opencode, you may not need this. Say so and use those instead.


Configuration

There isn't any, for the common case. onwrite doctor will tell you what it found.

For the cases zero-config cannot reach, drop a .onwrite.json at the project root:

{
  // gitignore syntax, on top of .gitignore
  "exclude": ["src/generated/**"],

  // turn off a builtin tool
  "disable": ["eslint"],

  "maxFileSize": "4MB",
  "timeout": "15s",
  "debounce": "120ms",

  // teach onwrite a formatter it has never heard of
  "tools": [
    {
      "id": "swiftformat",
      "lang": "swift",
      "extensions": [".swift"],
      "kind": "formatter",
      "mode": "stdio",
      "bin": "swiftformat",
      "args": ["--quiet", "stdin", "--stdinpath", "{file}"],
      "markers": [".swiftformat", "Package.swift"],
      "group": "swift-format",
      "priority": 10
    }
  ]
}

The builtin table uses this exact shape — see internal/registry/registry.go. Reusing a builtin id overrides how that tool is invoked.

  • kind — formatter (a failure abandons the file) or fixer (best effort, cannot abort the chain).
  • mode — stdio, stdio-json (ESLint-style reports), or tempfile for tools with no stdin support. tempfile still never hands the tool your real file; it gets a copy beside it, so its config discovery still works.
  • markers — the evidence that this project uses the tool. "biome.json" is a file or glob, "package.json#devDependencies.x" a JSON key path, "pyproject.toml#tool.x" a TOML table, "$binary" means "whenever the binary exists".
  • group — tools sharing a group are mutually exclusive; lowest priority wins.

Flags cover the rest: --only, --skip, --exclude, --timeout, --max-size, --dry-run, --verbose. Run onwrite --help.


Why Go

Start-up time is the whole argument. In hook mode this binary runs on every single tool call an agent makes — thousands of times a session — and it has to be invisible. A Go binary starts in single-digit milliseconds and the only dependencies are fsnotify and cobra.

Node would have given npx reach at the cost of a Node start-up per invocation, which is the thing being optimised away. Rust would have been an equally good answer; Go won on the standard library's os/exec, process-group handling and concurrency being exactly what this program is made of.

The result is one static binary, no runtime, no install step for the user's project, and nothing added to their dependency tree.


What it deliberately does not do

  • It does not install formatters. If prettier is not there, prettier does not run. Downloading a toolchain behind your back is not a service.
  • It does not follow symlinks. Skipped, not resolved.
  • It does not format your whole repository unless you ask with fix --all. Neither run nor the hook will ever mass-rewrite a repo.
  • It does not run type checkers or test suites. Formatters and safe autofixers only.
  • It does not lint. It applies fixes that tools can apply automatically, and stays quiet about findings it cannot fix — those belong in CI.
  • watch on very large trees costs one file descriptor per watched directory on macOS and the BSDs. onwrite raises the soft limit to the hard limit at start-up, but run mode is the better answer for a monorepo.

Development

go test ./internal/...          # unit tests, fake formatters, fast
go test -race ./internal/...    # the concurrency ones matter here
go test .                       # integration, against the real formatters

The integration suite skips any language whose toolchain is absent, so it is useful with only some of them installed, and complete in CI, which installs prettier, eslint, biome, ruff, black, goimports and gofmt and runs the whole thing on Linux and macOS.

Licence

MIT — see LICENSE.

Directories

Path Synopsis
cmd
onwrite command
Command onwrite applies a project's own formatters to files as they are written, from the command line or from a coding agent.
Command onwrite applies a project's own formatters to files as they are written, from the command line or from a coding agent.
internal
cli
Package cli wires the pieces together into the onwrite command.
Package cli wires the pieces together into the onwrite command.
config
Package config reads the optional .onwrite.json file.
Package config reads the optional .onwrite.json file.
detect
Package detect works out which of the tools in the registry a given project actually uses, and where their binaries live.
Package detect works out which of the tools in the registry a given project actually uses, and where their binaries live.
engine
Package engine applies a project's own formatters to a single file, safely.
Package engine applies a project's own formatters to a single file, safely.
hook
Package hook adapts onwrite to Claude Code's PostToolUse hook.
Package hook adapts onwrite to Claude Code's PostToolUse hook.
registry
Package registry holds the declarative table of formatters and fixers that onwrite knows how to drive.
Package registry holds the declarative table of formatters and fixers that onwrite knows how to drive.
runner
Package runner implements `onwrite run -- <command>`: run something, then format whatever it wrote.
Package runner implements `onwrite run -- <command>`: run something, then format whatever it wrote.
scan
Package scan decides which files onwrite is allowed to look at.
Package scan decides which files onwrite is allowed to look at.
testutil
Package testutil builds throwaway projects and fake formatters for tests.
Package testutil builds throwaway projects and fake formatters for tests.
watch
Package watch implements the daemon mode: format every source file as soon as anything finishes writing it.
Package watch implements the daemon mode: format every source file as soon as anything finishes writing it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL