keepsorted
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
Check a single file:
keepsorted --check file.txt
Check a directory recursively:
keepsorted --check --recursive .
Check only git-tracked files:
git ls-files | xargs -n1 keepsorted --check
Fix files in place (default mode):
keepsorted file.txt
Modes
--fix(default): Rewrites files in place.--check: Verifies files are sorted. Returns exit code 4 if not.--diff: Prints a diff of changes without modifying files.
Keywords
Keep sortedorkeepsorted: 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 support any of these. Bazel files require #. Cargo.toml, .gitignore, and CODEOWNERS are sorted
automatically when the matching feature flag is enabled.
Examples
Generic text (Python)
# Keep sorted
# comment B
# comment A
becomes
# Keep sorted
# comment A
# comment B
Generic text (C++)
// Keep sorted
// comment two
second
// comment one
becomes
// Keep sorted
// comment one
first
// comment two
Generic text (SQL/Lua)
-- Keep sorted
-- c comment
c
-- a comment
a
becomes
-- Keep sorted
-- a comment
a
-- c comment
c
Bazel
=
becomes
=
Cargo.toml
[]
= "2"
= "1"
# keepsorted: ignore block
[]
= "1"
= "2"
becomes
[]
= "1"
= "2"
# keepsorted: ignore block
[]
= "1"
= "2"
.gitignore
# Build
/b
/a
becomes
# Build
/a
/b
CODEOWNERS
# Team
b
# Lead
a
becomes
# Lead
a
# Team
b
Experimental features
The following features are behind flags because sorting might change behaviour:
gitignoreandcodeowners– order matters, so enable with care.rust_derive_alphabeticalandrust_derive_canonical– temporary helpers to reorder#[derive(...)]attributes.cargo fmtdoes not yet sort derives (rust-lang/rustfmt#6574). These features are hidden behind flags and only perform alphabetical or canonical ordering. Users have been requesting derive sorting since 2017, sokeepsortedfills the gap for now. Consider upvoting the issue if you want built-in support.
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
rustfmtorprettier.