mod config;
mod files;
use std::ffi::OsStr;
use std::io::{Read, Write};
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use anyhow::{Context, Result, bail};
use clap::{Args, Parser, ValueEnum};
use rayon::prelude::*;
const MAX_DISCOVERY_THREADS: usize = 4;
#[derive(Parser, Debug)]
#[command(name = "profmt", about = "Format Protocol Buffers definitions", version)]
struct Options {
#[arg(required = true)]
paths: Vec<PathBuf>,
#[arg(short, long, conflicts_with_all = ["check", "diff"])]
write: bool,
#[arg(short, long)]
check: bool,
#[arg(long, requires = "check")]
diff: bool,
#[arg(short, long)]
quiet: bool,
#[arg(long)]
threads: Option<NonZeroUsize>,
#[arg(long, value_name = "PATH", conflicts_with = "no_config")]
config: Option<PathBuf>,
#[arg(long, conflicts_with = "config")]
no_config: bool,
#[command(flatten)]
style: StyleOptions,
}
macro_rules! cli_enum {
($name:ident { $($variant:ident),+ $(,)? }) => {
#[derive(Clone, Copy, Debug, ValueEnum)]
enum $name {
$($variant),+
}
impl From<$name> for profmt::$name {
fn from(value: $name) -> Self {
match value {
$($name::$variant => profmt::$name::$variant),+
}
}
}
};
}
cli_enum!(QuoteStyle {
Single,
Double,
Preserve
});
cli_enum!(HeaderOrder {
Preserve,
PackageFirst,
ImportsFirst
});
cli_enum!(ImportOrder { Preserve, Sorted });
cli_enum!(EmptyBlockLayout { Compact, Expanded });
cli_enum!(EmptyRpcBody {
Preserve,
Semicolon,
Braces
});
cli_enum!(EmptyStatements { Remove, Preserve });
cli_enum!(DeclarationSpacing { Preserve, Separated });
cli_enum!(CommentSpacing { Preserve, Normalized });
cli_enum!(RpcSignatureLayout {
SingleLine,
BreakBeforeReturns
});
cli_enum!(FieldOptionsLayout { SingleLine, OnePerLine });
cli_enum!(OptionValueLayout { SingleLine, NewLine });
#[derive(Args, Clone, Debug, Default)]
struct StyleOptions {
#[arg(long, value_name = "COLUMNS")]
line_width: Option<usize>,
#[arg(long, value_name = "SPACES")]
indent_width: Option<usize>,
#[arg(long, value_enum)]
quote_style: Option<QuoteStyle>,
#[arg(long, value_enum)]
header_order: Option<HeaderOrder>,
#[arg(long, value_enum)]
import_order: Option<ImportOrder>,
#[arg(long, value_enum)]
empty_block_layout: Option<EmptyBlockLayout>,
#[arg(long, value_enum)]
empty_rpc_body: Option<EmptyRpcBody>,
#[arg(long, value_enum)]
empty_statements: Option<EmptyStatements>,
#[arg(long, value_enum)]
declaration_spacing: Option<DeclarationSpacing>,
#[arg(long, value_enum)]
comment_spacing: Option<CommentSpacing>,
#[arg(long, value_enum)]
rpc_signature_layout: Option<RpcSignatureLayout>,
#[arg(long, value_enum)]
field_options_layout: Option<FieldOptionsLayout>,
#[arg(long, value_enum)]
option_value_layout: Option<OptionValueLayout>,
#[arg(long, value_name = "LINES")]
blank_line_limit: Option<usize>,
#[arg(long = "ignore-directive", value_name = "COMMENT")]
ignore_directives: Vec<String>,
#[arg(long, conflicts_with = "ignore_directives")]
no_ignore_directives: bool,
}
impl StyleOptions {
fn apply(self, options: &mut profmt::FormatOptions) -> Result<()> {
set_if_some(&mut options.line_width, self.line_width);
set_if_some(&mut options.indent_width, self.indent_width);
set_if_some(&mut options.quote_style, self.quote_style.map(Into::into));
set_if_some(&mut options.header_order, self.header_order.map(Into::into));
set_if_some(&mut options.import_order, self.import_order.map(Into::into));
set_if_some(&mut options.empty_block_layout, self.empty_block_layout.map(Into::into));
set_if_some(&mut options.empty_rpc_body, self.empty_rpc_body.map(Into::into));
set_if_some(&mut options.empty_statements, self.empty_statements.map(Into::into));
set_if_some(
&mut options.declaration_spacing,
self.declaration_spacing.map(Into::into),
);
set_if_some(&mut options.comment_spacing, self.comment_spacing.map(Into::into));
set_if_some(
&mut options.rpc_signature_layout,
self.rpc_signature_layout.map(Into::into),
);
set_if_some(
&mut options.field_options_layout,
self.field_options_layout.map(Into::into),
);
set_if_some(
&mut options.option_value_layout,
self.option_value_layout.map(Into::into),
);
set_if_some(&mut options.blank_line_limit, self.blank_line_limit);
if self.no_ignore_directives {
options.ignore_directives.clear();
} else if !self.ignore_directives.is_empty() {
options.ignore_directives = self.ignore_directives;
}
options.validate()?;
Ok(())
}
}
fn set_if_some<T>(target: &mut T, value: Option<T>) {
if let Some(value) = value {
*target = value;
}
}
#[derive(Clone, Copy)]
enum Mode {
Check { diff: bool },
Write,
}
enum Outcome {
Unchanged,
Changed { diff: Option<String> },
Failed(String),
}
pub fn run() -> Result<ExitCode> {
run_with(Options::parse())
}
fn run_with(options: Options) -> Result<ExitCode> {
if options.quiet && !options.check && !options.write {
bail!("--quiet requires --check or --write");
}
let mut format_options = config::load(options.config.as_deref(), options.no_config)?;
options.style.clone().apply(&mut format_options)?;
let stdin = options
.paths
.iter()
.filter(|path| path.as_os_str() == OsStr::new("-"))
.count();
if stdin > 0 {
if options.paths.len() != 1 {
bail!("standard input (`-`) cannot be combined with file paths");
}
if options.write {
bail!("--write cannot be used with standard input");
}
return run_stdin(&options, &format_options);
}
let threads = match options.threads {
Some(threads) => threads.get(),
None => std::thread::available_parallelism()
.context("determine available formatter parallelism")?
.get(),
};
let paths = files::discover(&options.paths, threads.min(MAX_DISCOVERY_THREADS))?;
if !options.check && !options.write {
return print_one(&paths, &format_options);
}
let mode = if options.write {
Mode::Write
} else {
Mode::Check { diff: options.diff }
};
let outcomes: Vec<_> = if paths.len() <= 1 || threads == 1 {
paths
.iter()
.map(|path| process_file(path, mode, &format_options))
.collect()
} else {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build()
.context("create formatter thread pool")?;
pool.install(|| {
paths
.par_iter()
.map(|path| process_file(path, mode, &format_options))
.collect()
})
};
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
let mut stderr = std::io::BufWriter::new(std::io::stderr().lock());
let (mut unchanged, mut changed, mut failed) = (0usize, 0usize, 0usize);
for (path, outcome) in paths.iter().zip(outcomes) {
match outcome {
Outcome::Unchanged => unchanged += 1,
Outcome::Changed { diff } => {
changed += 1;
if options.check && !options.quiet {
writeln!(stdout, "changed: {}", path.display())?;
}
if let Some(diff) = diff {
stdout.write_all(diff.as_bytes())?;
}
}
Outcome::Failed(error) => {
failed += 1;
writeln!(stderr, "failed: {}: {error}", path.display())?;
}
}
}
if !options.quiet {
writeln!(
stderr,
"profmt: {unchanged} unchanged, {changed} changed, {failed} failed ({} total)",
paths.len()
)?;
}
stdout.flush()?;
stderr.flush()?;
Ok(exit_status(options.check, changed, failed))
}
fn run_stdin(options: &Options, format_options: &profmt::FormatOptions) -> Result<ExitCode> {
let mut source = Vec::new();
std::io::stdin()
.read_to_end(&mut source)
.context("read standard input")?;
let formatted = profmt::format_with_options(&source, format_options)?;
let changed = formatted.as_bytes() != source;
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
let mut stderr = std::io::BufWriter::new(std::io::stderr().lock());
if options.check {
if changed && !options.quiet {
writeln!(stdout, "changed: stdin")?;
}
if changed && options.diff {
stdout.write_all(unified_diff(&source, &formatted, Path::new("stdin")).as_bytes())?;
}
if !options.quiet {
let unchanged = usize::from(!changed);
writeln!(
stderr,
"profmt: {unchanged} unchanged, {} changed, 0 failed (1 total)",
usize::from(changed)
)?;
}
} else {
stdout.write_all(formatted.as_bytes())?;
}
stdout.flush()?;
stderr.flush()?;
Ok(if options.check && changed {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
})
}
fn print_one(paths: &[PathBuf], options: &profmt::FormatOptions) -> Result<ExitCode> {
let [path] = paths else {
bail!(
"printing requires exactly one proto file; use --write or --check for {} files",
paths.len()
);
};
let source = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
let formatted =
profmt::format_with_options(&source, options).with_context(|| format!("format {}", path.display()))?;
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
stdout.write_all(formatted.as_bytes())?;
stdout.flush()?;
Ok(ExitCode::SUCCESS)
}
fn process_file(path: &Path, mode: Mode, options: &profmt::FormatOptions) -> Outcome {
let result = (|| -> Result<Outcome> {
let source = std::fs::read(path).with_context(|| format!("read: {}", path.display()))?;
if matches!(mode, Mode::Check { diff: false }) {
return Ok(if profmt::is_formatted_with_options(&source, options)? {
Outcome::Unchanged
} else {
Outcome::Changed { diff: None }
});
}
let formatted = profmt::format_with_options(&source, options)?;
if formatted.as_bytes() == source {
return Ok(Outcome::Unchanged);
}
match mode {
Mode::Check { diff } => Ok(Outcome::Changed {
diff: diff.then(|| unified_diff(&source, &formatted, path)),
}),
Mode::Write => {
files::replace(path, &source, formatted.as_bytes())?;
Ok(Outcome::Changed { diff: None })
}
}
})();
result.unwrap_or_else(|error| Outcome::Failed(format!("{error:#}")))
}
fn unified_diff(before: &[u8], after: &str, path: &Path) -> String {
let before = std::str::from_utf8(before).expect("formatting validates UTF-8");
similar::TextDiff::from_lines(before, after)
.unified_diff()
.context_radius(2)
.header(&format!("a/{}", path.display()), &format!("b/{}", path.display()))
.to_string()
}
fn exit_status(check: bool, changed: usize, failed: usize) -> ExitCode {
if failed > 0 {
ExitCode::from(2)
} else if check && changed > 0 {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn style_flags_override_defaults() {
let style = StyleOptions {
line_width: Some(100),
quote_style: Some(QuoteStyle::Double),
empty_rpc_body: Some(EmptyRpcBody::Semicolon),
no_ignore_directives: true,
..StyleOptions::default()
};
let mut options = profmt::FormatOptions::default();
style.apply(&mut options).expect("valid options");
assert_eq!(options.line_width, 100);
assert_eq!(options.quote_style, profmt::QuoteStyle::Double);
assert_eq!(options.empty_rpc_body, profmt::EmptyRpcBody::Semicolon);
assert!(options.ignore_directives.is_empty());
}
#[test]
fn exit_status_prioritises_failures() {
assert_eq!(exit_status(true, 1, 1), ExitCode::from(2));
assert_eq!(exit_status(true, 1, 0), ExitCode::from(1));
assert_eq!(exit_status(true, 0, 0), ExitCode::SUCCESS);
assert_eq!(exit_status(false, 1, 0), ExitCode::SUCCESS);
}
}