Skip to content

dockerfmt v1.0.0 - #84

Merged
reteps merged 42 commits into
mainfrom
chore/cleanup-and-lint
Nov 14, 2026
Merged

reteps merged 42 commits into
mainfrom
chore/cleanup-and-lint

Conversation

@reteps

@reteps reteps commented Nov 13, 2026

Copy link
Copy Markdown
Owner

Prepares the v1.0.0 release. Changelog:

dockerfmt 1.0 makes formatting safe by construction and fixes a long list of
bugs found by fuzzing and review. Some defaults changed; see below.

Breaking changes

  • The trailing newline is kept as it is. Without --newline or an
    EditorConfig insert_final_newline, the output now ends with a newline if
    the input does. Before, it never did unless --newline was given.
    --newline=false removes it. The JS trailingNewline option defaults the
    same way.
  • The npm package requires Node.js 20 or later.
  • The Go lib package exposes only Format, Config and the indent size
    constants.
    FormatFileLines, ExtendedNode, ParseState, FormatNode,
    FormatOnBuild, BuildExtendedNode, GetHeredoc, GetFileLines,
    StripWhitespace, FormatComments and IndentFollowingLines were removed.
    Format returns an error instead of exiting the process.
  • The default Docker image is based on distroless and has no shell. Use
    ghcr.io/reteps/dockerfmt:alpine where a shell is needed, such as GitLab CI.
  • Redirects get a space by default (> file), in the CLI and the JS
    API; --space-redirects=false (spaceRedirects: false) turns it off. The
    pre-commit hook no longer needs to pass it.
  • --indent must be from 1 to 16, and --write can't be combined with
    --check or --diff.
  • Help is shown only when no files are given and stdin is a terminal; empty
    piped input is an error.

Safety

  • Each formatted instruction is checked with BuildKit's parser to mean the
    same as the original, and to stay the same when formatted again. The whole
    file is then checked as written. Anything that fails is left unchanged, with
    a warning.
  • FuzzFormat checks these properties on random inputs; CI runs it on every
    change.
  • --write rewrites files in place: permissions, owner, hard links and
    symbolic links are kept, it works in read-only directories, and a failed
    write restores the original contents.

Build checks

Formatting now fixes these BuildKit build-check warnings:

  • FromAsCasing: from a as b becomes FROM a AS b.
  • StageNameCasing: stage names are written in lower case, and so are the
    references to them in COPY --from, RUN --mount=...,from= and FROM.
    BuildKit finds a stage ignoring case everywhere except FROM, so
    FROM Builder now builds on the stage builder as intended.
  • ExposeProtoCasing: EXPOSE 80/TCP becomes EXPOSE 80/tcp.
  • LegacyKeyValueFormat: LABEL key value is rewritten as LABEL key=value,
    as ENV already was, and so are values with quotes or escapes, whose
    whitespace is escaped. A value written across several lines keeps its line
    breaks inside quotes.
  • NoEmptyContinuation: blank lines inside ENV, LABEL and other
    continued instructions are removed (BuildKit ignores them, and will reject
    them in a future release). Lines holding only \ are kept.

Formatting

  • Arguments written one per line stay one per line: COPY and ADD sources,
    and the elements of JSON arrays. The continued arguments of the first
    command in a && chain are indented like those of the commands after it.
    A heredoc stays on the line of a single --mount flag.

  • Shell bodies with several statements, such as the set -eux; \ style of
    the official images, and if, for, case and { } blocks, are
    formatted, with each statement on its own continued line ending in ; \.
    Statements written on one line stay on one line.

  • Comments get a space after the #: #comment becomes # comment.
    Parser directives, # check= lines, shebangs and banners such as
    ##### are left alone. #dockerfmt-ignore works too.

  • Indentation with tabs: --use-tabs, indent_style = tab in EditorConfig,
    or useTabs (or indent: 0, as prettier-plugin-sh passes) in JS.

  • HEALTHCHECK is formatted: flags and CMD/NONE are normalized, the
    command is formatted like CMD's, and CMD stays on its own line when
    written that way.

  • Words in ENV, LABEL, ARG, VOLUME, USER and STOPSIGNAL are
    separated by single spaces, trailing whitespace is removed, and a space goes
    before a line continuation that ends a word. VOLUME's JSON form is
    normalized.

Fixes

  • Quoted flag values (--chown="my user") kept their quotes; -- ending the
    flags is kept.
  • Backquoted command substitutions are no longer rewritten as $(...), which
    could change what they run.
  • Stages built on a PowerShell stage or a Windows image are not formatted as
    POSIX shell.
  • Blank lines after a comment are collapsed to one instead of deleted.
  • # dockerfmt-ignore applies only as the last comment before an
    instruction.
  • Indented comments that would become # syntax= or # check= directives
    keep their indentation.
  • Flags and continuations use the file's escape character with # escape=.
  • <<- heredoc scripts are indented with tabs.
  • Many edge cases with comments, separators, stray carriage returns and
    continuations at the end of the file.

Other changes

  • - reads stdin; version reports the module version for go install
    builds.
  • EditorConfig property names are case-insensitive, indent_size = tab uses
    tab_width, and invalid settings are reported once as warnings.
  • The JS API validates its options, reuses one WASM instance, and has an
    onFallback option.
  • The npm launcher passes signals through and explains launch failures.
  • Release binaries include darwin/amd64; prereleases aren't tagged latest.

🤖 Generated with Claude Code

reteps and others added 30 commits November 6, 2026 19:43
…c API

lib/format.go mixed the public API, the file walk, flag layout, every
directive formatter and assorted helpers. It is now:

  format.go      Config, Format, FormatFileLines and the file walk
  node.go        the instruction node and its source-text accessors
  directives.go  per-directive formatters and their registry
  flags.go       flag layout, including comments among flags
  context.go     SHELL/escape state and heredoc classification
  semantic.go    the equivalence guard
  doc.go         package overview

The exported API is now Config, Format and FormatFileLines (the only
names used outside this repo); ExtendedNode, ParseState, FormatNode,
FormatOnBuild, GetHeredoc, BuildExtendedNode, StripWhitespace,
FormatComments, IndentFollowingLines and GetFileLines are unexported or
removed. FormatFileLines is marked deprecated in favour of Format.

Also: build the output with a strings.Builder instead of repeated string
concatenation (quadratic in the number of instructions), drop the unused
formatBash, and make the fixture test check idempotency as well.

Output is byte-identical to before over BuildKit's parser test files,
BuildKit's own Dockerfiles and all fixtures, with four flag
combinations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The CLI kept its flags in package globals that run() mutated (--diff set
checkFlag) and that tests had to save and restore. Flags now live in an
options struct owned by a command built per invocation, and
execute(args, stdin, stdout, stderr) is the single entry point used by
main and the tests. The version subcommand moves into root.go.

Flag errors are reported once, on stderr, with a pointer to --help;
before, cobra printed the error to stdout and stderr plus the full usage.

Add .golangci.yml (standard linters plus errorlint, gocritic, misspell,
nolintlint, revive, unconvert, unparam, usestdlibvars; gofmt and
goimports) and fix what it reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
formatDockerfileContents passed options straight to Go, where a missing
or mistyped option (say indent: "2") panicked inside the js.FuncOf
callback. That exits the Go program, so the wasm instance was dead for
every later call. Now:

- Options are optional and default to the CLI's (indent 4, no trailing
  newline, no space after redirects). A wrong type rejects with a
  TypeError, and an indent outside 1..16 with a RangeError.
- formatBytes takes (contents, options), recovers from any panic and
  returns {output} or {error}, so a failure is a rejected promise and the
  runtime keeps working. An exception thrown by a JS callback is passed
  through as is.
- The wasm module is instantiated and the Go runtime started once, on
  first use, instead of on every call. Concurrent first calls share the
  same start-up; if it fails, or Go's main() ever exits, the next call
  starts afresh. The registered global is removed once captured.
- New onFallback option, mapped to lib.Config.OnFallback, is called with
  (line, reason) for each instruction left as written.
- getWasm returns a BufferSource rather than Node's Buffer, which the
  browser entry point has no business naming.

Add an npm test script and use it in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Go's wasm_exec.js throws at import time unless
globalThis.crypto.getRandomValues exists, which Node only provides
without a flag from 19 on. The Node entry point now installs
node:crypto's webcrypto first when it is missing.

Node 16 is the real minimum: before it there is no global performance,
which wasm_exec.js also requires, and Node 14 has no webcrypto. Set
engines to >=16 instead of claiming 12 and 14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cher

When the binary was killed by a signal, the launcher exited 1, hiding
Ctrl-C and SIGTERM from the caller. It now re-raises the signal, and
exits 128+n if it survives that (Node ignores SIGPIPE).

A failure to spawn the binary (EACCES, ENOENT) was also reported as exit
status 1 with no message, and a missing platform package threw with a
stack trace. Both now print one line on stderr: the spawn error code, or
the package to install, distinguishing an unsupported platform from an
install that omitted optional dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
npm only picks up a LICENSE at the package root, and none of the
packages under js/ had one. Each package's prepack script now copies the
repository's LICENSE in (npm publish and npm pack run it), and the
copies are git-ignored.

The main package also published dist/format.test.js and its .d.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pin the default image's base to gcr.io/distroless/static-debian12
rather than relying on ko's default, which has changed before. The
:alpine variant keeps overriding it with KO_DEFAULTBASEIMAGE.

Document running the image with -u "$(id -u):$(id -g)" so that, with
--write, dockerfmt runs as the invoking user rather than root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Trigger on release "published" instead of "created": a draft release
  fires "created" too, and then shipped binaries, images and npm
  packages before the release was public.
- Prereleases no longer move the Docker latest and alpine tags, and go
  to the npm "next" dist-tag instead of "latest".
- Drop workflow_dispatch from release.yaml. Run by hand it built from
  any branch and pushed an image tagged with the branch name.
- Build every release binary with CGO_ENABLED=0, so all of them are
  static, not only the musl-labeled ones.
- Publish a darwin/amd64 binary; the npm package already had one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FuzzFormat checks that formatting is idempotent and that BuildKit reads the
output as the same instructions as the input. What it found:

- BuildKit's parsed flags have their quotes removed, so --chown="my user"
  was re-emitted unquoted. Flags are now read from the source.
- "--" ends the flags even when there are none (COPY -- foo /tmp/).
- An empty RUN body was emitted without a newline, merging it with the
  next instruction.
- Trailing comments of a continued RUN were indented on the second pass.
- A comment in the middle of a line was given a guessed indentation; the
  line is now broken and printed again so mvdan/sh indents it.
- A "\" separator line right after the directive line, shell comments
  that BuildKit runs on into the next line, a dangling escape at the end of
  the body, and \v, \f or stray \r in shell code.
- IndentSize 0 made mvdan/sh indent with tabs; it now means 4.
- Keys of RUN flags and invalid instructions weren't deterministic.

Each instruction's output must now also format to itself, and the whole
file is checked as written, which catches a heredoc whose line endings
would change in a file that mixes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- --write rewrites the file in place, keeping its mode, owner and hard
  links, with a backup that is restored if the write fails.
- The output ends with a newline if the input does, unless --newline
  (or --newline=false) or .editorconfig says otherwise.
- "-" reads stdin; help is shown only when stdin is a terminal, so empty
  piped input is an error rather than a help screen.
- -w can't be combined with -c/-d, and --indent must be 1 to 16.
- .editorconfig keys are case-insensitive, indent_size = tab uses
  tab_width, and invalid settings are warned about once.
- "version" reports the module version for go install builds and
  doesn't complete file names; diff headers use relative paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
types_or: [dockerfile] made pre-commit skip files its own detection
doesn't identify, such as prod.dockerfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The JS onFallback tests used that crash as their fallback; they now use a
file whose mixed line endings would change a heredoc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Node 18 is end of life, and CI tests 20, 22 and 24. From Node 19 on,
globalThis.crypto is available without a polyfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nding

A RUN whose last line ends in "\" was read as a dangling escape at the
end of the file but as a continuation before a blank line, so formatting
it twice could give different results. Trailing blank lines inside the
continuation are dropped, as BuildKit does, and the last line always gets
a line ending.

Also set the npm author email to peter@stenger.io.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… too

The JS trailingNewline option now defaults to what the input does, as
the CLI does. Files whose formatted output would end a line with a stray
carriage return are left as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Meaning changes the guard missed:
- Backquoted command substitutions were printed as $(...), which keeps
  escapes the backquotes would have removed. Bodies with backquotes are
  left as written, and the guard no longer treats the two as equal.
- A stage built on a PowerShell stage, or on a Windows image, was
  formatted as POSIX shell.
- Expansion is compared with every variable set and with every variable
  unset, so ${A:-x} and ${A:+x} no longer compare equal to their result.
- Reordered RUN flags no longer compare equal.

Comments and blank lines:
- Two or more blank lines after a comment were deleted, while two after
  an instruction were kept; any run of blank lines now becomes one.
- "# dockerfmt-ignore" applies only as the last comment before the
  instruction, as documented.
- An indented comment before the first instruction that would become a
  parser directive, such as "# syntax=", keeps its indentation.
- A comment on the directive line ("RUN # c \") is shell code, not a
  dropped comment line.

Also: flags and EXPOSE ports are laid out with the file's escape
character; "<<-" heredoc scripts are indented with tabs; Format rejects an
IndentSize above MaxIndentSize; trimming no longer turns a line into a
continuation. Removed the deprecated FormatFileLines, dead heredoc code
in formatWords, and the guess at the escape character.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A failed --write renamed the backup over the file even when nothing had
  been written, replacing it (breaking hard links, and symlinks with it).
  The file is now truncated and rewritten in place; the original is kept
  in memory and written back if the write fails, and saved to a temporary
  file only if that fails too. --write works in read-only directories
  again.
- Help is shown only when stdin is a terminal: /dev/null is a character
  device too, so `dockerfmt -c </dev/null` passed silently.
- Every invalid .editorconfig setting is reported, once however many
  files share it, in one style; errors name the path once.
- The indent limit and default come from lib.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Also deduplicate the shell operator list, and keep the pre-commit hook off
files such as Dockerfile.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Such output would run on into the next line of the file, which checking
the instruction on its own can't show. Found by fuzzing: a legacy ENV
whose value is a backslash followed by a stray carriage return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… build checks

- FROM ... AS takes the case of FROM, which is upper case.
- EXPOSE protocols are written in lower case, as BuildKit reads them; one
  given by a variable is left alone.
- Blank lines inside continued ENV, LABEL, ARG and similar instructions
  are removed; BuildKit drops them and warns that they will become errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the formatter moves a trailing comment out of a continuation, the
comment follows the instruction in its output; formatted again, it is a
line between instructions. The stability check compared the two and left
such instructions unformatted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tests/in and tests/out, and the table tests that formatted whole files,
are now txtar archives in tests/golden, one per area, with each input next
to what it formats to. Every case now gets the same checks: idempotency,
CRLF, no final newline, and no instruction left unformatted. Inline tests
remain for internal functions and byte-level edge cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BuildKit merges such a comment into the linter's configuration while
parsing the instruction, and ParseInstruction has no linter, so the
semantic check panicked and the whole file was left unformatted. The
whole-file fallback now reports its actual reason instead of always
suggesting mixed line endings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HEALTHCHECK gets its own formatter: flags and CMD/NONE are normalized, the
command is formatted as CMD's is, and CMD stays on its own line when it was.
ENV, LABEL, ARG, VOLUME, USER and STOPSIGNAL separate words by single
spaces, drop trailing whitespace, and get a space before a continuation
that ends a word. VOLUME's JSON form is normalized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lib.Config.UseTabs indents continuation lines with tabs and has the shell
printer do the same. The CLI takes --use-tabs and EditorConfig's
indent_style; the JS API takes useTabs, and indent: 0, which is what
prettier-plugin-sh passes for tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ENV and LABEL share the conversion of the legacy "key value" form. A
value with unquoted whitespace is quoted if it has no quotes or escapes,
and otherwise has the whitespace escaped; a value written across several
lines is quoted with its line breaks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
reteps and others added 12 commits November 12, 2026 20:52
The printer puts statements, and the parts of if, for, case and { }
blocks, on separate lines; those line breaks now become continuations,
after a ";" where the shell needs a separator. Statements the source has
on one line are joined back. Bodies in the official images' set -eux style
were left as written; they are now formatted, with a statement ended on
its own line ("; \\") lined up with the statement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…alues with comments

- FROM's image is expanded with the defaults of the global ARGs before
  telling whether it is a Windows image, as BuildKit does; a stage
  named FROM ${BASE} was formatted as POSIX shell, turning cmd's escaped
  ^| into a pipe.
- JSON-form arguments with backslashes keep the JSON form, which suits
  Windows paths and avoids a fallback warning.
- A legacy ENV or LABEL value with comment lines is left as written.
- A shell body that can't be formatted after flag lines leaves the whole
  instruction as written, rather than re-indenting its first line only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The printer indents the continued arguments of a command after && one
level deeper than the && lines, but those of the first command level with
them. They now get the same extra level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
COPY and ADD sources, and the elements of JSON arrays, written across
lines were joined into one long line. A heredoc no longer moves off the
line of a single --mount flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Case items are indented under case, as the official images and most
scripts write them (shfmt -ci). A ;; the printer moved onto its own line
no longer gets a ";" before it when joined back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…bodies

Turning statement breaks into continuations gave every line one more
level, so a && chain containing a block, like nginx's RUN, had its &&
lines pushed in. The first statement's lines now get the extra level
only if it is a block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"SHELL\f0" lost its argument, which changed the shell later instructions
were formatted for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pre-commit hook already passed --space-redirects, and the official
images mostly write "> file". --space-redirects=false, or spaceRedirects:
false in JS, turns it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BuildKit stores stage names in lower case (its StageNameCasing check) and
finds the stage of COPY --from and RUN --mount from= ignoring case. FROM
looks a stage up as written, so lowering "FROM Builder" makes it build on
the stage builder, as intended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#comment becomes # comment between instructions and on comment lines
inside continuations. Parser directives and # check= lines, shebangs and
banners such as ##### are left alone, and #dockerfmt-ignore is honored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e file

Also rewrite the README to be shorter and easier to read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@reteps
reteps merged commit b60349d into main Nov 14, 2026
6 checks passed
@reteps
reteps deleted the chore/cleanup-and-lint branch November 14, 2026 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant