Crate keepsorted

Source
Expand description

§keepsorted

keepsorted GitHub Actions keepsorted on crates.io keepsorted on docs.rs

cargo install keepsorted

§Overview

keepsorted sorts lists of lines while keeping nearby comments with the lines that follow them. Add a comment like Keep sorted and the tool will reorder the next block. Some file types are sorted automatically.

§Usage

keepsorted --check <path>   # verify without changes
keepsorted --diff <path>    # preview changes as a diff
keepsorted --fix <path>     # rewrite files in place (default)

Use --recursive (-r) to process directories. Combine with git ls-files in CI to check only tracked files.

§Keywords

  • Keep sorted or keepsorted: keep sorted – sort the next block.
  • keepsorted: ignore file – skip the whole file.
  • keepsorted: ignore block – skip a single block.

Markers work with #, //, or -- comments. Generic files and Bazel require one of these comments. Cargo.toml, .gitignore, and CODEOWNERS are sorted automatically when the matching feature flag is enabled.

§Examples

§Generic text (Python)
# Keep sorted
# comment B
b
# comment A
a

becomes

# Keep sorted
# comment A
a
# comment B
b
§Generic text (C++)
// Keep sorted
// comment two
second
// comment one
first

becomes

// Keep sorted
// comment one
first
// comment two
second
§Generic text (SQL/Lua)
-- Keep sorted
-- c comment
c
-- a comment
a

becomes

-- Keep sorted
-- a comment
a
-- c comment
c
§Bazel
srcs = [
    # Keep sorted
    "b",
    # note for a
    "a",
]

becomes

srcs = [
    # Keep sorted
    # note for a
    "a",
    "b",
]
§Cargo.toml
[dependencies]
b = "2"
a = "1"

# keepsorted: ignore block
[dev-dependencies]
z = "1"
y = "2"

becomes

[dependencies]
a = "1"
b = "2"

# keepsorted: ignore block
[dev-dependencies]
z = "1"
y = "2"
§.gitignore
# Build
/b
/a

becomes

# Build
/a
/b
§CODEOWNERS
# Team
b
# Lead
a

becomes

# Team
a
# Lead
b

§Experimental features

The following features are behind flags because sorting might change behaviour:

  • gitignore and codeowners – order matters, so enable with care.
  • rust_derive_alphabetical and rust_derive_canonical – temporary helpers for sorting Rust #[derive(...)] lists until rustfmt gains this ability. These implementations are intentionally simple.

Enable features with --features:

keepsorted file --features gitignore,rust_derive_canonical

§Limitations

keepsorted intentionally does not:

  • Handle advanced directory traversal or ignore rules automatically.
  • Act as a full-fledged parser for every file type.
  • Handle ignore files or exclude paths automatically.
  • Automatically detect project structure or configuration files.
  • Replace formatting tools like rustfmt or prettier.

Enums§

Strategy
Available sorting strategies.

Functions§

process_file
Returns the sorted content of a file using an appropriate strategy.
process_lines
Sorts lines according to the chosen Strategy and returns the reordered lines.