gear_utils/
codegen.rs

1// This file is part of Gear.
2
3// Copyright (C) 2021-2025 Gear Technologies Inc.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Useful things for generating code.
20
21use std::{
22    io::Write,
23    process::{Command, Stdio},
24};
25
26/// License header.
27pub const LICENSE: &str = r#"
28// This file is part of Gear.
29//
30// Copyright (C) 2021-2025 Gear Technologies Inc.
31// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
32//
33// This program is free software: you can redistribute it and/or modify
34// it under the terms of the GNU General Public License as published by
35// the Free Software Foundation, either version 3 of the License, or
36// (at your option) any later version.
37//
38// This program is distributed in the hope that it will be useful,
39// but WITHOUT ANY WARRANTY; without even the implied warranty of
40// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41// GNU General Public License for more details.
42//
43// You should have received a copy of the GNU General Public License
44// along with this program. If not, see <https://www.gnu.org/licenses/>.
45
46"#;
47
48/// Formats generated code with rustfmt.
49pub fn format_with_rustfmt(stream: &[u8]) -> String {
50    let raw = String::from_utf8_lossy(stream).to_string();
51    let mut rustfmt = Command::new("rustfmt");
52    let mut code = rustfmt
53        .stdin(Stdio::piped())
54        .stdout(Stdio::piped())
55        .spawn()
56        .expect("Spawn rustfmt failed");
57
58    code.stdin
59        .as_mut()
60        .expect("Get stdin of rustfmt failed")
61        .write_all(raw.as_bytes())
62        .expect("pipe generated code to rustfmt failed");
63
64    let out = code.wait_with_output().expect("Run rustfmt failed").stdout;
65    String::from_utf8_lossy(&out).to_string()
66}