cargo install keepsortedkeepsorted 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.
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. Binary files are skipped automatically.
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 and Bazel require
one of these comments. Cargo.toml, .gitignore, and CODEOWNERS are sorted
automatically when the matching feature flag is enabled.
# Keep sorted
# comment B
b
# comment A
abecomes
# Keep sorted
# comment A
a
# comment B
b// Keep sorted
// comment two
second
// comment one
firstbecomes
// Keep sorted
// comment one
first
// comment two
second-- Keep sorted
-- c comment
c
-- a comment
abecomes
-- Keep sorted
-- a comment
a
-- c comment
csrcs = [
# Keep sorted
"b",
# note for a
"a",
]becomes
srcs = [
# Keep sorted
# note for a
"a",
"b",
][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"# Build
/b
/abecomes
# Build
/a
/b# Team
b
# Lead
abecomes
# Team
a
# Lead
bThe 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_canonicalkeepsorted 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.