wasmgo 0.3.5

Go WebAssembly plugin for Wasmrun - compile Go projects to WebAssembly using TinyGo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#[cfg(feature = "cli")]
use clap::{Parser, Subcommand};
use wasmgo::{CompileConfig, OptimizationLevel, Plugin, TargetType, WasmGoPlugin};

#[cfg(feature = "cli")]
#[derive(Parser)]
#[command(name = "wasmgo")]
#[command(about = "Go WebAssembly plugin for Wasmrun")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[cfg(feature = "cli")]
#[derive(Subcommand)]
enum Commands {
    /// Run a Go WebAssembly project for execution (default command)
    #[command(alias = "r")]
    Run {
        /// Project path containing go.mod or main.go
        #[arg(short, long, default_value = ".", value_name = "PATH")]
        project: String,

        /// Output directory for compiled files
        #[arg(short, long, default_value = "./dist", value_name = "DIR")]
        output: String,

        /// Optimization level for compilation
        #[arg(long, value_enum, default_value = "release")]
        optimization: CliOptimization,

        /// Enable verbose compilation output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Compile a Go project to WebAssembly
    #[command(alias = "c")]
    Compile {
        /// Project path containing go.mod or main.go
        #[arg(short, long, default_value = ".", value_name = "PATH")]
        project: String,

        /// Output directory for compiled files
        #[arg(short, long, default_value = "./dist", value_name = "DIR")]
        output: String,

        /// Optimization level for compilation
        #[arg(long, value_enum, default_value = "release")]
        optimization: CliOptimization,

        /// Target type for compilation
        #[arg(long, value_enum, default_value = "wasm")]
        target: CliTarget,

        /// Enable verbose compilation output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Inspect project structure, dependencies, and frameworks
    #[command(alias = "check")]
    Inspect {
        /// Project path to inspect
        #[arg(short, long, default_value = ".", value_name = "PATH")]
        project: String,
    },

    /// Check if wasmgo can handle the project
    CanHandle {
        /// Project path to check
        #[arg(value_name = "PATH")]
        project: String,
    },

    /// Check dependencies and system requirements
    CheckDeps,

    /// Clean build artifacts
    Clean {
        /// Project path to clean
        #[arg(value_name = "PATH")]
        project: String,
    },

    /// Show plugin information and capabilities
    Info,

    /// Show supported frameworks and project types
    Frameworks,
}

#[cfg(feature = "cli")]
#[derive(clap::ValueEnum, Clone, Debug)]
enum CliOptimization {
    /// Fast compilation with debug symbols
    Debug,
    /// Balanced optimization for production
    Release,
    /// Smallest possible output size
    Size,
}

#[cfg(feature = "cli")]
#[derive(clap::ValueEnum, Clone, Debug)]
enum CliTarget {
    /// Standard WebAssembly module
    Wasm,
    /// Complete web application bundle
    WebApp,
}

#[cfg(feature = "cli")]
impl From<CliOptimization> for OptimizationLevel {
    fn from(opt: CliOptimization) -> Self {
        match opt {
            CliOptimization::Debug => OptimizationLevel::Debug,
            CliOptimization::Release => OptimizationLevel::Release,
            CliOptimization::Size => OptimizationLevel::Size,
        }
    }
}

#[cfg(feature = "cli")]
impl From<CliTarget> for TargetType {
    fn from(target: CliTarget) -> Self {
        match target {
            CliTarget::Wasm => TargetType::Standard,
            CliTarget::WebApp => TargetType::WebApp,
        }
    }
}

#[cfg(feature = "cli")]
fn print_header() {
    println!(
        "๐Ÿน {} v{}",
        env!("CARGO_PKG_NAME"),
        env!("CARGO_PKG_VERSION")
    );
    println!("   {}", env!("CARGO_PKG_DESCRIPTION"));
    println!();
}

#[cfg(feature = "cli")]
fn check_project_validity(plugin: &WasmGoPlugin, project: &str) -> bool {
    if !plugin.can_handle_project(project) {
        eprintln!("โŒ Error: Not a valid Go project");
        eprintln!("   Looking for go.mod or .go files in: {project}");
        eprintln!("   Make sure you're in a Go project directory");
        return false;
    }
    true
}

#[cfg(feature = "cli")]
fn check_dependencies(plugin: &WasmGoPlugin) -> bool {
    let missing_deps = plugin.get_builder().check_dependencies();
    if !missing_deps.is_empty() {
        eprintln!("โŒ Missing required dependencies:");
        for dep in &missing_deps {
            eprintln!("   โ€ข {dep}");
        }
        eprintln!();
        eprintln!("๐Ÿ’ก Installation suggestions:");
        if missing_deps.iter().any(|d| d.contains("go")) {
            eprintln!("   โ€ข Install Go: https://golang.org/dl/");
        }
        if missing_deps.iter().any(|d| d.contains("tinygo")) {
            eprintln!("   โ€ข Install TinyGo: https://tinygo.org/getting-started/install/");
        }
        return false;
    }
    true
}

#[cfg(feature = "cli")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    let plugin = WasmGoPlugin::new();

    // Default to Run command if no subcommand is provided
    // Note: this would require making command optional in Cli struct
    match cli.command {
        Commands::Run {
            project,
            output,
            optimization,
            verbose,
        } => {
            if verbose {
                print_header();
                println!("๐Ÿš€ Preparing Go project for execution...");
                println!("๐Ÿ“ Project: {project}");
                println!("๐Ÿ“ฆ Output: {output}");
                println!("๐ŸŽฏ Optimization: {optimization:?}");
                println!();
            }

            if !check_project_validity(&plugin, &project) {
                std::process::exit(1);
            }

            if !check_dependencies(&plugin) {
                std::process::exit(1);
            }

            let builder = plugin.get_builder();
            let compile_config = CompileConfig {
                project_path: project.clone(),
                output_directory: output,
                verbose,
                optimization_level: optimization.into(),
                target_type: TargetType::Standard,
            };

            match builder.compile(&compile_config) {
                Ok(result) => {
                    if verbose {
                        println!("โœ… Project ready for execution!");
                        println!("๐ŸŽฏ Entry point: {}", result.wasm_file_path);
                    } else {
                        println!("{}", result.wasm_file_path);
                    }
                }
                Err(e) => {
                    eprintln!("โŒ Failed to prepare project for execution: {e}");
                    std::process::exit(1);
                }
            }
        }

        Commands::Compile {
            project,
            output,
            optimization,
            target,
            verbose,
        } => {
            if verbose {
                print_header();
                println!("๐Ÿ”จ Compiling Go project to WebAssembly...");
                println!("๐Ÿ“ Project: {project}");
                println!("๐Ÿ“ฆ Output: {output}");
                println!("๐ŸŽฏ Optimization: {optimization:?}");
                println!("๐Ÿ—๏ธ  Target: {target:?}");
                println!();
            }

            if !check_project_validity(&plugin, &project) {
                std::process::exit(1);
            }

            if !check_dependencies(&plugin) {
                std::process::exit(1);
            }

            let builder = plugin.get_builder();
            let compile_config = CompileConfig {
                project_path: project.clone(),
                output_directory: output,
                verbose,
                optimization_level: optimization.into(),
                target_type: target.into(),
            };

            match builder.compile(&compile_config) {
                Ok(result) => {
                    println!("โœ… Compilation completed successfully!");
                    println!("๐ŸŽฏ WASM file: {}", result.wasm_file_path);

                    if let Some(js_path) = result.js_file_path {
                        println!("๐Ÿ“„ JS bindings: {js_path}");
                    }

                    if !result.additional_files.is_empty() {
                        println!("๐Ÿ“‚ Additional files: {}", result.additional_files.len());
                        if verbose {
                            for file in result.additional_files {
                                println!("   โ€ข {file}");
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("โŒ Compilation failed: {e}");
                    std::process::exit(1);
                }
            }
        }

        Commands::Inspect { project } => {
            print_header();
            println!("๐Ÿ” Inspecting Go project...");
            println!();

            if plugin.can_handle_project(&project) {
                println!("๐Ÿ“Š Project Analysis");
                println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");

                if let Ok(directory_entries) = std::fs::read_dir(&project) {
                    let go_files: Vec<_> = directory_entries
                        .filter_map(|entry| entry.ok())
                        .filter(|entry| {
                            entry
                                .path()
                                .extension()
                                .map(|extension| extension.to_string_lossy().to_lowercase() == "go")
                                .unwrap_or(false)
                        })
                        .map(|entry| entry.file_name().to_string_lossy().to_string())
                        .collect();

                    if !go_files.is_empty() {
                        println!("๐Ÿ“ Go files: {}", go_files.join(", "));
                    }
                }

                if std::path::Path::new(&project).join("go.mod").exists() {
                    println!("๐Ÿ“ฆ Module: Found go.mod");
                }

                println!("๐ŸŽฏ Type: Go WebAssembly project");
                println!("๐Ÿ”ง Build Tool: TinyGo");

                println!();
                println!("๐Ÿ“‹ Dependencies");
                println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");

                let missing = plugin.get_builder().check_dependencies();
                if missing.is_empty() {
                    println!("โœ… go - Go compiler");
                    println!("โœ… tinygo - WebAssembly compiler for Go");
                    println!();
                    println!("๐ŸŽ‰ Project is ready to compile!");
                } else {
                    for dep in &missing {
                        println!("โŒ {dep}");
                    }
                    println!();
                    println!(
                        "โš ๏ธ  Some required dependencies are missing. Install them to proceed."
                    );
                    std::process::exit(1);
                }
            } else {
                eprintln!("โŒ Invalid project: Not a Go project");
                eprintln!("   Looking for go.mod or .go files in: {project}");
                std::process::exit(1);
            }
        }

        Commands::CanHandle { project } => {
            if plugin.can_handle_project(&project) {
                println!("โœ… Yes, wasmgo can handle this project");
                if std::path::Path::new(&project).join("go.mod").exists() {
                    println!("๐Ÿ“ Found go.mod at: {project}/go.mod");
                } else {
                    println!("๐Ÿ“ Found Go files in: {project}");
                }
            } else {
                println!("โŒ No, wasmgo cannot handle this project");
                println!("๐Ÿ” Looking for go.mod or .go files in: {project}");
                std::process::exit(1);
            }
        }

        Commands::CheckDeps => {
            print_header();
            println!("๐Ÿ” Checking system dependencies...");
            println!();

            let missing = plugin.get_builder().check_dependencies();

            if missing.is_empty() {
                println!("โœ… All required dependencies are available!");
                println!();
                println!("๐Ÿ“‹ Available tools:");
                println!("   โœ… go - Go compiler");
                println!("   โœ… tinygo - WebAssembly compiler for Go");
            } else {
                println!("โŒ Missing required dependencies:");
                for dep in &missing {
                    println!("   โ€ข {dep}");
                }

                println!();
                println!("๐Ÿ’ก Installation suggestions:");
                println!("   โ€ข Install Go: https://golang.org/dl/");
                println!("   โ€ข Install TinyGo: https://tinygo.org/getting-started/install/");
                println!("   โ€ข On macOS with Homebrew: brew install go tinygo");
                println!("   โ€ข On Ubuntu/Debian: sudo apt install golang-go && follow TinyGo instructions");

                std::process::exit(1);
            }
        }

        Commands::Clean { project } => {
            println!("๐Ÿงน Cleaning project artifacts: {project}");

            // For Go projects, we mainly clean any built WASM files
            let dist_path = std::path::Path::new(&project).join("dist");
            if dist_path.exists() {
                match std::fs::remove_dir_all(&dist_path) {
                    Ok(_) => println!("โœ… Cleaned dist directory"),
                    Err(e) => println!("โš ๏ธ  Failed to clean dist directory: {e}"),
                }
            }

            println!("โœ… Project cleaned successfully!");
        }

        Commands::Info => {
            print_header();
            println!("๐Ÿ”ง Plugin Information");
            println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
            let plugin_info = plugin.info();
            println!("Name: {}", plugin_info.name);
            println!("Version: {}", plugin_info.version);
            println!("Description: {}", plugin_info.description);
            println!("Author: {}", plugin_info.author);

            println!();
            println!("๐ŸŽฏ Capabilities");
            println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
            println!("โœ… Standard WASM compilation");
            println!("โœ… TinyGo integration");
            println!("โœ… Multiple optimization levels");
            println!("โœ… Go module support");
            println!();

            println!("๐Ÿ“„ Usage");
            println!("โ•โ•โ•โ•โ•โ•โ•โ•");
            println!("Primary (via Wasmrun):");
            println!("   wasmrun run ./my-go-project");
            println!("   wasmrun compile ./my-project --optimization size");
            println!();
            println!("Standalone (testing/development):");
            println!("   {} run ./my-project", env!("CARGO_PKG_NAME"));
            println!(
                "   {} compile ./my-project --target webapp",
                env!("CARGO_PKG_NAME")
            );
            println!("   {} inspect ./my-project", env!("CARGO_PKG_NAME"));
        }

        Commands::Frameworks => {
            print_header();
            println!("๐ŸŒ Supported Frameworks & Project Types");
            println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
            println!();

            println!("๐Ÿ“ฆ Project Types:");
            println!("   โ€ข Standard WASM    - Basic Go โ†’ WebAssembly compilation via TinyGo");
            println!("   โ€ข Web Applications - Full Go web apps compiled to WebAssembly");
            println!();

            println!("๐Ÿ”ง Build Tools:");
            println!("   โ€ข TinyGo           - Primary WebAssembly compiler for Go");
            println!("   โ€ข go               - Standard Go toolchain for dependency management");
            println!();

            println!("๐ŸŽฏ Optimization Levels:");
            println!("   โ€ข debug            - Fast compilation, debug symbols");
            println!("   โ€ข release          - Balanced optimization");
            println!("   โ€ข size             - Smallest possible output");
        }
    }

    Ok(())
}

#[cfg(not(feature = "cli"))]
fn main() {
    println!("Wasmrun Go Plugin v{}", env!("CARGO_PKG_VERSION"));
    println!("This plugin is designed to be used with the Wasmrun WebAssembly runtime.");
    println!("Configuration is stored in Cargo.toml [package.metadata.wasm-plugin] section.");
    println!();
    println!("Install the CLI feature to use this binary standalone:");
    println!("  cargo install wasmgo --features cli");
    println!();
    println!("Or use with Wasmrun:");
    println!("  wasmrun plugin install wasmgo");
    println!("  wasmrun run ./my-go-project");
}