- Notifications
You must be signed in to change notification settings - Fork933
Format Rust code
License
Apache-2.0, MIT licenses found
Licenses found
rust-lang/rustfmt
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A tool for formatting Rust code according to style guidelines.
If you'd like to help out (and you should, it's a fun project!), seeContributing.md and ourCode ofConduct.
You can use rustfmt in Travis CI builds. We provide a minimal Travis CIconfiguration (seehere).
You can runrustfmt
with Rust 1.24 and above.
To install:
rustup component add rustfmt
To run on a cargo project in the current working directory:
cargo fmt
For the latest and greatestrustfmt
, nightly is required.
To install:
rustup component add rustfmt --toolchain nightly
To run on a cargo project in the current working directory:
cargo +nightly fmt
Rustfmt tries to work on as much Rust code as possible. Sometimes, the codedoesn't even need to compile! In general, we are looking to limit areas ofinstability; in particular, post-1.0, the formatting of most code should notchange as Rustfmt improves. However, there are some things that Rustfmt can'tdo or can't do well (and thus where formatting might change significantly,even post-1.0). We would like to reduce the list of limitations over time.
The following list enumerates areas where Rustfmt does not work or where thestability guarantees do not apply (we don't make a distinction between the twobecause in the future Rustfmt might work on code where it currently does not):
- a program where any part of the program does not parse (parsing is an earlystage of compilation and in Rust includes macro expansion).
- Macro declarations and uses (current status: some macro declarations and usesare formatted).
- Comments, including any AST node with a comment 'inside' (Rustfmt does notcurrently attempt to format comments, it does format code with comments inside, but that formatting may change in the future).
- Rust code in code blocks in comments.
- Any fragment of a program (i.e., stability guarantees only apply to wholeprograms, even where fragments of a program can be formatted today).
- Code containing non-ascii unicode characters (we believe Rustfmt mostly workshere, but do not have the test coverage or experience to be 100% sure).
- Bugs in Rustfmt (like any software, Rustfmt has bugs, we do not consider bugfixes to break our stability guarantees).
You can run Rustfmt by just typingrustfmt filename
if you usedcargo install
. This runs rustfmt on the given file, if the file includes out of linemodules, then we reformat those too. So to run on a whole module or crate, youjust need to run on the root file (usually mod.rs or lib.rs). Rustfmt can alsoread data from stdin. Alternatively, you can usecargo fmt
to format allbinary and library targets of your crate.
You can runrustfmt --help
for information about available arguments.The easiest way to run rustfmt against a project is withcargo fmt
.cargo fmt
works on bothsingle-crate projects andcargo workspaces.Please seecargo fmt --help
for usage information.
You can specify the path to your ownrustfmt
binary for cargo to use by setting theRUSTFMT
environment variable. This was added in v1.4.22, so you must have this version or newer to leverage this feature (cargo fmt --version
)
To format individual files or arbitrary codes from stdin, therustfmt
binary should be used. Someexamples follow:
rustfmt lib.rs main.rs
will format "lib.rs" and "main.rs" in placerustfmt
will read a code from stdin and write formatting to stdoutecho "fn main() {}" | rustfmt
would emit "fn main() {}".
For more information, including arguments and emit options, seerustfmt --help
.
When running with--check
, Rustfmt will exit with0
if Rustfmt would notmake any formatting changes to the input, and1
if Rustfmt would make changes.In other modes, Rustfmt will exit with1
if there was some error duringformatting (for example a parsing or internal error) and0
if formattingcompleted without error (whether or not changes were made).
To keep your code base consistently formatted, it can be helpful to fail the CI buildwhen a pull request contains unformatted code. Using--check
instructsrustfmt to exit with an error code if the input is not formatted correctly.It will also print any found differences. (Older versions of Rustfmt don'tsupport--check
, use--write-mode diff
).
A minimal Travis setup could look like this (requires Rust 1.31.0 or greater):
language:rustbefore_script:-rustup component add rustfmtscript:-cargo build-cargo test-cargo fmt --all -- --check
Seethis blog postfor more info.
cargo build
to build.
cargo test
to run all tests.
To run rustfmt after this, usecargo run --bin rustfmt -- filename
. See thenotes above on running rustfmt.
Rustfmt is designed to be very configurable. You can create a TOML file calledrustfmt.toml
or.rustfmt.toml
, place it in the project or any other parentdirectory and it will apply the options in that file. Seerustfmt --help=config
for the options which are available, or if you prefer to seevisual style previews,GitHub page.
By default, Rustfmt uses a style which conforms to theRust style guide that has been formalized through thestyle RFCprocess.
Configuration options are either stable or unstable. Stable options can alwaysbe used, while unstable ones are only available on a nightly toolchain, and opt-in.SeeGitHub page for details.
Theedition
option determines the Rust language edition used for parsing the code. This is important for syntax compatibility but does not directly control formatting behavior (seeStyle Editions).
When runningcargo fmt
, theedition
is automatically read from theCargo.toml
file. However, when runningrustfmt
directly, theedition
defaults to 2015. For consistent parsing between rustfmt andcargo fmt
, you should configure theedition
in yourrustfmt.toml
file:
edition ="2018"
This option is inferred from theedition
if not specified.
SeeRust Style Editions for details on formatting differences between style editions.rustfmt has a default style edition of2015
whilecargo fmt
infers the style edition from theedition
set inCargo.toml
. This can lead to inconsistencies betweenrustfmt
andcargo fmt
if the style edition is not explicitly configured.
To ensure consistent formatting, it is recommended to specify thestyle_edition
in arustfmt.toml
configuration file. For example:
style_edition ="2024"
To ensure consistent parsing between
cargo fmt
andrustfmt
, you should configure theedition
in yourrustfmt.toml
file.To ensure consistent formatting between
cargo fmt
andrustfmt
, you should configure thestyle_edition
in yourrustfmt.toml
file.For things you do not want rustfmt to mangle, use
#[rustfmt::skip]
To prevent rustfmt from formatting a macro or an attribute,use
#[rustfmt::skip::macros(target_macro_name)]
or#[rustfmt::skip::attributes(target_attribute_name)]
Example:
#![rustfmt::skip::attributes(custom_attribute)]#[custom_attribute(formatting, here, should, be,Skipped)]#[rustfmt::skip::macros(html)]fn main(){let macro_result1 =html!{ <div>Hello</div>}.to_string();
When you run rustfmt, place a file named
rustfmt.toml
or.rustfmt.toml
intarget file directory or its parents to override the default settings ofrustfmt. You can generate a file containing the default configuration withrustfmt --print-config default rustfmt.toml
and customize as needed.After successful compilation, a
rustfmt
executable can be found in thetarget directory.If you're having issues compiling Rustfmt (or compile errors when trying toinstall), make sure you have the most recent version of Rust installed.
You can change the way rustfmt emits the changes with the --emit flag:
Example:
cargo fmt -- --emit files
Options:
Flag Description Nightly Only files overwrites output to files No stdout writes output to stdout No coverage displays how much of the input file was processed Yes checkstyle emits in a checkstyle format Yes json emits diffs in a json format Yes
Rustfmt is distributed under the terms of both the MIT license and theApache License (Version 2.0).
SeeLICENSE-APACHE andLICENSE-MIT for details.
About
Format Rust code
Topics
Resources
License
Apache-2.0, MIT licenses found
Licenses found
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.