Skip to content

Commit

Permalink
Support @generated marker to skip code formatting
Browse files Browse the repository at this point in the history
`@generated` marker is used by certain tools to understand that the
file is generated, so it should be treated differently than a file
written by a human:
* linters should not be invoked on these files,
* diffs in these files are less important,
* and these files should not be reformatted.

This PR proposes builtin support for `@generated` marker.

I have not found a standard for a generated file marker, but:
* Facebook [uses `@generated` marker](https://tinyurl.com/fb-generated)
* Phabricator tool which was spawned from Facebook internal tool
  [also understands `@generated` marker](https://git.io/JnVHa)
* Cargo inserts `@generated` marker into [generated Cargo.lock files](https://git.io/JnVHP)

My personal story is that rust-protobuf project which I maintain
was broken twice because of incompatibilities/bugs in rustfmt marker handling:
[one](stepancheg/rust-protobuf#493),
[two](stepancheg/rust-protobuf#551).

While rustfmt AST markers are useful to apply to a certain AST
elements, disable whole-file-at-once all-tools-at-once text level
marker might be easier to use and more reliable for generated code.
  • Loading branch information
stepancheg committed Jun 20, 2021
1 parent 6495024 commit f78adda
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
is_macro_def: bool,
) -> Result<(), ErrorKind> {
let snippet_provider = self.parse_session.snippet_provider(module.span);

let generated_marker = concat!("@", "generated");
if snippet_provider.entire_snippet().contains(generated_marker) {
return Ok(());
}

let mut visitor = FmtVisitor::from_parse_sess(
&self.parse_session,
&self.config,
Expand Down
14 changes: 14 additions & 0 deletions tests/source/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
fn

foo

(
x: u32
) {




}

// This file is @generated
14 changes: 14 additions & 0 deletions tests/target/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
fn

foo

(
x: u32
) {




}

// This file is @generated

0 comments on commit f78adda

Please sign in to comment.