ruff/crates/ruff_python_formatter/src/main.rs
konsti 1031bb6550
Formatter: Add SourceType to context to enable special formatting for stub files (#6331)
**Summary** This adds the information whether we're in a .py python
source file or in a .pyi stub file to enable people working on #5822 and
related issues.

I'm not completely happy with `Default` for something that depends on
the input.

**Test Plan** None, this is currently unused, i'm leaving this to first
implementation of stub file specific formatting.

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
2023-08-04 11:52:26 +00:00

55 lines
1.8 KiB
Rust

use std::io::{stdout, Read, Write};
use std::path::Path;
use std::{fs, io};
use anyhow::{bail, Context, Result};
use clap::Parser as ClapParser;
use ruff_python_formatter::cli::{format_and_debug_print, Cli, Emit};
/// Read a `String` from `stdin`.
pub(crate) fn read_from_stdin() -> Result<String> {
let mut buffer = String::new();
io::stdin().lock().read_to_string(&mut buffer)?;
Ok(buffer)
}
#[allow(clippy::print_stdout)]
fn main() -> Result<()> {
let cli: Cli = Cli::parse();
if cli.files.is_empty() {
if !matches!(cli.emit, None | Some(Emit::Stdout)) {
bail!(
"Can only write to stdout when formatting from stdin, but you asked for {:?}",
cli.emit
);
}
let input = read_from_stdin()?;
// It seems reasonable to give this a dummy name
let formatted = format_and_debug_print(&input, &cli, Path::new("stdin.py"))?;
if cli.check {
if formatted == input {
return Ok(());
}
bail!("Content not correctly formatted")
}
stdout().lock().write_all(formatted.as_bytes())?;
} else {
for file in &cli.files {
let input = fs::read_to_string(file)
.with_context(|| format!("Could not read {}: ", file.display()))?;
let formatted = format_and_debug_print(&input, &cli, file)?;
match cli.emit {
Some(Emit::Stdout) => stdout().lock().write_all(formatted.as_bytes())?,
None | Some(Emit::Files) => {
fs::write(file, formatted.as_bytes()).with_context(|| {
format!("Could not write to {}, exiting", file.display())
})?;
}
}
}
}
Ok(())
}