• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Code Formatting
2
3`bindgen` uses `rustfmt` to format the emitted bindings. This section describes
4how to adjust the `rustfmt` behavior when being used from `bindgen`.
5
6## Passing a `rustfmt.toml` configuration file
7
8`rustfmt` should automatically use any `rustfmt.toml` file that is present in
9the directory from where `bindgen` will be run. If you want to use a
10configuration file that has a different name or that is in a different
11directory you can use the `--rustfmt-configuration-file` flag or the
12[`Builder::rustfmt_configuration_file`](https://docs.rs/bindgen/latest/bindgen/struct.Builder.html#method.rustfmt_configuration_file)
13method.
14
15## Using a nightly release of `rustfmt`
16
17If the `rustfmt` command does not correspond to a nightly release of `rustfmt`
18but you have `rustup` available, you can use `nightly` by following these
19steps:
20
21### When using `bindgen` as a CLI application
22
23Use `rustup run` to run `bindgen`:
24
25```bash
26$ rustup run nightly bindgen [ARGS]
27```
28
29### When using `bindgen` as a library
30
31Take the output of the following command:
32```bash
33$ rustup which rustfmt --toolchain=nightly
34```
35and pass it to
36[`Builder::with_rustfmt`](https://docs.rs/bindgen/latest/bindgen/struct.Builder.html#method.with_rustfmt):
37
38```rust,ignore
39use bindgen::Builder;
40use std::process::Command;
41
42fn main() {
43    let output = Command::new("rustup")
44        .args(["which", "rustfmt", "--toolchain", "nightly"])
45        .output()
46        .expect("Could not spawn `rustup` command");
47
48    assert!(
49        output.status.success(),
50        "Unsuccessful status code when running `rustup`: {:?}",
51        output
52    );
53
54    let rustfmt_path =
55        String::from_utf8(output.stdout).expect("The `rustfmt` path is not valid `utf-8`");
56
57    let bindings = Builder::default()
58        .header("path/to/input.h")
59        .with_rustfmt(rustfmt_path)
60        .generate()
61        .expect("Could not generate bindings");
62
63    bindings
64        .write_to_file("path/to/output.rs")
65        .expect("Could not write bindings");
66}
67```
68
69These two methods also apply to any other toolchain available in your system.
70