Skip to content
Latchkey

Mage: Write Build Targets in Go

Mage runs build targets that you write as exported Go functions in a magefile.

Mage is a make-like tool where the build logic is plain Go, not a DSL. Each exported function is a target; dependencies are expressed with mg.Deps.

What it does

A magefile is a Go file with the //go:build mage tag and an exported function per target. A target returns nothing, or error, and may take a context.Context. mage <Target> runs it. Dependencies use mg.Deps(Build, Test) to run other targets first (once, in parallel). mage -l lists targets and their doc comments.

Common usage

magefile.go
//go:build mage

package main

import (
    "github.com/magefile/mage/mg"
    "github.com/magefile/mage/sh"
)

// Build compiles the binary.
func Build() error {
    return sh.Run("go", "build", "./...")
}

// Test runs the unit tests after Build.
func Test() error {
    mg.Deps(Build)
    return sh.Run("go", "test", "./...")
}

// run: mage test

Syntax

FormWhat it does
//go:build mageBuild tag marking the file as a magefile
func Build() errorAn exported function is a runnable target
mg.Deps(A, B)Run targets A and B first (once, in parallel)
ctx context.ContextOptional first arg for cancellation/timeout
mage <Target>Run the named target (case-insensitive)
mage -lList targets with their doc comments

In CI

Mage targets are real Go, so they are testable and cross-platform without shell quirks, which suits multi-OS pipelines. Express ordering with mg.Deps so one mage test call runs the whole chain. Document each target with a comment so mage -l shows useful help in logs.

Common errors in CI

"No .go files marked with the mage build tag" means the //go:build mage tag is missing or malformed. "Unknown target specified: X" means the function is not exported (lowercase) or misspelled. A target with an unsupported signature gives "target has invalid signature". Build failures surface as Go compiler errors before any target runs.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →