Skip to content

Stdin Specification

Formatters MAY also implement the Stdin Specification, which allows formatting virtual files passed via stdin.

A formatter MUST implement the Stdin Specification if its formatting behavior can depend on the path of the file being formatted.

Terms

  • virtual file: Conceptually, represents some file the formatter is supposed to treat "as if" it existed on disk. Concretely, a virtual file is a buffer (passed via stdin) and an advisory path (passed as a CLI option).
  • advisory path: Represents the path of some virtual file. Called "advisory" because it MAY be passed to a formatter, and the formatter MAY alter its behavior based on the given advisory path.

Rules

In order for the formatter to comply with this spec, it MUST implement the vanilla Formatter Specification, and additionally satisfy the following:

1. Command line option

The formatter's CLI MUST have some option to activate Stdin mode.

The CLI SHOULD accept an advisory path to make the formatter pretend stdin comes from this file.

The formatter MAY alter its behavior based on the given advisory path. For example, if there are different formatting rules in different directories, or for use in error messages. If the formatter's behavior doesn't depend on the given advisory path, it's ok to ignore it.

The CLI option SHOULD be called --stdin-filepath:

$ echo "{}" | nixfmt --stdin-filepath path/to/file.nix

However, other options are OK, such as -path:

$ echo 'print( "hello")' | buildifier -path foo.bzl

It's OK if the formatter does not accept an advisory path (which implies the formatter's behavior does not depend on file paths, which means the Stdin Specification is optional).

$ echo 'print( "hello")' | ruff format -

2. Stdin mode

When in stdin mode, the formatter:

  1. MUST print the formatted file to stdout.
  2. MUST NOT attempt to read the file on the filesystem. Instead, it MUST read from stdin.
  3. MUST NOT write to the given path on the filesytem. It MAY write to temporary files elsewhere on disk, but SHOULD clean them up when done.