GitHub - nushell/nufmt: An AST-based formatter for Nushell scripts, built on Nushell's own parser
Repository navigation
nufmtPublic
About
An AST-based formatter for Nushell scripts, built on Nushell's own parser
www.nushell.shTopics
cli code-formatter formatter nushell rustResources
Readme MIT licenseContributing
Contributing Activity Custom propertiesStars
242 starsWatchers
9 watchingForks
50 forks Report repositoryBranches
Tags
Go to Branches page Go to Tags page
Latest commit
History
116 Commits
View commit history for this file.
Folders and files
| Name | Name | Last commit message | Last commit date |
|---|---|---|---|
| .github | .github | ||
| benches | benches | ||
| docs | docs | ||
| src | src | ||
| tests | tests | ||
| .gitattributes | .gitattributes | ||
| .gitignore | .gitignore | ||
| CHANGELOG.md | CHANGELOG.md | ||
| Cargo.lock | Cargo.lock | ||
| Cargo.toml | Cargo.toml | ||
| LICENSE | LICENSE | ||
| README.md | README.md | ||
| dist-workspace.toml | dist-workspace.toml | ||
| flake.lock | flake.lock | ||
| flake.nix | flake.nix | ||
| rustfmt.toml | rustfmt.toml | ||
| toolkit.nu | toolkit.nu | ||
Repository files navigation
nufmt: the nushell formatter
Table of contents
Features
nufmt is a formatter for Nushell scripts, built entirely on Nushell's own parsing infrastructure (nu-parser, nu-protocol). It provides:
- AST-based formatting : Uses Nushell's actual parser for accurate code understanding
- Idempotent output : Running the formatter twice produces the same result
- Comment preservation : Comments are preserved in their original positions
- Configurable : Supports configuration via NUON files
- Fast : Parallel file processing with Rayon
Installation
From source
cargo install --git https://github.com/nushell/nufmt
Using Nix
nix run github:nushell/nufmt
Usage
nufmt [OPTIONS] [FILES]...
Files
Format one or more Nushell files:
# Format a single file nufmt script.nu # Format multiple files nufmt file1.nu file2.nu file3.nu # Format all .nu files in a directory nufmt src/
Options
| Option | Short | Description |
|---|---|---|
--dry-run |
Check files without modifying them. Returns exit code 1 if files would be reformatted. | |
--stdin |
Read from stdin and write formatted output to stdout. Cannot be combined with file arguments. | |
--config |
-c |
Path to a configuration file (NUON format). |
--help |
-h |
Show help and exit. |
--version |
-v |
Print version and exit. |
Examples
# Format files in place nufmt *.nu # Check if files need formatting (CI mode) nufmt --dry-run src/ # Format stdin echo 'let x=1' | nufmt --stdin # Use custom config nufmt --config nufmt.nuon src/
Configuration
Create a nufmt.nuon file in your project root:
{
indent: 4
indent_char: "space"
line_length: 80
exclude: ["vendor/**", "target/**"]
consistent_branches: "single_line"
}
Configuration options:
| Option | Type | Default | Description |
|---|---|---|---|
indent |
int | 4 | Visual indentation width per level (tab width when indent_char = "tab") |
indent_char |
string | "space" |
Indentation character: "space" or "tab" |
line_length |
int | 80 | Maximum line length (advisory) |
margin |
int | Automatic | Blank lines between ordinary top-level items when set. 0 and 1 also control spacing between statements inside blocks. |
exclude |
list<string> | [] | Glob patterns for files to exclude |
consistent_branches |
string | "single_line" |
When one branch of an if/else or try/catch chain spans several lines, put every branch on its own lines: "single_line" for chains written on one line, "always" for every chain, "never" to lay out each branch independently |
Leave margin out to keep up to one existing blank line between ordinary statements.
At the top level, nufmt still adds a blank line between variable (let or mut) and constant (const or export const) declarations, or between two such declarations when either spans multiple lines.
Set margin: 1 to insert a blank line between ordinary statements even when they are adjacent in the source.
At the top level, nufmt removes blank lines between adjacent use and export use imports.
It also removes blank lines within groups of single-line variable declarations or single-line constant declarations when no comment separates them.
Exit codes
| Code | Description |
|---|---|
| 0 | Success (files formatted or already formatted) |
| 1 | Dry-run mode: at least one file would be reformatted |
| 2 | Error: invalid configuration, CLI options, or parse error |
Pre-commit
Install nufmt and make sure it is on PATH. Add this local hook to your .pre-commit-config.yaml.
repos:
- repo: local
hooks:
- id: nufmt
name: Format Nushell files
entry: nufmt
language: unsupported
files: '\.nu$'
args: ["--"]
With pre-commit versions older than 4.4, use language: system.
The hook formats .nu files in place. Stage the formatted files and rerun the hook if it makes changes.
If you add formatter options to args, keep -- at the end to support filenames that start with -.
Pre-commit passes filenames directly to nufmt, bypassing the exclude globs in nufmt.nuon.
Use the hook's exclude regex to skip paths relative to the repository root.
For example, add exclude: '^vendor/' next to files to skip files under vendor/.
Supported Constructs
nufmt properly formats the following Nushell constructs:
- ✅ Variable declarations (
let,mut,const) - ✅ Function definitions (
def,def-env,export def) - ✅ Control flow (
if/else,match,for,while,loop) - ✅ Pipelines with proper spacing around
| - ✅ Lists and records
- ✅ Closures with parameters (
{|x| ... }) - ✅ String interpolation (
$"Hello ($name)") - ✅ Modules (
module,use,export) - ✅ Error handling (
try/catch) - ✅ Comments (preserved in output)
- ✅ Ranges (
1..10,1..2..10) - ✅ Binary operations with proper spacing
How It Works
Unlike tree-sitter based formatters, nufmt uses Nushell's own nu-parser crate to parse scripts into an AST. This ensures:
- Accuracy : The same parser that runs your scripts formats them
- Compatibility : Always in sync with Nushell's syntax
- Error detection : Invalid syntax is detected before formatting
The formatter walks the AST and emits properly formatted code with consistent:
- Indentation (configurable)
- Spacing around operators and keywords
- Brace placement for blocks
- Comment placement
Testing
nufmt has a comprehensive ground truth testing system that verifies the formatter produces correct output for all supported Nushell constructs.
Ground Truth Tests
The testing system uses two sets of fixture files:
- Input files (
tests/fixtures/input/): Contain valid Nushell code with intentional formatting issues (extra spaces, inconsistent indentation, etc.) - Expected files (
tests/fixtures/expected/): Contain the correctly formatted version of each input file
When tests run, the formatter processes each input file and compares the output against the corresponding expected file. This ensures:
- The formatter produces consistent, correct output
- Formatting changes are intentional and reviewed
- Regressions are caught immediately
Important : Input files should always differ from expected files. Input files represent "what not to do" - poorly formatted but valid Nushell code that the formatter should fix.
Test Categories
Tests are organized by Nushell construct category:
| Category | Constructs |
|---|---|
core |
let_statement, mut_statement, const_statement, def_statement |
control_flow |
if_else, for_loop, while_loop, loop_statement, match_expr, try_catch, break_continue, return_statement |
data_structures |
list, record, table, nested_structures |
pipelines_expressions |
pipeline, multiline_pipeline, closure, subexpression, binary_ops, range, cell_path, spread |
strings_interpolation |
string_interpolation, comment |
types_values |
value_with_unit, datetime, nothing, glob_pattern |
modules_imports |
module, use_statement, export, source, hide, overlay |
commands_definitions |
alias, extern, external_call |
special_constructs |
do_block, where_clause, error_make |
Running Tests
Rust Tests
use toolkit.nu # Run the same checks as CI toolkit ci # Run individual checks toolkit test toolkit clippy toolkit rustdoc # Check only benchmark tests cargo test --benches # Run only ground truth tests cargo test --test ground_truth # Run with verbose output cargo test -- --nocapture
Nushell Test Runner
A Nushell script (tests/run_ground_truth_tests.nu) provides a more interactive testing experience:
# Build the release binary first cargo build --release # Run all tests nu tests/run_ground_truth_tests.nu # Run with verbose output (show diffs on failure) nu tests/run_ground_truth_tests.nu --verbose # Run only ground truth tests (skip idempotency) nu tests/run_ground_truth_tests.nu --ground-truth # Run only idempotency tests nu tests/run_ground_truth_tests.nu --idempotency # Run tests for a specific category nu tests/run_ground_truth_tests.nu --category control_flow # Run a single test nu tests/run_ground_truth_tests.nu --test let_statement # List all available tests nu tests/run_ground_truth_tests.nu --list # List available categories nu tests/run_ground_truth_tests.nu --list-categories # Check which test files exist nu tests/run_ground_truth_tests.nu --check-files
Adding New Tests
To add a test for a new construct:
- Create an input file at
tests/fixtures/input/<construct_name>.nuwith poorly-formatted but valid Nushell code - Create an expected file at
tests/fixtures/expected/<construct_name>.nuwith the correctly formatted version - Add the construct name to the appropriate category in
tests/run_ground_truth_tests.nu - Run the tests to verify
Example input file (tests/fixtures/input/my_construct.nu):
let x = 1 let y = 2
Example expected file (tests/fixtures/expected/my_construct.nu):
let x = 1 let y = 2
Contributing
Contributions are welcome! Please see our contribution guide .
Reporting issues
If you encounter formatting issues, please:
- Check if the script is valid Nushell syntax
- Provide a minimal reproduction case
- Include your
nufmtversion and Nushell version
License
MIT License - see LICENSE for details.
About
An AST-based formatter for Nushell scripts, built on Nushell's own parser
www.nushell.sh