Current section

Files

Jump to
garnet_tool src garnet.gleam
Raw

src/garnet.gleam

import argv
import esgleam
import gleam/io
import gleam/string
import gleam_community/ansi
import shellout
import simplifile
const help_message = "garnet - Compile gleam to single binary, via Deno and Bun.
Usage: garnet `target_module` `outname` `runtime`
target_module(require): Module name of compile target module.
outname(require): Name of output binary.
runtime(default: deno): Runtime of when use make single binary.
"
pub fn main() {
let _ = case argv.load().arguments {
[modname, outname, runtime] -> {
let _ = compile(modname, outname, runtime)
shellout.exit(1)
}
[modname, outname] -> {
let _ = compile(modname, outname, "deno")
shellout.exit(1)
}
_ -> {
io.println(help_message)
shellout.exit(1)
}
}
}
fn deploy_glue() {
case simplifile.copy_file("./src/glue.js", "./dist/glue.js") {
Ok(_) -> io.println("Copy sucessed.")
Error(_) -> io.println("Copy failed.")
}
}
fn bundle(target: String) {
let _ =
esgleam.new("./dist")
|> esgleam.entry(
[target, ".gleam"]
|> string.concat,
)
|> esgleam.bundle
}
/// Compile module to single binary.
///
/// ```gleam
/// compile("example", "out", "deno")
/// ```
pub fn compile(modname: String, outfile: String, runtime: String) {
let _ = simplifile.delete(outfile)
// Compile and bundle.
case bundle(modname) {
Error(_) -> shellout.exit(1)
_ -> Nil
}
deploy_glue()
// Generate single binary.
case runtime {
"bun" -> compile_bun(outfile)
"deno" -> compile_deno(outfile)
_ -> Error("Missing target runtime")
}
}
fn compile_deno(outfile: String) -> Result(String, String) {
io.println(
"===== Build on Deno ====="
|> ansi.cyan,
)
case
shellout.command(
run: "deno",
with: ["compile", "-o", outfile, "-A", "./dist/glue.js"],
in: ".",
opt: [shellout.LetBeStdout],
)
{
Ok(val) -> Ok(val)
Error(_) -> Error("Compile failed.")
}
}
fn compile_bun(outfile: String) -> Result(String, String) {
io.println(
"===== Build on Bun ====="
|> ansi.cyan,
)
case
shellout.command(
run: "bun",
with: ["build", "./dist/glue.js", "--compile", "--outfile", outfile],
in: ".",
opt: [shellout.LetBeStdout],
)
{
Ok(val) -> Ok(val)
Error(_) -> Error("Compile failed.")
}
}