Skip to content

Commit

Permalink
feat(build): use prettyplease to format output (#890) (#904)
Browse files Browse the repository at this point in the history
  • Loading branch information
matze authored Feb 10, 2022
1 parent 468e422 commit d6c0fc1
Show file tree
Hide file tree
Showing 11 changed files with 8 additions and 93 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ the generated code.

```bash
$ rustup update
$ rustup component add rustfmt
$ cargo build
```

Expand Down
1 change: 0 additions & 1 deletion examples/helloworld-tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ feature.

```bash
$ rustup update
$ rustup component add rustfmt
```

## Defining the HelloWorld service
Expand Down
6 changes: 0 additions & 6 deletions examples/routeguide-tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,6 @@ Change your current directory to Tonic's repository root:
$ cd tonic
```

Tonic uses `rustfmt` to tidy up the code it generates, so we'll make sure it's installed.

```shell
$ rustup component add rustfmt
```

Run the server
```shell
$ cargo run --bin routeguide-server
Expand Down
4 changes: 2 additions & 2 deletions tonic-build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ repository = "https://github.com/hyperium/tonic"
version = "0.6.2"

[dependencies]
prettyplease = {version = "0.1"}
proc-macro2 = "1.0"
prost-build = {version = "0.9", optional = true}
quote = "1.0"
syn = "1.0"

[features]
compression = []
default = ["transport", "rustfmt", "prost"]
default = ["transport", "prost"]
prost = ["prost-build"]
rustfmt = []
transport = []

[package.metadata.docs.rs]
Expand Down
4 changes: 1 addition & 3 deletions tonic-build/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ Compiles proto files via prost and generates service stubs and proto definitione

## Features

- rustfmt: This feature enables the use of rustfmt to format the output code this makes the code readable and the error messages nice. This requires that rustfmt is installed. This is enabled by default.

Required dependencies

```toml
Expand Down Expand Up @@ -103,4 +101,4 @@ pub mod google {
}
}
```
See [the example here](https://github.com/hyperium/tonic/tree/master/examples/src/gcp)
See [the example here](https://github.com/hyperium/tonic/tree/master/examples/src/gcp)
49 changes: 0 additions & 49 deletions tonic-build/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
//! `tonic-build` compiles `proto` files via `prost` and generates service stubs
//! and proto definitiones for use with `tonic`.
//!
//! # Features
//!
//! - `rustfmt`: This feature enables the use of `rustfmt` to format the output code
//! this makes the code readable and the error messages nice. This requires that `rustfmt`
//! is installed. This is enabled by default.
//!
//! # Required dependencies
//!
//! ```toml
Expand Down Expand Up @@ -85,13 +79,6 @@ mod prost;
#[cfg_attr(docsrs, doc(cfg(feature = "prost")))]
pub use prost::{compile_protos, configure, Builder};

#[cfg(feature = "rustfmt")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustfmt")))]
use std::io::{self, Write};
#[cfg(feature = "rustfmt")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustfmt")))]
use std::process::{exit, Command};

/// Service code generation for client
pub mod client;
/// Service code generation for Server
Expand Down Expand Up @@ -217,42 +204,6 @@ fn generate_attributes<'a>(
.collect::<Vec<_>>()
}

/// Format files under the out_dir with rustfmt
#[cfg(feature = "rustfmt")]
#[cfg_attr(docsrs, doc(cfg(feature = "rustfmt")))]
pub fn fmt(out_dir: &str) {
let dir = std::fs::read_dir(out_dir).unwrap();

for entry in dir {
let file = entry.unwrap().file_name().into_string().unwrap();
if !file.ends_with(".rs") {
continue;
}
let result =
Command::new(std::env::var("RUSTFMT").unwrap_or_else(|_| "rustfmt".to_owned()))
.arg("--emit")
.arg("files")
.arg("--edition")
.arg("2018")
.arg(format!("{}/{}", out_dir, file))
.output();

match result {
Err(e) => {
eprintln!("error running rustfmt: {:?}", e);
exit(1)
}
Ok(output) => {
if !output.status.success() {
io::stdout().write_all(&output.stdout).unwrap();
io::stderr().write_all(&output.stderr).unwrap();
exit(output.status.code().unwrap_or(1))
}
}
}
}
}

// Generate a singular line of a doc comment
fn generate_doc_comment<S: AsRef<str>>(comment: S) -> TokenStream {
let mut doc_stream = TokenStream::new();
Expand Down
27 changes: 4 additions & 23 deletions tonic-build/src/prost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ pub fn configure() -> Builder {
client_attributes: Attributes::default(),
proto_path: "super".to_string(),
compile_well_known_types: false,
#[cfg(feature = "rustfmt")]
format: true,
emit_package: true,
protoc_args: Vec::new(),
include_file: None,
Expand Down Expand Up @@ -184,7 +182,8 @@ impl prost_build::ServiceGenerator for ServiceGenerator {
#clients
};

let code = format!("{}", client_service);
let ast: syn::File = syn::parse2(client_service).expect("not a valid tokenstream");
let code = prettyplease::unparse(&ast);
buf.push_str(&code);

self.clients = TokenStream::default();
Expand All @@ -197,7 +196,8 @@ impl prost_build::ServiceGenerator for ServiceGenerator {
#servers
};

let code = format!("{}", server_service);
let ast: syn::File = syn::parse2(server_service).expect("not a valid tokenstream");
let code = prettyplease::unparse(&ast);
buf.push_str(&code);

self.servers = TokenStream::default();
Expand All @@ -223,8 +223,6 @@ pub struct Builder {
pub(crate) include_file: Option<PathBuf>,

out_dir: Option<PathBuf>,
#[cfg(feature = "rustfmt")]
format: bool,
}

impl Builder {
Expand All @@ -247,13 +245,6 @@ impl Builder {
self
}

/// Enable the output to be formated by rustfmt.
#[cfg(feature = "rustfmt")]
pub fn format(mut self, run: bool) -> Self {
self.format = run;
self
}

/// Set the output directory to generate code to.
///
/// Defaults to the `OUT_DIR` environment variable.
Expand Down Expand Up @@ -397,9 +388,6 @@ impl Builder {
PathBuf::from(std::env::var("OUT_DIR").unwrap())
};

#[cfg(feature = "rustfmt")]
let format = self.format;

config.out_dir(out_dir.clone());
if let Some(path) = self.file_descriptor_set_path.as_ref() {
config.file_descriptor_set_path(path);
Expand Down Expand Up @@ -428,13 +416,6 @@ impl Builder {

config.compile_protos(protos, includes)?;

#[cfg(feature = "rustfmt")]
{
if format {
super::fmt(out_dir.to_str().expect("Expected utf8 out_dir"));
}
}

Ok(())
}
}
3 changes: 1 addition & 2 deletions tonic-health/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ repository = "https://github.com/hyperium/tonic"
version = "0.5.0"

[features]
default = ["transport", "rustfmt"]
rustfmt = ["tonic-build/rustfmt"]
default = ["transport"]
transport = ["tonic/transport", "tonic-build/transport"]

[dependencies]
Expand Down
1 change: 0 additions & 1 deletion tonic-health/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.file_descriptor_set_path(grpc_health_v1_descriptor_set_path)
.build_server(true)
.build_client(true)
.format(false)
.compile(&["proto/health.proto"], &["proto/"])?;

Ok(())
Expand Down
4 changes: 0 additions & 4 deletions tonic-reflection/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ readme = "README.md"
repository = "https://github.com/hyperium/tonic"
version = "0.3.0"

[features]
default = ["rustfmt"]
rustfmt = ["tonic-build/rustfmt"]

[dependencies]
bytes = "1.0"
prost = "0.9"
Expand Down
1 change: 0 additions & 1 deletion tonic-reflection/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.build_server(true)
.build_client(true) // Client is only used for tests
.format(true)
.compile(&["proto/reflection.proto"], &["proto/"])?;

Ok(())
Expand Down

0 comments on commit d6c0fc1

Please sign in to comment.