1
Fork 0
mirror of https://github.com/RGBCube/alejandra synced 2025-07-30 12:07:46 +00:00

feat: more levels of --quiet

This commit is contained in:
Kevin Amado 2022-08-07 12:17:43 -06:00
parent ccb31f3523
commit cf8b9d8cfa
6 changed files with 88 additions and 50 deletions

View file

@ -97,6 +97,7 @@
- [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=kamadorueda.alejandra) - [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=kamadorueda.alejandra)
- [Neovim](./integrations/neovim/README.md) - [Neovim](./integrations/neovim/README.md)
- [Vim](./integrations/vim/README.md)
- [GNU Emacs](./integrations/gnu-emacs/README.md) - [GNU Emacs](./integrations/gnu-emacs/README.md)
- [Doom Emacs](./integrations/doom-emacs/README.md) - [Doom Emacs](./integrations/doom-emacs/README.md)
- [Pre-commit](./integrations/pre-commit/README.md) - [Pre-commit](./integrations/pre-commit/README.md)

View file

@ -2,7 +2,9 @@
In order to use Alejandra with In order to use Alejandra with
[Neovim](https://neovim.io/) [Neovim](https://neovim.io/)
please use any of the following plugins: please use the `:%!alejandra -qq` command
to format the current buffer,
or use any of the following plugins:
- [Neoformat](https://github.com/sbdchd/neoformat) - [Neoformat](https://github.com/sbdchd/neoformat)
- [null-ls.nvim](https://github.com/jose-elias-alvarez/null-ls.nvim) - [null-ls.nvim](https://github.com/jose-elias-alvarez/null-ls.nvim)

View file

@ -0,0 +1,6 @@
# Vim integration
In order to use Alejandra with
[Vim](https://www.vim.org/)
please use the `:%!alejandra -qq` command
to format the current buffer.

View file

@ -1,35 +1,30 @@
use std::io::Read; use std::io::Read;
use clap::value_parser;
use clap::ArgAction;
use clap::Parser; use clap::Parser;
use futures::future::RemoteHandle; use futures::future::RemoteHandle;
use futures::stream::FuturesUnordered; use futures::stream::FuturesUnordered;
use futures::task::SpawnExt; use futures::task::SpawnExt;
use crate::ads::random_ad; use crate::ads::random_ad;
use crate::verbosity::Verbosity;
#[derive(Clone)]
pub(crate) struct FormattedPath {
pub path: String,
pub status: alejandra::format::Status,
}
const AFTER_HELP: &str = concat!(
"Alejandra will exit with status code:\n",
" 1, if any error occurs.\n",
" 2, if --check was used and any file requires formatting.\n",
" 0, otherwise.",
);
/// The Uncompromising Nix Code Formatter. /// The Uncompromising Nix Code Formatter.
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
name="Alejandra", name="Alejandra",
after_help = AFTER_HELP, after_help = concat!(
"Alejandra will exit with status code:\n",
" 1, if any error occurs.\n",
" 2, if --check was used and any file requires formatting.\n",
" 0, otherwise.",
),
term_width = 80, term_width = 80,
version, version,
)] )]
struct Args { struct CLIArgs {
/// Files or directories, or a single "-" (or leave empty) to format stdin. /// Files or directories, or a single "-" (or leave empty) to format stdin.
#[clap(multiple_values = true)] #[clap(multiple_values = true)]
include: Vec<String>, include: Vec<String>,
@ -45,25 +40,34 @@ struct Args {
/// Number of formatting threads to spawn. Defaults to the number of /// Number of formatting threads to spawn. Defaults to the number of
/// physical CPUs. /// physical CPUs.
#[clap(long, short, value_parser = clap::value_parser!(u8).range(1..))] #[clap(long, short, value_parser = value_parser!(u8).range(1..))]
threads: Option<u8>, threads: Option<u8>,
/// Hide the details, only show error messages. /// Use once to hide informational messages,
#[clap(long, short)] /// twice to hide error messages.
quiet: bool, #[clap(long, short, action = ArgAction::Count)]
quiet: u8,
} }
pub(crate) fn stdin(quiet: bool) -> FormattedPath { #[derive(Clone)]
struct FormattedPath {
pub path: String,
pub status: alejandra::format::Status,
}
fn format_stdin(verbosity: Verbosity) -> FormattedPath {
let mut before = String::new(); let mut before = String::new();
let path = "<anonymous file on stdin>".to_string(); let path = "<anonymous file on stdin>".to_string();
if !quiet { if verbosity.allows_info() {
eprintln!("Formatting stdin."); eprintln!("Formatting stdin.");
eprintln!("Use --help to see all command line options."); eprintln!("Use --help to see all command line options.");
eprintln!("use --quiet to suppress this and all messages."); eprintln!("use --quiet to suppress this and other messages.");
} }
std::io::stdin().read_to_string(&mut before).unwrap(); std::io::stdin()
.read_to_string(&mut before)
.expect("Unable to read stdin.");
let (status, data) = let (status, data) =
alejandra::format::in_memory(path.clone(), before.clone()); alejandra::format::in_memory(path.clone(), before.clone());
@ -73,15 +77,15 @@ pub(crate) fn stdin(quiet: bool) -> FormattedPath {
FormattedPath { path, status } FormattedPath { path, status }
} }
pub(crate) fn simple( fn format_paths(
paths: Vec<String>, paths: Vec<String>,
in_place: bool, in_place: bool,
quiet: bool, verbosity: Verbosity,
threads: usize, threads: usize,
) -> Vec<FormattedPath> { ) -> Vec<FormattedPath> {
let paths_len = paths.len(); let paths_len = paths.len();
if !quiet { if verbosity.allows_info() {
eprintln!( eprintln!(
"{} {paths_len} file{} using {threads} thread{}.", "{} {paths_len} file{} using {threads} thread{}.",
"Checking style in", "Checking style in",
@ -94,7 +98,7 @@ pub(crate) fn simple(
let pool = futures::executor::ThreadPoolBuilder::new() let pool = futures::executor::ThreadPoolBuilder::new()
.pool_size(threads) .pool_size(threads)
.create() .create()
.expect("Unable to instantiate a new thread pool"); .expect("Unable to instantiate a new thread pool.");
let futures: FuturesUnordered<RemoteHandle<FormattedPath>> = paths let futures: FuturesUnordered<RemoteHandle<FormattedPath>> = paths
.into_iter() .into_iter()
@ -103,7 +107,7 @@ pub(crate) fn simple(
let status = alejandra::format::in_fs(path.clone(), in_place); let status = alejandra::format::in_fs(path.clone(), in_place);
if let alejandra::format::Status::Changed(changed) = status { if let alejandra::format::Status::Changed(changed) = status {
if changed && !quiet { if changed && verbosity.allows_info() {
println!( println!(
"{}: {path}", "{}: {path}",
if in_place { if in_place {
@ -117,7 +121,7 @@ pub(crate) fn simple(
FormattedPath { path: path.clone(), status } FormattedPath { path: path.clone(), status }
}) })
.expect("Unable to spawn formatting task") .expect("Unable to spawn formatting task.")
}) })
.collect(); .collect();
@ -125,25 +129,30 @@ pub(crate) fn simple(
} }
pub fn main() -> std::io::Result<()> { pub fn main() -> std::io::Result<()> {
let args = Args::parse(); let args = CLIArgs::parse();
let in_place = !args.check; let in_place = !args.check;
let include: Vec<&str> = let include: Vec<&str> =
args.include.iter().map(String::as_str).collect::<Vec<&str>>(); args.include.iter().map(String::as_str).collect::<Vec<&str>>();
let threads = args let threads =
.threads args.threads.map_or_else(num_cpus::get_physical, Into::<usize>::into);
.map_or_else(num_cpus::get_physical, |threads| threads as usize);
let verbosity = match args.quiet {
0 => Verbosity::Everything,
1 => Verbosity::NoInfo,
_ => Verbosity::NoErrors,
};
let formatted_paths = match &include[..] { let formatted_paths = match &include[..] {
&[] | &["-"] => { &[] | &["-"] => {
vec![crate::cli::stdin(args.quiet)] vec![crate::cli::format_stdin(verbosity)]
}, },
include => { include => {
let paths = crate::find::nix_files(include, &args.exclude); let paths = crate::find::nix_files(include, &args.exclude);
crate::cli::simple(paths, in_place, args.quiet, threads) crate::cli::format_paths(paths, in_place, verbosity, threads)
}, },
}; };
@ -155,18 +164,21 @@ pub fn main() -> std::io::Result<()> {
.count(); .count();
if errors > 0 { if errors > 0 {
eprintln!(); if verbosity.allows_errors() {
eprintln!( eprintln!();
"Failed! {errors} error{} found at:", eprintln!(
if errors == 1 { "" } else { "s" } "Failed! {errors} error{} found at:",
); if errors == 1 { "" } else { "s" }
for formatted_path in formatted_paths { );
if let alejandra::format::Status::Error(error) = for formatted_path in formatted_paths {
formatted_path.status if let alejandra::format::Status::Error(error) =
{ formatted_path.status
eprintln!("- {}: {error}", formatted_path.path); {
eprintln!("- {}: {error}", formatted_path.path);
}
} }
} }
std::process::exit(1); std::process::exit(1);
} }
@ -181,7 +193,7 @@ pub fn main() -> std::io::Result<()> {
.count(); .count();
if changed > 0 { if changed > 0 {
if !args.quiet { if verbosity.allows_info() {
eprintln!(); eprintln!();
eprintln!( eprintln!(
"{}! {changed} file{} {}.", "{}! {changed} file{} {}.",
@ -204,7 +216,7 @@ pub fn main() -> std::io::Result<()> {
std::process::exit(if in_place { 0 } else { 2 }); std::process::exit(if in_place { 0 } else { 2 });
} }
if !args.quiet { if verbosity.allows_info() {
eprintln!(); eprintln!();
eprintln!("Congratulations! Your code complies with the Alejandra style."); eprintln!("Congratulations! Your code complies with the Alejandra style.");
eprintln!(); eprintln!();

View file

@ -1,3 +1,4 @@
pub mod ads; mod ads;
pub mod cli; pub mod cli;
pub mod find; mod find;
mod verbosity;

View file

@ -0,0 +1,16 @@
#[derive(Clone, Copy)]
pub(crate) enum Verbosity {
Everything,
NoInfo,
NoErrors,
}
impl Verbosity {
pub(crate) fn allows_info(&self) -> bool {
matches!(self, Verbosity::Everything)
}
pub(crate) fn allows_errors(&self) -> bool {
self.allows_info() || matches!(self, Verbosity::NoInfo)
}
}