profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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 {
    /// Proto files or directories to format. `-` reads standard input.
    #[arg(required = true)]
    paths: Vec<PathBuf>,

    /// Rewrite files in place.
    #[arg(short, long, conflicts_with_all = ["check", "diff"])]
    write: bool,

    /// Exit with status 1 if any input would change.
    #[arg(short, long)]
    check: bool,

    /// Print a unified diff for each input that would change.
    #[arg(long, requires = "check")]
    diff: bool,

    /// Suppress changed-file status and the summary. Errors and requested
    /// diffs are still printed.
    #[arg(short, long)]
    quiet: bool,

    /// Number of worker threads. Directory discovery uses at most four.
    #[arg(long)]
    threads: Option<NonZeroUsize>,

    /// Read formatting policy from this TOML file instead of discovering
    /// `.profmt.toml` from the current directory.
    #[arg(long, value_name = "PATH", conflicts_with = "no_config")]
    config: Option<PathBuf>,

    /// Do not discover or load a formatting configuration.
    #[arg(long, conflicts_with = "config")]
    no_config: bool,

    #[command(flatten)]
    style: StyleOptions,
}

/// Declares a CLI value enum mirroring a library option enum, with the
/// conversion between them.
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 {
    /// Maximum line width.
    #[arg(long, value_name = "COLUMNS")]
    line_width: Option<usize>,

    /// Spaces emitted for one indentation level.
    #[arg(long, value_name = "SPACES")]
    indent_width: Option<usize>,

    /// Preferred delimiter for string literals.
    #[arg(long, value_enum)]
    quote_style: Option<QuoteStyle>,

    /// Order of the syntax, package, import and option statements that open
    /// a file.
    #[arg(long, value_enum)]
    header_order: Option<HeaderOrder>,

    /// Order of the import statements within the file header.
    #[arg(long, value_enum)]
    import_order: Option<ImportOrder>,

    /// Layout of a block with no statements.
    #[arg(long, value_enum)]
    empty_block_layout: Option<EmptyBlockLayout>,

    /// How an rpc with no options is terminated.
    #[arg(long, value_enum)]
    empty_rpc_body: Option<EmptyRpcBody>,

    /// What happens to a `;` that terminates nothing.
    #[arg(long, value_enum)]
    empty_statements: Option<EmptyStatements>,

    /// Whether block-bodied declarations are always set apart by blank lines.
    #[arg(long, value_enum)]
    declaration_spacing: Option<DeclarationSpacing>,

    /// Spacing between `//` and the text of a line comment.
    #[arg(long, value_enum)]
    comment_spacing: Option<CommentSpacing>,

    /// Whether an rpc signature may break when it does not fit.
    #[arg(long, value_enum)]
    rpc_signature_layout: Option<RpcSignatureLayout>,

    /// Whether a field or enum value option list may break when it does not
    /// fit.
    #[arg(long, value_enum)]
    field_options_layout: Option<FieldOptionsLayout>,

    /// Whether an option value may leave its statement's line when the
    /// statement does not fit.
    #[arg(long, value_enum)]
    option_value_layout: Option<OptionValueLayout>,

    /// Maximum number of consecutive blank lines kept between statements.
    #[arg(long, value_name = "LINES")]
    blank_line_limit: Option<usize>,

    /// Replace the default ignore directives with this repeatable value.
    #[arg(long = "ignore-directive", value_name = "COMMENT")]
    ignore_directives: Vec<String>,

    /// Disable all ignore directives.
    #[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(),
    };
    // Directory walking is syscall-bound; more walkers add contention while
    // file formatting continues to benefit from the full worker count.
    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);
    }
}