11use anyhow:: Result ;
22use heck:: { ToLowerCamelCase as _, ToSnakeCase as _, ToUpperCamelCase as _} ;
3+ use std:: borrow:: Cow ;
34use std:: collections:: { BTreeMap , BTreeSet , HashMap , HashSet , hash_map} ;
45use std:: fmt:: Write as _;
6+ use std:: io:: { self , Write as _} ;
57use std:: iter;
68use std:: mem;
9+ use std:: process:: Command ;
10+ use std:: thread;
711use 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
723728import (
724729 "runtime"
@@ -734,8 +739,9 @@ var {SYNC_EXPORT_PINNER} = runtime.Pinner{{}}
734739// Unused, but present to make the compiler happy
735740func main() {{}}
736741"#
737- )
738- . as_bytes ( ) ,
742+ )
743+ . as_bytes ( ) ,
744+ ) ,
739745 ) ;
740746 files. push ( "go.mod" , b"module wit_component\n \n go 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
756763import (
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