Skip to content

Commit 9972772

Browse files
committed
run gofmt on generated code if available
Signed-off-by: Joel Dice <joel.dice@fermyon.com>
1 parent e14b18c commit 9972772

File tree

1 file changed

+40
-12
lines changed

1 file changed

+40
-12
lines changed

crates/go/src/lib.rs

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
use anyhow::Result;
22
use heck::{ToLowerCamelCase as _, ToSnakeCase as _, ToUpperCamelCase as _};
3+
use std::borrow::Cow;
34
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, hash_map};
45
use std::fmt::Write as _;
6+
use std::io::{self, Write as _};
57
use std::iter;
68
use std::mem;
9+
use std::process::Command;
10+
use std::thread;
711
use wit_bindgen_core::abi::{
812
self, AbiVariant, Bindgen, Bitcast, FlatTypes, Instruction, LiftLower, WasmType,
913
};
@@ -717,8 +721,9 @@ impl WorldGenerator for Go {
717721

718722
files.push(
719723
"wit_bindings.go",
720-
format!(
721-
r#"package main
724+
&gofmt(
725+
format!(
726+
r#"package main
722727
723728
import (
724729
"runtime"
@@ -734,8 +739,9 @@ var {SYNC_EXPORT_PINNER} = runtime.Pinner{{}}
734739
// Unused, but present to make the compiler happy
735740
func main() {{}}
736741
"#
737-
)
738-
.as_bytes(),
742+
)
743+
.as_bytes(),
744+
),
739745
);
740746
files.push("go.mod", b"module wit_component\n\ngo 1.25");
741747
files.push(
@@ -750,16 +756,18 @@ func main() {{}}
750756

751757
files.push(
752758
&format!("{prefix}{name}/wit_bindings.go"),
753-
format!(
754-
"package {prefix}{name}
759+
&gofmt(
760+
format!(
761+
"package {prefix}{name}
755762
756763
import (
757764
{imports}
758765
)
759766
760767
{code}"
761-
)
762-
.as_bytes(),
768+
)
769+
.as_bytes(),
770+
),
763771
);
764772
}
765773
}
@@ -788,13 +796,15 @@ import (
788796

789797
files.push(
790798
"wit_types/wit_tuples.go",
791-
format!(
792-
r#"package wit_types
799+
&gofmt(
800+
format!(
801+
r#"package wit_types
793802
794803
{tuples}
795804
"#
796-
)
797-
.as_bytes(),
805+
)
806+
.as_bytes(),
807+
),
798808
);
799809
}
800810

@@ -2948,3 +2958,21 @@ fn func_declaration(resolve: &Resolve, func: &Function) -> (String, bool) {
29482958
}
29492959
}
29502960
}
2961+
2962+
fn gofmt<'a>(code: &'a [u8]) -> Cow<'a, [u8]> {
2963+
return thread::scope(|s| {
2964+
if let Ok((reader, mut writer)) = io::pipe() {
2965+
s.spawn(move || {
2966+
_ = writer.write_all(&code);
2967+
});
2968+
2969+
if let Ok(output) = Command::new("gofmt").stdin(reader).output() {
2970+
if output.status.success() {
2971+
return Cow::Owned(output.stdout);
2972+
}
2973+
}
2974+
}
2975+
2976+
Cow::Borrowed(code)
2977+
});
2978+
}

0 commit comments

Comments
 (0)