Skip to main content

gear_utils/
codegen.rs

1// Copyright (C) Gear Technologies Inc.
2// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
3
4//! Useful things for generating code.
5
6use std::{
7    io::Write,
8    process::{Command, Stdio},
9};
10
11/// License header.
12pub const LICENSE: &str = r#"
13// Copyright (C) Gear Technologies Inc.
14// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
15
16"#;
17
18/// Formats generated code with rustfmt.
19pub fn format_with_rustfmt(stream: &[u8]) -> String {
20    let raw = String::from_utf8_lossy(stream).to_string();
21    let mut rustfmt = Command::new("rustfmt");
22    let mut code = rustfmt
23        .stdin(Stdio::piped())
24        .stdout(Stdio::piped())
25        .spawn()
26        .expect("Spawn rustfmt failed");
27
28    code.stdin
29        .as_mut()
30        .expect("Get stdin of rustfmt failed")
31        .write_all(raw.as_bytes())
32        .expect("pipe generated code to rustfmt failed");
33
34    let out = code.wait_with_output().expect("Run rustfmt failed").stdout;
35    String::from_utf8_lossy(&out).to_string()
36}