Skip to content
paqPublic

About

A fast C# formatter CLI written in F#.

Topics

Resources

Stars

19 stars

Watchers

0 watching

Forks

Repository files navigation

csff

A fast C# formatter CLI written in F#.

Why csff?

Most C# formatters were designed around editing code by hand: IDE extensions, background servers, and formatting one file on save. csff drops editor integration entirely and stays a standalone CLI.

When AI tools and developers change hundreds or thousands of files at once, whole-repository CI checks become the bottleneck. csff is tuned for formatting and checking an entire tree as fast as possible, not for single-file saves.

Benchmarks

Median time to format every .cs file in place (without cache) across 8 dotnet/* repositories:

Bar chart of the median time to format every .cs file in 8 dotnet/* repositories, measured on Mac mini, Apple M6. On dotnet/runtime: csff 1.6 s, CSharpier 61 s, dotnet format whitespace 104 s.

How it works

Instead of building on Roslyn, csff implements its own C# lexer, parser, and document printer in F#. Avoiding Roslyn's compiler overhead makes it over 20x faster than existing C# formatters on whole repositories. It compiles to a single Native AOT executable, formats files in parallel across available cores, and caches results per input root.

Example

Before

public class Inventory {
    public void Restock(Warehouse warehouse, IEnumerable<Item> items, DateTime today) {
        var orders = items.Where(i => i.Stock < i.ReorderPoint && !i.Discontinued)
          .OrderBy(i => i.Sku).Select(i => new RestockOrder{
            Sku=i.Sku, Quantity=i.ReorderPoint-i.Stock, Supplier=i.Supplier, DeliverBy=today.AddDays(7)
          }).ToList();
        if (orders.Count == 0) { return; }
        warehouse.Submit(orders, new DispatchOptions{Priority=Priority.High, NotifyOnDelay=true, Region="east"});
    }
}

After

public class Inventory
{
    public void Restock(Warehouse warehouse, IEnumerable<Item> items, DateTime today)
    {
        var orders = items
            .Where(i => i.Stock < i.ReorderPoint && !i.Discontinued)
            .OrderBy(i => i.Sku)
            .Select(i => new RestockOrder
            {
                Sku = i.Sku,
                Quantity = i.ReorderPoint - i.Stock,
                Supplier = i.Supplier,
                DeliverBy = today.AddDays(7),
            })
            .ToList();

        if (orders.Count == 0)
        {
            return;
        }

        warehouse.Submit(
            orders,
            new DispatchOptions
            {
                Priority = Priority.High,
                NotifyOnDelay = true,
                Region = "east",
            }
        );
    }
}

Getting started

Install as a .NET tool (Native AOT)

Install csff globally via NuGet (requires the .NET 10+ SDK on supported Native AOT platforms: linux-x64, linux-arm64, linux-musl-x64, linux-musl-arm64, osx-arm64, win-x64, win-arm64; the CLI automatically selects the matching native package):

dotnet tool install -g csff

Or run it once without installing:

dotnet tool exec csff -- --check .

On other platforms, the .NET CLI falls back to the portable managed package (csff.any), which requires the .NET 11 runtime.

Format all C# files in the current directory:

csff .

Check formatting without writing files (for CI or pre-commit hooks):

csff --check .

Format a single file or stdin to stdout:

csff --write-stdout path/to/File.cs
cat path/to/File.cs | csff --write-stdout

Standalone Native AOT archives (.tar.gz / .zip, no .NET installation required) are also published on GitHub Releases.

Build from source

Build the native executable (requires the .NET SDK pinned in global.json):

dotnet build -t:Native

This writes the binary to out/csff/bin/Csff.Cli (out/csff/bin/Csff.Cli.exe on Windows).

CLI reference

csff [--check | --write-stdout] [options] [files or directories...]

Formats .cs files only. With no paths, formats the current directory. Pass -- to stop option parsing before positional paths.

Options

Option Description
--check Report unformatted files without rewriting them (exits 1 if any file needs formatting).
--write-stdout Format a single file, or stdin when no path or - is given, and print to stdout. Cannot be combined with --check.
--config-path FILE Use the specified JSON or YAML configuration file instead of discovering configuration.
--ignore-path FILE Use the specified ignore file instead of discovered .csffignore / .gitignore files.
--include-generated Include files normally skipped as generated (by filename pattern or <auto-generated header).
--no-cache Neither read nor write the formatting cache.
--cache-path DIR Store bounded per-input-root cache files in DIR.
--jobs N Maximum number of parallel workers (positive integer; default: processor count).
-h, --help Show CLI usage and exit.

Caching

Caching is enabled by default. Inside a Git repository, cache files are stored in <repo-root>/out/csff/cache; outside a Git repository, they go to .cache/csff under the input root. Entries are keyed by file content hash and active formatting options, and invalidated automatically when the binary changes. Pass --cache-path DIR to store cache files elsewhere (for example, in CI) or --no-cache to disable caching.

Exit codes

Code Meaning
0 Success (all files formatted or already formatted).
1 One or more files failed to parse/format, or unformatted files were found under --check.
2 Invalid command-line arguments or configuration error.
3 One or more files could not be verified for syntax preservation and were left unchanged.
130 Cancelled (SIGINT / Ctrl+C).

Configuration

csff works with zero configuration by default. To customize formatting, add .csffrc.json, .csffrc.yaml, .csffrc.yml, or .editorconfig (see EditorConfig).

Configuration is resolved upward from each formatted .cs file's directory:

  1. If --config-path FILE is passed, that file is used.
  2. Otherwise, the nearest .csffrc.* file in the file's directory or an ancestor is used (checked in order: .csffrc.json, .csffrc.yaml, .csffrc.yml).
  3. Otherwise, .editorconfig files are resolved upward until root = true.

Options

Option Default Values Description
printWidth 100 positive integer Target line width at which the printer wraps code (guideline, not a hard limit).
useTabs false true, false Indent lines with tabs instead of spaces.
indentSize 4 positive integer Spaces per indentation level (or visual tab width when useTabs is true).
endOfLine "auto" "auto", "lf", "crlf", "cr" Line ending style to emit. "auto" preserves the file's first line break (defaults to lf if none).

JSON (.csffrc.json):

{
  "printWidth": 100,
  "useTabs": false,
  "indentSize": 4,
  "endOfLine": "auto"
}

YAML (.csffrc.yaml / .csffrc.yml):

printWidth: 100
useTabs: false
indentSize: 4
endOfLine: auto

Overrides

Use overrides to apply different options to files matching a glob pattern (relative to the configuration file's directory). Each entry inherits top-level options and requires a files pattern; when multiple entries match, the last match wins.

JSON:

{
  "printWidth": 100,
  "overrides": [
    {
      "files": "tests/**/*.cs",
      "printWidth": 120,
      "indentSize": 2
    }
  ]
}

YAML:

printWidth: 100
overrides:
  - files: "tests/**/*.cs"
    printWidth: 120
    indentSize: 2

EditorConfig

When no .csffrc.* file applies, csff reads .editorconfig files using standard inheritance (stopping at root = true and honoring unset).

.editorconfig key Values Maps to
indent_style space, tab useTabs
indent_size positive integer, tab indentSize
tab_width positive integer indentSize when indent_style = tab (or indent_size = tab)
max_line_length positive integer printWidth
end_of_line auto, lf, crlf, cr endOfLine
csff_formatter csharp (any other value excludes matching files) enable/disable formatting

Example:

root = true

[*.cs]
indent_style = space
indent_size = 4
max_line_length = 100
end_of_line = lf

[src/Legacy/*.cs]
csff_formatter = none

Ignoring files and code

csff respects .csffignore (nearest ancestor, or --ignore-path FILE) and .gitignore (inherited up to the .git directory). The .git, bin, obj, node_modules, and .cache directories are always skipped.

Generated files matching *.g.cs, *.g.i.cs, *.designer.cs, *.generated.cs, TemporaryGeneratedFile_*.cs, or starting with an <auto-generated / <autogenerated comment are skipped unless --include-generated is passed.

To skip specific code in a file, place // csff-ignore before a statement or member, or wrap a block with // csff-ignore-start and // csff-ignore-end:

public class Matrix
{
    // csff-ignore
    public static readonly int[,] Transform =
    {
        {  1,  0,  0 },
        {  0, -1,  0 },
        {  0,  0,  1 },
    };

    public void Configure()
    {
        // csff-ignore-start
        Register("GET",    "/items",      ListItems);
        Register("POST",   "/items",      CreateItem);
        Register("DELETE", "/items/{id}", DeleteItem);
        // csff-ignore-end
    }
}

Development

Requires the .NET SDK pinned in global.json.

# Build the native CLI (out/csff/bin/Csff.Cli)
dotnet build -t:Native

# Run the test suite
dotnet run --project tests/Csff.Tests -c Release

# Run F# analyzers
dotnet build -t:Lint

For benchmarks and allocation gates, see benchmarks/Csff.ToolComparison and benchmarks/Csff.Benchmarks.

License

MIT. See LICENSE.

Some test cases and expected outputs are adapted from CSharpier. Third-party notices for CSharpier, FSharp.Core, the .NET runtime, and Roslyn are in THIRD-PARTY-NOTICES.txt.

About

A fast C# formatter CLI written in F#.

Topics

Resources

Stars

19 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages