Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 28 additions & 26 deletions crates/go/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,6 @@ fn remote_pkg(name: &str) -> String {
format!(r#""github.com/bytecodealliance/wit-bindgen/{name}""#)
}

/// This is the literal location of the Go package.
const REPLACEMENT_PKG: &str = concat!(
"github.com/bytecodealliance/wit-bindgen/crates/go/src/package v",
env!("CARGO_PKG_VERSION")
);

#[derive(Default, Debug, Copy, Clone)]
pub enum Format {
#[default]
Expand Down Expand Up @@ -105,10 +99,6 @@ pub struct Opts {
/// (or "wit_component" if `None`).
#[cfg_attr(feature = "clap", clap(long))]
pub mod_name: Option<String>,

/// The package name used in the top-level Wasm exports file (or "main" if `None`).
#[cfg_attr(feature = "clap", clap(long))]
pub pkg_name: Option<String>,
}

impl Opts {
Expand Down Expand Up @@ -853,18 +843,39 @@ impl WorldGenerator for Go {
.collect::<Vec<_>>()
.join("\n");

// If a package name isn't "main", there isn't a need for a main function.
let (package_name, main_func) = if let Some(pkg) = self.opts.pkg_name.as_deref() {
(pkg, "")
let (exports_file_path, package_name, main_func) = if self.opts.mod_name.is_some() {
// If a module name is specified, the generated files will be used as a library.
("wit_exports/wit_exports.go", "wit_exports", "")
} else {
let func = r#"// Unused, but present to make the compiler happy
// This is the literal location of the Go package.
let replacement_pkg = concat!(
"github.com/bytecodealliance/wit-bindgen/crates/go/src/package v",
env!("CARGO_PKG_VERSION")
);

files.push(
"go.mod",
format!(
"module {}\n\ngo 1.25\n\nreplace github.com/bytecodealliance/wit-bindgen => {}",
self.opts.mod_name.as_deref().unwrap_or("wit_component"),
replacement_pkg
)
.as_bytes(),
);

// If a module name is NOT specified, the generated files will be used as a
// standalone executable.
(
"wit_exports.go",
"main",
r#"// Unused, but present to make the compiler happy
func main() {}
"#;
("main", func)
"#,
)
};

files.push(
"wit_exports.go",
exports_file_path,
&maybe_gofmt(
self.opts.format,
format!(
Expand All @@ -888,15 +899,6 @@ var {SYNC_EXPORT_PINNER} = runtime.Pinner{{}}
.as_bytes(),
),
);
files.push(
"go.mod",
format!(
"module {}\n\ngo 1.25\n\nreplace github.com/bytecodealliance/wit-bindgen => {}",
self.opts.mod_name.as_deref().unwrap_or("wit_component"),
REPLACEMENT_PKG
)
.as_bytes(),
);

for (prefix, interfaces) in [("export_", &self.export_interfaces), ("", &self.interfaces)] {
for (name, data) in interfaces {
Expand Down
Loading