├── .github ├── dependabot.yml └── workflows │ └── rust.yml ├── .gitignore ├── CHANGELOG.adoc ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── release.toml └── src ├── config └── mod.rs └── lib.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Dependabot configuration file 3 | # 4 | 5 | version: 2 6 | updates: 7 | - package-ecosystem: "cargo" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Configuration for GitHub-based CI, based on the stock GitHub Rust config. 3 | # 4 | name: Build 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | check-style: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: actions-rs/toolchain@v1 18 | with: 19 | toolchain: stable 20 | components: rustfmt 21 | - name: Report cargo version 22 | run: cargo --version 23 | - name: Report rustfmt version 24 | run: cargo fmt -- --version 25 | - name: Check style 26 | run: cargo fmt -- --check 27 | 28 | build-and-test: 29 | runs-on: ${{ matrix.os }} 30 | strategy: 31 | matrix: 32 | os: [ ubuntu-latest, windows-latest, macos-latest ] 33 | steps: 34 | - uses: actions/checkout@v2 35 | - name: Install nightly 36 | uses: actions-rs/toolchain@v1 37 | with: 38 | toolchain: nightly 39 | components: rustfmt 40 | default: false 41 | - name: Install stable 42 | uses: actions-rs/toolchain@v1 43 | with: 44 | toolchain: stable 45 | components: rustfmt 46 | default: true 47 | - name: Build 48 | run: cargo build --tests --verbose 49 | - name: Run tests 50 | run: cargo test --verbose 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /CHANGELOG.adoc: -------------------------------------------------------------------------------- 1 | :showtitle: 2 | :toc: left 3 | :icons: font 4 | :toclevels: 1 5 | 6 | = Rustfmt-wrapper Changelog 7 | 8 | // WARNING: This file is modified programmatically by `cargo release` as 9 | // configured in release.toml. DO NOT change the format of the headers or the 10 | // list of raw commits. 11 | 12 | // cargo-release: next header goes here (do not change this line) 13 | 14 | == Unreleased changes (release date TBD) 15 | 16 | https://github.com/oxidecomputer/rustfmt-wrapper/compare/v0.2.1\...HEAD[Full list of commits] 17 | 18 | == 0.2.1 (released 2023-10-23) 19 | 20 | https://github.com/oxidecomputer/rustfmt-wrapper/compare/v0.2.0\...v0.2.1[Full list of commits] 21 | 22 | * Update dependencies 23 | 24 | == 0.2.0 (released 2022-06-21) 25 | 26 | https://github.com/oxidecomputer/rustfmt-wrapper/compare/v0.1.0\...v0.2.0[Full list of commits] 27 | 28 | * Added `rustfmt_config()` for greater flexibility (#1) 29 | * Imported all stable and unstable `rustfmt` options (#1) 30 | 31 | == 0.1.0 (released 2021-10-08) 32 | 33 | First published version 34 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aho-corasick" 7 | version = "1.0.1" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "67fc08ce920c31afb70f013dcce1bfc3a3195de6a228474e45e1f145b36f8d04" 10 | dependencies = [ 11 | "memchr", 12 | ] 13 | 14 | [[package]] 15 | name = "bitflags" 16 | version = "1.3.2" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 19 | 20 | [[package]] 21 | name = "bitflags" 22 | version = "2.4.1" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" 25 | 26 | [[package]] 27 | name = "cfg-if" 28 | version = "1.0.0" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 31 | 32 | [[package]] 33 | name = "equivalent" 34 | version = "1.0.0" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" 37 | 38 | [[package]] 39 | name = "errno" 40 | version = "0.3.8" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" 43 | dependencies = [ 44 | "libc", 45 | "windows-sys", 46 | ] 47 | 48 | [[package]] 49 | name = "fastrand" 50 | version = "2.0.0" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" 53 | 54 | [[package]] 55 | name = "hashbrown" 56 | version = "0.14.0" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" 59 | 60 | [[package]] 61 | name = "home" 62 | version = "0.5.3" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654" 65 | dependencies = [ 66 | "winapi", 67 | ] 68 | 69 | [[package]] 70 | name = "indexmap" 71 | version = "2.0.0" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" 74 | dependencies = [ 75 | "equivalent", 76 | "hashbrown", 77 | ] 78 | 79 | [[package]] 80 | name = "libc" 81 | version = "0.2.151" 82 | source = "registry+https://github.com/rust-lang/crates.io-index" 83 | checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" 84 | 85 | [[package]] 86 | name = "linux-raw-sys" 87 | version = "0.4.12" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" 90 | 91 | [[package]] 92 | name = "memchr" 93 | version = "2.5.0" 94 | source = "registry+https://github.com/rust-lang/crates.io-index" 95 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 96 | 97 | [[package]] 98 | name = "newline-converter" 99 | version = "0.3.0" 100 | source = "registry+https://github.com/rust-lang/crates.io-index" 101 | checksum = "47b6b097ecb1cbfed438542d16e84fd7ad9b0c76c8a65b7f9039212a3d14dc7f" 102 | dependencies = [ 103 | "unicode-segmentation", 104 | ] 105 | 106 | [[package]] 107 | name = "once_cell" 108 | version = "1.17.1" 109 | source = "registry+https://github.com/rust-lang/crates.io-index" 110 | checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" 111 | 112 | [[package]] 113 | name = "proc-macro2" 114 | version = "1.0.76" 115 | source = "registry+https://github.com/rust-lang/crates.io-index" 116 | checksum = "95fc56cda0b5c3325f5fbbd7ff9fda9e02bb00bb3dac51252d2f1bfa1cb8cc8c" 117 | dependencies = [ 118 | "unicode-ident", 119 | ] 120 | 121 | [[package]] 122 | name = "quote" 123 | version = "1.0.35" 124 | source = "registry+https://github.com/rust-lang/crates.io-index" 125 | checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" 126 | dependencies = [ 127 | "proc-macro2", 128 | ] 129 | 130 | [[package]] 131 | name = "redox_syscall" 132 | version = "0.4.1" 133 | source = "registry+https://github.com/rust-lang/crates.io-index" 134 | checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" 135 | dependencies = [ 136 | "bitflags 1.3.2", 137 | ] 138 | 139 | [[package]] 140 | name = "regex" 141 | version = "1.8.3" 142 | source = "registry+https://github.com/rust-lang/crates.io-index" 143 | checksum = "81ca098a9821bd52d6b24fd8b10bd081f47d39c22778cafaa75a2857a62c6390" 144 | dependencies = [ 145 | "aho-corasick", 146 | "memchr", 147 | "regex-syntax", 148 | ] 149 | 150 | [[package]] 151 | name = "regex-syntax" 152 | version = "0.7.2" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" 155 | 156 | [[package]] 157 | name = "rustfmt-wrapper" 158 | version = "0.2.1" 159 | dependencies = [ 160 | "newline-converter", 161 | "quote", 162 | "serde", 163 | "tempfile", 164 | "thiserror", 165 | "toml", 166 | "toolchain_find", 167 | ] 168 | 169 | [[package]] 170 | name = "rustix" 171 | version = "0.38.28" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" 174 | dependencies = [ 175 | "bitflags 2.4.1", 176 | "errno", 177 | "libc", 178 | "linux-raw-sys", 179 | "windows-sys", 180 | ] 181 | 182 | [[package]] 183 | name = "same-file" 184 | version = "1.0.6" 185 | source = "registry+https://github.com/rust-lang/crates.io-index" 186 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 187 | dependencies = [ 188 | "winapi-util", 189 | ] 190 | 191 | [[package]] 192 | name = "semver" 193 | version = "1.0.17" 194 | source = "registry+https://github.com/rust-lang/crates.io-index" 195 | checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" 196 | 197 | [[package]] 198 | name = "serde" 199 | version = "1.0.193" 200 | source = "registry+https://github.com/rust-lang/crates.io-index" 201 | checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" 202 | dependencies = [ 203 | "serde_derive", 204 | ] 205 | 206 | [[package]] 207 | name = "serde_derive" 208 | version = "1.0.193" 209 | source = "registry+https://github.com/rust-lang/crates.io-index" 210 | checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" 211 | dependencies = [ 212 | "proc-macro2", 213 | "quote", 214 | "syn", 215 | ] 216 | 217 | [[package]] 218 | name = "serde_spanned" 219 | version = "0.6.4" 220 | source = "registry+https://github.com/rust-lang/crates.io-index" 221 | checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" 222 | dependencies = [ 223 | "serde", 224 | ] 225 | 226 | [[package]] 227 | name = "syn" 228 | version = "2.0.28" 229 | source = "registry+https://github.com/rust-lang/crates.io-index" 230 | checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567" 231 | dependencies = [ 232 | "proc-macro2", 233 | "quote", 234 | "unicode-ident", 235 | ] 236 | 237 | [[package]] 238 | name = "tempfile" 239 | version = "3.9.0" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" 242 | dependencies = [ 243 | "cfg-if", 244 | "fastrand", 245 | "redox_syscall", 246 | "rustix", 247 | "windows-sys", 248 | ] 249 | 250 | [[package]] 251 | name = "thiserror" 252 | version = "1.0.55" 253 | source = "registry+https://github.com/rust-lang/crates.io-index" 254 | checksum = "6e3de26b0965292219b4287ff031fcba86837900fe9cd2b34ea8ad893c0953d2" 255 | dependencies = [ 256 | "thiserror-impl", 257 | ] 258 | 259 | [[package]] 260 | name = "thiserror-impl" 261 | version = "1.0.55" 262 | source = "registry+https://github.com/rust-lang/crates.io-index" 263 | checksum = "268026685b2be38d7103e9e507c938a1fcb3d7e6eb15e87870b617bf37b6d581" 264 | dependencies = [ 265 | "proc-macro2", 266 | "quote", 267 | "syn", 268 | ] 269 | 270 | [[package]] 271 | name = "toml" 272 | version = "0.8.8" 273 | source = "registry+https://github.com/rust-lang/crates.io-index" 274 | checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" 275 | dependencies = [ 276 | "serde", 277 | "serde_spanned", 278 | "toml_datetime", 279 | "toml_edit", 280 | ] 281 | 282 | [[package]] 283 | name = "toml_datetime" 284 | version = "0.6.5" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" 287 | dependencies = [ 288 | "serde", 289 | ] 290 | 291 | [[package]] 292 | name = "toml_edit" 293 | version = "0.21.0" 294 | source = "registry+https://github.com/rust-lang/crates.io-index" 295 | checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" 296 | dependencies = [ 297 | "indexmap", 298 | "serde", 299 | "serde_spanned", 300 | "toml_datetime", 301 | "winnow", 302 | ] 303 | 304 | [[package]] 305 | name = "toolchain_find" 306 | version = "0.4.0" 307 | source = "registry+https://github.com/rust-lang/crates.io-index" 308 | checksum = "ebc8c9a7f0a2966e1acdaf0461023d0b01471eeead645370cf4c3f5cff153f2a" 309 | dependencies = [ 310 | "home", 311 | "once_cell", 312 | "regex", 313 | "semver", 314 | "walkdir", 315 | ] 316 | 317 | [[package]] 318 | name = "unicode-ident" 319 | version = "1.0.1" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" 322 | 323 | [[package]] 324 | name = "unicode-segmentation" 325 | version = "1.10.0" 326 | source = "registry+https://github.com/rust-lang/crates.io-index" 327 | checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a" 328 | 329 | [[package]] 330 | name = "walkdir" 331 | version = "2.3.2" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" 334 | dependencies = [ 335 | "same-file", 336 | "winapi", 337 | "winapi-util", 338 | ] 339 | 340 | [[package]] 341 | name = "winapi" 342 | version = "0.3.9" 343 | source = "registry+https://github.com/rust-lang/crates.io-index" 344 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 345 | dependencies = [ 346 | "winapi-i686-pc-windows-gnu", 347 | "winapi-x86_64-pc-windows-gnu", 348 | ] 349 | 350 | [[package]] 351 | name = "winapi-i686-pc-windows-gnu" 352 | version = "0.4.0" 353 | source = "registry+https://github.com/rust-lang/crates.io-index" 354 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 355 | 356 | [[package]] 357 | name = "winapi-util" 358 | version = "0.1.5" 359 | source = "registry+https://github.com/rust-lang/crates.io-index" 360 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 361 | dependencies = [ 362 | "winapi", 363 | ] 364 | 365 | [[package]] 366 | name = "winapi-x86_64-pc-windows-gnu" 367 | version = "0.4.0" 368 | source = "registry+https://github.com/rust-lang/crates.io-index" 369 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 370 | 371 | [[package]] 372 | name = "windows-sys" 373 | version = "0.52.0" 374 | source = "registry+https://github.com/rust-lang/crates.io-index" 375 | checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" 376 | dependencies = [ 377 | "windows-targets", 378 | ] 379 | 380 | [[package]] 381 | name = "windows-targets" 382 | version = "0.52.0" 383 | source = "registry+https://github.com/rust-lang/crates.io-index" 384 | checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" 385 | dependencies = [ 386 | "windows_aarch64_gnullvm", 387 | "windows_aarch64_msvc", 388 | "windows_i686_gnu", 389 | "windows_i686_msvc", 390 | "windows_x86_64_gnu", 391 | "windows_x86_64_gnullvm", 392 | "windows_x86_64_msvc", 393 | ] 394 | 395 | [[package]] 396 | name = "windows_aarch64_gnullvm" 397 | version = "0.52.0" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" 400 | 401 | [[package]] 402 | name = "windows_aarch64_msvc" 403 | version = "0.52.0" 404 | source = "registry+https://github.com/rust-lang/crates.io-index" 405 | checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" 406 | 407 | [[package]] 408 | name = "windows_i686_gnu" 409 | version = "0.52.0" 410 | source = "registry+https://github.com/rust-lang/crates.io-index" 411 | checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" 412 | 413 | [[package]] 414 | name = "windows_i686_msvc" 415 | version = "0.52.0" 416 | source = "registry+https://github.com/rust-lang/crates.io-index" 417 | checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" 418 | 419 | [[package]] 420 | name = "windows_x86_64_gnu" 421 | version = "0.52.0" 422 | source = "registry+https://github.com/rust-lang/crates.io-index" 423 | checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" 424 | 425 | [[package]] 426 | name = "windows_x86_64_gnullvm" 427 | version = "0.52.0" 428 | source = "registry+https://github.com/rust-lang/crates.io-index" 429 | checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" 430 | 431 | [[package]] 432 | name = "windows_x86_64_msvc" 433 | version = "0.52.0" 434 | source = "registry+https://github.com/rust-lang/crates.io-index" 435 | checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" 436 | 437 | [[package]] 438 | name = "winnow" 439 | version = "0.5.15" 440 | source = "registry+https://github.com/rust-lang/crates.io-index" 441 | checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" 442 | dependencies = [ 443 | "memchr", 444 | ] 445 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustfmt-wrapper" 3 | version = "0.2.1" 4 | authors = ["Adam H. Leventhal "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | description = "Library wrapper around rustfmt for use by code generators" 8 | repository = "https://github.com/oxidecomputer/rustfmt-wrapper" 9 | readme = "README.md" 10 | keywords = ["rustfmt"] 11 | categories = ["development-tools", 12 | "development-tools::procedural-macro-helpers"] 13 | 14 | [dependencies] 15 | serde = { version = "1", features = ["derive"] } 16 | tempfile = "3.9.0" 17 | thiserror = "1.0.55" 18 | toml = "0.8.8" 19 | toolchain_find = "0.4.0" 20 | 21 | [dev-dependencies] 22 | quote = "1.0.35" 23 | newline-converter = "0.3.0" 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rustfmt-wrapper 2 | 3 | Rust makes it easy to generate more Rust code--for macros, builders, whatever. 4 | It's nice to format that code to be a little easier on the eyes. While 5 | `rustfmt` does a pretty good job, it does a pretty good job as a command and 6 | isn't usable as a library. This is a probably-too-simple wrapper library. 7 | 8 | It's pretty simple to use and mixes well with `quote!`: 9 | 10 | ```rust 11 | let codegen = quote::quote!{ struct Foo { bar: String } }; 12 | let formatted: String = rustfmt_wrapper::rustfmt(codegen).unwrap(); 13 | ``` 14 | 15 | If you need more control over the **vast** array of [`rustfmt` configuration 16 | options](https://rust-lang.github.io/rustfmt), you can use the second form: 17 | 18 | ```rust 19 | let codegen = quote::quote!{ 20 | async fn go() { 21 | let _ = Client::new().operation_id().send().await?; 22 | } 23 | }; 24 | let config = Config { 25 | max_width: Some(45), 26 | ..Default::default() 27 | }; 28 | 29 | let narrow_formatted = rustfmt_config(config, codegen).unwrap(); 30 | ``` 31 | 32 | Note that in order to use unstable configuration options, you will need to have 33 | a the nightly version of `rustfmt` installed. 34 | 35 | --- 36 | 37 | Thanks to David Tolnay for so many tools including 38 | [`cargo-expand`](https://github.com/dtolnay/cargo-expand) from which this 39 | borrows. -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | # This file is used by cargo-release. 2 | 3 | # Update the change log to reflect the new release and set us up for the next release. 4 | pre-release-replacements = [ 5 | # First, replace the current "Unreleased changes" header with one reflecting the new release version and date. 6 | {file="CHANGELOG.adoc", search="Unreleased changes \\(release date TBD\\)", replace="{{version}} (released {{date}})", exactly=1}, 7 | # Update the link to the list of raw commits in the formerly "Unreleased changes" section. It should end at the tag for the newly-released version. 8 | {file="CHANGELOG.adoc", search="\\\\.\\.\\.HEAD", replace="\\...{{tag_name}}", exactly=1}, 9 | # Next, append a new "Unreleased changes" header beneath the sentinel line. 10 | {file="CHANGELOG.adoc", search="// cargo-release: next header goes here \\(do not change this line\\)", replace="// cargo-release: next header goes here (do not change this line)\n\n== Unreleased changes (release date TBD)\n\nhttps://github.com/oxidecomputer/rustfmt-wrapper/compare/{{tag_name}}\\...HEAD[Full list of commits]", exactly=1}, 11 | ] 12 | 13 | pre-release-commit-message = "release {{crate_name}} {{version}}" 14 | tag-message = "release {{crate_name}} {{version}}" 15 | tag-prefix = "" 16 | push = false 17 | -------------------------------------------------------------------------------- /src/config/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Oxide Computer Company 2 | 3 | use serde::Serialize; 4 | 5 | // Process the configuration options lifted from the rustfmt repo. Note that 6 | // the default value is ignored, but left in to simplify updates. 7 | macro_rules! create_config { 8 | ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => { 9 | /// `rustfmt` configuration. 10 | /// 11 | /// See the [`rustfmt` documentation](https://rust-lang.github.io/rustfmt) 12 | /// for the descriptions of these stable and non-stable options. 13 | #[derive(Serialize, Default)] 14 | pub struct Config { 15 | $( 16 | $( 17 | #[doc = $dstring] 18 | )* 19 | #[serde(skip_serializing_if = "Option::is_none")] 20 | pub $i: Option<$ty>, 21 | )* 22 | } 23 | 24 | impl Config { 25 | pub(crate) fn unstable(&self) -> bool { 26 | false 27 | $( 28 | // Not stable and explicitly set. 29 | || (!$stb && self.$i.is_some()) 30 | )* 31 | } 32 | 33 | pub(crate) fn list_unstable(&self) -> String { 34 | let mut list = Vec::new(); 35 | $( 36 | if !$stb && self.$i.is_some() { 37 | list.push(stringify!($i)); 38 | } 39 | )* 40 | list.join(", ") 41 | } 42 | } 43 | }; 44 | } 45 | 46 | // Per https://github.com/rust-lang/rustfmt/blob/master/src/config/mod.rs 47 | // ... skipping the section titled "Not user-facing" and "Control options". 48 | // 49 | // This macro defines configuration options used in rustfmt. Each option 50 | // is defined as follows: 51 | // 52 | // `name: value type, default value, is stable, description;` 53 | create_config! { 54 | // Fundamental stuff 55 | max_width: usize, 100, true, "Maximum width of each line"; 56 | hard_tabs: bool, false, true, "Use tab characters for indentation, spaces for alignment"; 57 | tab_spaces: usize, 4, true, "Number of spaces per tab"; 58 | newline_style: NewlineStyle, NewlineStyle::Auto, true, "Unix or Windows line endings"; 59 | indent_style: IndentStyle, IndentStyle::Block, false, "How do we indent expressions or items"; 60 | 61 | // Width Heuristics 62 | use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different \ 63 | formatting for items and expressions if they satisfy a heuristic notion of 'small'"; 64 | fn_call_width: usize, 60, true, "Maximum width of the args of a function call before \ 65 | falling back to vertical formatting."; 66 | attr_fn_like_width: usize, 70, true, "Maximum width of the args of a function-like \ 67 | attributes before falling back to vertical formatting."; 68 | struct_lit_width: usize, 18, true, "Maximum width in the body of a struct lit before \ 69 | falling back to vertical formatting."; 70 | struct_variant_width: usize, 35, true, "Maximum width in the body of a struct variant before \ 71 | falling back to vertical formatting."; 72 | array_width: usize, 60, true, "Maximum width of an array literal before falling \ 73 | back to vertical formatting."; 74 | chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line."; 75 | single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \ 76 | expressions. A value of zero means always break if-else expressions."; 77 | 78 | // Comments. macros, and strings 79 | wrap_comments: bool, false, false, "Break comments to fit on the line"; 80 | format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments."; 81 | doc_comment_code_block_width: usize, 100, false, "Maximum width for code snippets in doc \ 82 | comments. No effect unless format_code_in_doc_comments = true"; 83 | comment_width: usize, 80, false, 84 | "Maximum length of comments. No effect unless wrap_comments = true"; 85 | normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible"; 86 | normalize_doc_attributes: bool, false, false, "Normalize doc attributes as doc comments"; 87 | format_strings: bool, false, false, "Format string literals where necessary"; 88 | format_macro_matchers: bool, false, false, 89 | "Format the metavariable matching patterns in macros"; 90 | format_macro_bodies: bool, true, false, "Format the bodies of macros"; 91 | hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, 92 | "Format hexadecimal integer literals"; 93 | 94 | // Single line expressions and items 95 | empty_item_single_line: bool, true, false, 96 | "Put empty-body functions and impls on a single line"; 97 | struct_lit_single_line: bool, true, false, 98 | "Put small struct literals on a single line"; 99 | fn_single_line: bool, false, false, "Put single-expression functions on a single line"; 100 | where_single_line: bool, false, false, "Force where-clauses to be on a single line"; 101 | 102 | // Imports 103 | imports_indent: IndentStyle, IndentStyle::Block, false, "Indent of imports"; 104 | imports_layout: ListTactic, ListTactic::Mixed, false, "Item layout inside a import block"; 105 | imports_granularity: ImportGranularity, ImportGranularity::Preserve, false, 106 | "Merge or split imports to the provided granularity"; 107 | group_imports: GroupImportsTactic, GroupImportsTactic::Preserve, false, 108 | "Controls the strategy for how imports are grouped together"; 109 | merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; 110 | 111 | // Ordering 112 | reorder_imports: bool, true, true, "Reorder import and extern crate statements alphabetically"; 113 | reorder_modules: bool, true, true, "Reorder module statements alphabetically in group"; 114 | reorder_impl_items: bool, false, false, "Reorder impl items"; 115 | 116 | // Spaces around punctuation 117 | type_punctuation_density: TypeDensity, TypeDensity::Wide, false, 118 | "Determines if '+' or '=' are wrapped in spaces in the punctuation of types"; 119 | space_before_colon: bool, false, false, "Leave a space before the colon"; 120 | space_after_colon: bool, true, false, "Leave a space after the colon"; 121 | spaces_around_ranges: bool, false, false, "Put spaces around the .. and ..= range operators"; 122 | binop_separator: SeparatorPlace, SeparatorPlace::Front, false, 123 | "Where to put a binary operator when a binary expression goes multiline"; 124 | 125 | // Misc. 126 | remove_nested_parens: bool, true, true, "Remove nested parens"; 127 | combine_control_expr: bool, true, false, "Combine control expressions with function calls"; 128 | short_array_element_width_threshold: usize, 10, true, 129 | "Width threshold for an array element to be considered short"; 130 | overflow_delimited_expr: bool, false, false, 131 | "Allow trailing bracket/brace delimited expressions to overflow"; 132 | struct_field_align_threshold: usize, 0, false, 133 | "Align struct fields if their diffs fits within threshold"; 134 | enum_discrim_align_threshold: usize, 0, false, 135 | "Align enum variants discrims, if their diffs fit within threshold"; 136 | match_arm_blocks: bool, true, false, "Wrap the body of arms in blocks when it does not fit on \ 137 | the same line with the pattern of arms"; 138 | match_arm_leading_pipes: MatchArmLeadingPipe, MatchArmLeadingPipe::Never, true, 139 | "Determines whether leading pipes are emitted on match arms"; 140 | force_multiline_blocks: bool, false, false, 141 | "Force multiline closure bodies and match arms to be wrapped in a block"; 142 | fn_args_layout: Density, Density::Tall, true, 143 | "Control the layout of arguments in a function"; 144 | brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items"; 145 | control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false, 146 | "Brace style for control flow constructs"; 147 | trailing_semicolon: bool, true, false, 148 | "Add trailing semicolon after break, continue and return"; 149 | trailing_comma: SeparatorTactic, SeparatorTactic::Vertical, false, 150 | "How to handle trailing commas for lists"; 151 | match_block_trailing_comma: bool, false, true, 152 | "Put a trailing comma after a block based match arm (non-block arms are not affected)"; 153 | blank_lines_upper_bound: usize, 1, false, 154 | "Maximum number of blank lines which can be put between items"; 155 | blank_lines_lower_bound: usize, 0, false, 156 | "Minimum number of blank lines which must be put between items"; 157 | edition: Edition, Edition::Edition2015, true, "The edition of the parser (RFC 2052)"; 158 | version: Version, Version::One, false, "Version of formatting rules"; 159 | inline_attribute_width: usize, 0, false, 160 | "Write an item and its attribute on the same line \ 161 | if their combined width is below a threshold"; 162 | format_generated_files: bool, true, false, "Format generated files"; 163 | 164 | // Options that can change the source code beyond whitespace/blocks (somewhat linty things) 165 | merge_derives: bool, true, true, "Merge multiple `#[derive(...)]` into a single one"; 166 | use_try_shorthand: bool, false, true, "Replace uses of the try! macro by the ? shorthand"; 167 | use_field_init_shorthand: bool, false, true, "Use field initialization shorthand if possible"; 168 | force_explicit_abi: bool, true, true, "Always print the abi for extern items"; 169 | condense_wildcard_suffixes: bool, false, false, "Replace strings of _ wildcards by a single .. \ 170 | in tuple patterns"; 171 | 172 | // Control options (changes the operation of rustfmt, rather than the formatting) 173 | // [..] deleted 174 | 175 | // Not user-facing 176 | // [..] deleted 177 | } 178 | 179 | macro_rules! make_enum { 180 | ($name:ident $(, $v:ident)+) => { 181 | #[derive(Serialize)] 182 | pub enum $name { 183 | $( $v, )* 184 | } 185 | }; 186 | } 187 | 188 | make_enum!(NewlineStyle, Auto, Windows, Unix, Native); 189 | make_enum!(IndentStyle, Visual, Block); 190 | make_enum!(Heuristics, Off, Max, Default); 191 | make_enum!(HexLiteralCase, Preserve, Upper, Lower); 192 | make_enum!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed); 193 | make_enum!(ImportGranularity, Preserve, Crate, Module, Item, One); 194 | make_enum!(GroupImportsTactic, Preserve, StdExternalCrate, One); 195 | make_enum!(TypeDensity, Compressed, Wide); 196 | make_enum!(SeparatorPlace, Front, Back); 197 | make_enum!(MatchArmLeadingPipe, Always, Never, Preserve); 198 | make_enum!(Density, Compressed, Tall, Vertical); 199 | make_enum!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere); 200 | make_enum!( 201 | ControlBraceStyle, 202 | AlwaysSameLine, 203 | ClosingNextLine, 204 | AlwaysNextLine 205 | ); 206 | make_enum!(SeparatorTactic, Always, Never, Vertical); 207 | make_enum!(Version, One, Two); 208 | 209 | #[derive(Serialize)] 210 | pub enum Edition { 211 | #[serde(rename = "2015")] 212 | Edition2015, 213 | #[serde(rename = "2018")] 214 | Edition2018, 215 | #[serde(rename = "2021")] 216 | Edition2021, 217 | #[serde(rename = "2024")] 218 | Edition2024, 219 | } 220 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Oxide Computer Company 2 | 3 | //! Use `rustfmt` to format generated code: 4 | //! ``` 5 | //! let codegen = quote::quote!{ struct Foo { bar: String } }; 6 | //! let formatted: String = rustfmt_wrapper::rustfmt(codegen).unwrap(); 7 | //! ``` 8 | 9 | use std::{ 10 | env, 11 | io::Write, 12 | path::PathBuf, 13 | process::{Command, Stdio}, 14 | }; 15 | 16 | use thiserror::Error; 17 | 18 | pub mod config; 19 | 20 | #[derive(Error, Debug)] 21 | pub enum Error { 22 | /// Command `rustfmt` could not be found 23 | #[error("rustfmt is not installed")] 24 | NoRustfmt, 25 | /// Command `rustfmt` produced an error at runtime. 26 | #[error("rustfmt runtime error")] 27 | Rustfmt(String), 28 | /// Nightly channel required, but not found. 29 | #[error("nightly channel required for unstable options")] 30 | Unstable(String), 31 | /// Error with file IO 32 | #[error(transparent)] 33 | IO(#[from] std::io::Error), 34 | /// Error from reading stdin of rustfmt 35 | #[error(transparent)] 36 | Conversion(#[from] std::string::FromUtf8Error), 37 | } 38 | 39 | /// Use the `rustfmt` command to format the input. 40 | pub fn rustfmt(input: T) -> Result { 41 | // The only rustfmt default we override is edition = 2018 (vs 2015) 42 | let config = config::Config { 43 | edition: Some(config::Edition::Edition2018), 44 | ..Default::default() 45 | }; 46 | rustfmt_config(config, input) 47 | } 48 | 49 | /// Use the `rustfmt` command to format the input with the given [`Config`]. 50 | /// 51 | /// [`Config`]: config::Config 52 | pub fn rustfmt_config(mut config: config::Config, input: T) -> Result { 53 | let input = input.to_string(); 54 | 55 | // rustfmt's default edition is 2015; our default is 2021. 56 | if config.edition.is_none() { 57 | config.edition = Some(config::Edition::Edition2018); 58 | } 59 | 60 | let mut builder = tempfile::Builder::new(); 61 | builder.prefix("rustfmt-wrapper"); 62 | let outdir = builder.tempdir().expect("failed to create tmp file"); 63 | 64 | let rustfmt_config_path = outdir.as_ref().join("rustfmt.toml"); 65 | std::fs::write( 66 | rustfmt_config_path, 67 | toml::to_string_pretty(&config).unwrap(), 68 | )?; 69 | 70 | let rustfmt = which_rustfmt().ok_or(Error::NoRustfmt)?; 71 | 72 | let mut args = vec![format!("--config-path={}", outdir.path().to_str().unwrap())]; 73 | if config.unstable() { 74 | args.push("--unstable-features".to_string()) 75 | } 76 | 77 | let mut command = Command::new(&rustfmt) 78 | .args(args) 79 | .stdin(Stdio::piped()) 80 | .stdout(Stdio::piped()) 81 | .stderr(Stdio::piped()) 82 | .spawn() 83 | .unwrap(); 84 | 85 | let mut stdin = command.stdin.take().unwrap(); 86 | std::thread::spawn(move || { 87 | stdin 88 | .write_all(input.as_bytes()) 89 | .expect("Failed to write to stdin"); 90 | }); 91 | 92 | let output = command.wait_with_output()?; 93 | if output.status.success() { 94 | Ok(String::from_utf8(output.stdout)?) 95 | } else { 96 | let err_str = String::from_utf8(output.stderr)?; 97 | if err_str.contains("Unrecognized option: 'unstable-features'") { 98 | Err(Error::Unstable(config.list_unstable())) 99 | } else { 100 | Err(Error::Rustfmt(err_str)) 101 | } 102 | } 103 | } 104 | 105 | fn which_rustfmt() -> Option { 106 | match env::var_os("RUSTFMT") { 107 | Some(which) => { 108 | if which.is_empty() { 109 | None 110 | } else { 111 | Some(PathBuf::from(which)) 112 | } 113 | } 114 | None => toolchain_find::find_installed_component("rustfmt"), 115 | } 116 | } 117 | 118 | #[cfg(test)] 119 | mod tests { 120 | use crate::{config::Config, rustfmt, rustfmt_config}; 121 | use newline_converter::dos2unix; 122 | use quote::quote; 123 | 124 | #[test] 125 | fn test_basics() { 126 | let code = quote! { struct Foo { bar: String } }; 127 | assert_eq!( 128 | dos2unix(rustfmt(code).unwrap().as_str()), 129 | "struct Foo {\n bar: String,\n}\n" 130 | ); 131 | } 132 | 133 | #[test] 134 | fn test_doc_comments() { 135 | let comment = "This is a very long doc comment that could span \ 136 | multiple lines of text. For the purposes of this test, we're hoping \ 137 | that it gets formatted into a single, nice doc comment."; 138 | let code = quote! { 139 | #[doc = #comment] 140 | struct Foo { bar: String } 141 | }; 142 | 143 | let config = Config { 144 | normalize_doc_attributes: Some(true), 145 | wrap_comments: Some(true), 146 | ..Default::default() 147 | }; 148 | 149 | assert_eq!( 150 | dos2unix(rustfmt_config(config, code).unwrap().as_str()), 151 | r#"///This is a very long doc comment that could span multiple lines of text. For 152 | /// the purposes of this test, we're hoping that it gets formatted into a 153 | /// single, nice doc comment. 154 | struct Foo { 155 | bar: String, 156 | } 157 | "#, 158 | ); 159 | } 160 | 161 | #[test] 162 | fn test_narrow_call() { 163 | let code = quote! { 164 | async fn go() { 165 | let _ = Client::new().operation_id().send().await?; 166 | } 167 | }; 168 | 169 | let config = Config { 170 | max_width: Some(45), 171 | ..Default::default() 172 | }; 173 | 174 | assert_eq!( 175 | dos2unix(rustfmt_config(config, code).unwrap().as_str()), 176 | "async fn go() { 177 | let _ = Client::new() 178 | .operation_id() 179 | .send() 180 | .await?; 181 | }\n" 182 | ); 183 | } 184 | } 185 | --------------------------------------------------------------------------------