gobuild

package module
v0.0.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 10 Imported by: 0

README

gobuild

Project Badges

Thread-safe Go/WASM build handler with sync/async compilation support.

Installation

go get github.com/tinywasm/gobuild

Quick Start

Configuration is documented in config.go.

// See config.go for full configuration options
config := &Config{
    Command:                    "go",
    MainInputFileRelativePath:  "server/main.go",
    OutName:                    "app",
    Extension:                  ".exe",
    OutFolderRelativePath:      "dist",
    Logger:                     func(msg ...any) { fmt.Println(msg...) },
    Timeout:                    5 * time.Second,
    Env:                        []string{"GOOS=js", "GOARCH=wasm"}, // For WASM compilation
}

compiler := gobuild.New(config)
err := compiler.CompileProgram() // Synchronous

Async Compilation

config.Callback = func(err error) {
    if err != nil {
        log.Printf("Failed: %v", err)
    } else {
        log.Printf("Success!")
    }
}
err := compiler.CompileProgram() // Returns immediately

Thread-Safe Control

// Cancel ongoing compilation
compiler.Cancel()

// Check compilation status
if compiler.IsCompiling() {
    fmt.Println("Compilation in progress...")
}

Methods

  • CompileProgram() error - Compile to disk (sync/async based on callback)
  • CompileToMemory() ([]byte, error) - Compile to memory (returns byte slice, sync only)
  • BinarySize() string - Get human-readable binary size (e.g., "2.1 MB", "10.4 KB")
  • Cancel() error - Cancel current compilation
  • IsCompiling() bool - Check if compilation is active
  • MainOutputFileNameWithExtension() string - Get output filename with extension (e.g., "main.wasm")
  • FinalOutputPath() string - Get full path to compiled binary (e.g., "web/build/main.wasm")

In-Memory Compilation

// Compile directly to memory without writing to disk
binary, err := compiler.CompileToMemory()
if err != nil {
    log.Fatal(err)
}

// Get human-readable size (works with both disk and memory compilations)
fmt.Printf("Binary size: %s (%d bytes)\n", compiler.BinarySize(), len(binary))
// Output: Binary size: 2.1 MB (2254340 bytes)

Binary Size Information

// After CompileProgram() or CompileToMemory()
size := compiler.BinarySize()
fmt.Println("Compiled binary:", size) 
// Examples: "10.4 KB", "2.3 MB", "1.5 GB"
// Returns "0.0 KB" if binary is unavailable

Features

  • Thread-safe: Automatic cancellation of previous compilations
  • Unique temp files: Prevents conflicts during concurrent builds
  • Context-aware: Proper cancellation and timeout handling
  • In-memory: Compile directly to memory slice without disk I/O
  • Size reporting: Human-readable binary size (KB, MB, GB) for both disk and memory compilations

Contributing

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BinarySizer added in v0.0.22

type BinarySizer struct {
	// contains filtered or unexported fields
}

BinarySizer formats binary sizes in human-readable format

func NewBinarySizer added in v0.0.22

func NewBinarySizer(getBinary func() []byte) *BinarySizer

NewBinarySizer creates a new BinarySizer instance

func (*BinarySizer) BinarySize added in v0.0.22

func (b *BinarySizer) BinarySize() string

BinarySize returns the binary size in human-readable format Returns format: "10.4 KB", "2.3 MB", "1.5 GB" Returns "0.0 KB" if binary is unavailable or empty

func (*BinarySizer) SetLog added in v0.0.22

func (b *BinarySizer) SetLog(f func(...any))

SetLog sets the logging function

type CompileCallback

type CompileCallback func(error)

CompileCallback is called when compilation completes (success or failure)

type Config

type Config struct {
	AppRootDir                string               // eg: /abs/path/to/project
	Command                   string               // eg: "go", "tinygo"
	MainInputFileRelativePath string               // eg: web/main.server.go, web/main.wasm.go
	OutName                   string               // eg: app, user, main.server
	Extension                 string               // eg: .exe, .wasm
	CompilingArguments        func() []string      // eg: []string{"-X 'main.version=v1.0.0'"}
	OutFolderRelativePath     string               // eg: web, web/public/wasm
	Logger                    func(message ...any) // output for log messages to integrate with other tools (e.g., TUI)
	Callback                  CompileCallback      // optional callback for async compilation
	Timeout                   time.Duration        // max compilation time, defaults to 5 seconds if not set
	Env                       []string             // environment variables, eg: []string{"GOOS=js", "GOARCH=wasm"}
}

type GoBuild

type GoBuild struct {
	// contains filtered or unexported fields
}

GoBuild represents a Go compiler instance

func New

func New(c *Config) *GoBuild

New creates a new GoBuild instance with the given configuration

func (*GoBuild) BinarySize added in v0.0.22

func (h *GoBuild) BinarySize() string

BinarySize returns the compiled binary size in human-readable format Returns format: "10.4 KB", "2.3 MB", "1.5 GB" Returns "0.0 KB" if binary is unavailable

func (*GoBuild) BuildArguments

func (h *GoBuild) BuildArguments() []string

BuildArguments returns the build arguments that would be used for compilation This is exposed for testing purposes

func (*GoBuild) Cancel

func (h *GoBuild) Cancel() error

Cancel cancels any active compilation

func (*GoBuild) CompileProgram

func (h *GoBuild) CompileProgram() error

CompileProgram compiles the Go program If a callback is configured, it runs asynchronously and returns immediately Otherwise, it runs synchronously and returns the compilation result Thread-safe: cancels any previous compilation automatically

func (*GoBuild) CompileToMemory added in v0.0.20

func (h *GoBuild) CompileToMemory() ([]byte, error)

CompileToMemory compiles the Go program returning the binary as a byte slice. It avoids writing to physical disk by using stdout.

func (*GoBuild) FinalOutputPath

func (h *GoBuild) FinalOutputPath() string

FinalOutputPath returns the full path to the final output file eg: web/build/main.wasm

func (*GoBuild) IsCompiling

func (h *GoBuild) IsCompiling() bool

IsCompiling returns true if there's an active compilation

func (*GoBuild) MainInputFileRelativePath

func (h *GoBuild) MainInputFileRelativePath() string

MainInputFileRelativePath eg: cmd/main.go

func (*GoBuild) MainOutputFileNameWithExtension

func (h *GoBuild) MainOutputFileNameWithExtension() string

MainOutputFileNameWithExtension returns the output filename with extension (e.g., "main.wasm", "app.exe")

func (*GoBuild) RenameOutputFile

func (h *GoBuild) RenameOutputFile() error

RenameOutputFile renames the default temporary output file to the final output file This is exposed for testing purposes

func (*GoBuild) RenameOutputFileFrom

func (h *GoBuild) RenameOutputFileFrom(tempFileName string) error

RenameOutputFileFrom renames a specific temporary file to the final output file This is exposed for testing purposes

func (*GoBuild) UnobservedFiles

func (h *GoBuild) UnobservedFiles() []string

UnobservedFiles returns the list of files that should not be tracked by file watchers eg: main.exe, main_temp.exe

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL