mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-28 21:05:08 +00:00
Add a --check flag to the formatter CLI (#6982)
## Summary Returns an exit code of 1 if any files would be reformatted: ``` ruff on charlie/format-check:main [$?⇡] is 📦 v0.0.286 via 🐍 v3.11.2 via 🦀 v1.72.0 ❯ cargo run -p ruff_cli -- format foo.py --check Compiling ruff_cli v0.0.286 (/Users/crmarsh/workspace/ruff/crates/ruff_cli) Finished dev [unoptimized + debuginfo] target(s) in 1.69s Running `target/debug/ruff format foo.py --check` warning: `ruff format` is a work-in-progress, subject to change at any time, and intended only for experimentation. 1 file would be reformatted ruff on charlie/format-check:main [$?⇡] is 📦 v0.0.286 via 🐍 v3.11.2 via 🦀 v1.72.0 took 2s ❯ echo $? 1 ``` Closes #6966.
This commit is contained in:
parent
25c374856a
commit
fad23bbe60
5 changed files with 84 additions and 16 deletions
|
@ -6,6 +6,7 @@ use ruff_python_formatter::{format_module, PyFormatOptions};
|
|||
use ruff_workspace::resolver::python_file_at_path;
|
||||
|
||||
use crate::args::{FormatArguments, Overrides};
|
||||
use crate::commands::format::FormatMode;
|
||||
use crate::resolve::resolve;
|
||||
use crate::stdin::read_from_stdin;
|
||||
use crate::ExitStatus;
|
||||
|
@ -18,6 +19,11 @@ pub(crate) fn format_stdin(cli: &FormatArguments, overrides: &Overrides) -> Resu
|
|||
overrides,
|
||||
cli.stdin_filename.as_deref(),
|
||||
)?;
|
||||
let mode = if cli.check {
|
||||
FormatMode::Check
|
||||
} else {
|
||||
FormatMode::Write
|
||||
};
|
||||
|
||||
if let Some(filename) = cli.stdin_filename.as_deref() {
|
||||
if !python_file_at_path(filename, &pyproject_config, overrides)? {
|
||||
|
@ -25,13 +31,27 @@ pub(crate) fn format_stdin(cli: &FormatArguments, overrides: &Overrides) -> Resu
|
|||
}
|
||||
}
|
||||
|
||||
let stdin = read_from_stdin()?;
|
||||
// Format the file.
|
||||
let unformatted = read_from_stdin()?;
|
||||
let options = cli
|
||||
.stdin_filename
|
||||
.as_deref()
|
||||
.map(PyFormatOptions::from_extension)
|
||||
.unwrap_or_default();
|
||||
let formatted = format_module(&stdin, options)?;
|
||||
stdout().lock().write_all(formatted.as_code().as_bytes())?;
|
||||
Ok(ExitStatus::Success)
|
||||
let formatted = format_module(&unformatted, options)?;
|
||||
|
||||
match mode {
|
||||
FormatMode::Write => {
|
||||
stdout().lock().write_all(formatted.as_code().as_bytes())?;
|
||||
Ok(ExitStatus::Success)
|
||||
}
|
||||
FormatMode::Check => {
|
||||
if formatted.as_code().len() == unformatted.len() && formatted.as_code() == unformatted
|
||||
{
|
||||
Ok(ExitStatus::Success)
|
||||
} else {
|
||||
Ok(ExitStatus::Failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue