1
0
mirror of https://github.com/goreleaser/goreleaser.git synced 2025-01-12 03:51:10 +02:00

feat(build): initial support for zig (#5312)

Continuing on #5308 and #5307, this finally adds Zig support to
GoReleaser!

Things are very raw still, plenty of use cases to test (please do test
on your project if you can), but it does work at least for simple
projects!

A release done by this:
https://github.com/goreleaser/example-zig/releases/tag/v0.1.0

---------

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
This commit is contained in:
Carlos Alexandro Becker 2024-11-28 08:47:20 -03:00 committed by GitHub
parent e635b3f369
commit 09be848e1a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 1025 additions and 42 deletions

View File

@ -12,3 +12,7 @@ charset = utf-8
[*.{md,yml,yaml,rb}]
indent_size = 2
indent_style = space
[*.py]
indent_size = 4
indent_style = space

6
.gitattributes vendored
View File

@ -10,6 +10,12 @@ www/docs/static/schema.json linguist-generated=true
www/docs/static/schema-pro.json linguist-generated=true
www/docs/static/releases.json linguist-generated=true
www/docs/static/releases-pro.json linguist-generated=true
internal/builders/zig/testdata/proj/**/* linguist-generated=true
internal/builders/zig/all_targets.txt linguist-generated=true
internal/builders/zig/error_targets.txt linguist-generated=true
internal/builders/zig/testdata/version.txt linguist-generated=true
*.nix.golden linguist-language=Nix
*.rb.golden linguist-language=Ruby
*.json.golden linguist-language=JSON

View File

@ -63,6 +63,7 @@ jobs:
- uses: actions/setup-go@41dfa10bad2bb2ae585af6ee5bb4d7d973ad74ed # v4
with:
go-version: stable
- uses: mlugg/setup-zig@v1
- uses: sigstore/cosign-installer@v3.7.0
- uses: anchore/sbom-action/download-syft@v0.17.8
- name: setup-validate-krew-manifest

View File

@ -36,7 +36,7 @@ func (g *Goreleaser) Base() *dagger.Container {
// Base image with Go
return dag.Container().
From(wolfiBase).
WithExec([]string{"apk", "add", "go"}).
WithExec([]string{"apk", "add", "go", "zig"}).
// Mount the Go cache
WithMountedCache(
"/go",

View File

@ -162,6 +162,7 @@ const (
ExtraSize = "Size"
ExtraChecksum = "Checksum"
ExtraChecksumOf = "ChecksumOf"
ExtraBuilder = "Builder"
)
// Extras represents the extra fields in an artifact.
@ -467,14 +468,24 @@ func ByGoarch(s string) Filter {
// ByGoarm is a predefined filter that filters by the given goarm.
func ByGoarm(s string) Filter {
return func(a *Artifact) bool {
return a.Goarm == s
switch ExtraOr(*a, ExtraBuilder, "") {
case "zig":
return true
default:
return a.Goarm == s
}
}
}
// ByGoamd64 is a predefined filter that filters by the given goamd64.
func ByGoamd64(s string) Filter {
return func(a *Artifact) bool {
return a.Goamd64 == s
switch ExtraOr(*a, ExtraBuilder, "") {
case "zig":
return true
default:
return a.Goamd64 == s
}
}
}

View File

@ -244,9 +244,10 @@ func (*Builder) Build(ctx *context.Context, build config.Build, options api.Opti
Goriscv64: t.Goriscv64,
Target: t.Target,
Extra: map[string]interface{}{
artifact.ExtraBinary: strings.TrimSuffix(filepath.Base(options.Path), options.Ext),
artifact.ExtraExt: options.Ext,
artifact.ExtraID: build.ID,
artifact.ExtraBinary: strings.TrimSuffix(filepath.Base(options.Path), options.Ext),
artifact.ExtraExt: options.Ext,
artifact.ExtraID: build.ID,
artifact.ExtraBuilder: "go",
},
}

View File

@ -529,10 +529,11 @@ func TestBuild(t *testing.T) {
Target: "linux_amd64_v1",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=l"},
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=l"},
},
},
{
@ -544,10 +545,11 @@ func TestBuild(t *testing.T) {
Target: "linux_mips_softfloat",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=l"},
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=l"},
},
},
{
@ -559,10 +561,11 @@ func TestBuild(t *testing.T) {
Target: "linux_mips64le_softfloat",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=l"},
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=l"},
},
},
{
@ -574,10 +577,11 @@ func TestBuild(t *testing.T) {
Target: "darwin_amd64_v1",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=d"},
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=d"},
},
},
{
@ -589,10 +593,11 @@ func TestBuild(t *testing.T) {
Target: "linux_arm_6",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=l"},
artifact.ExtraExt: "",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=l"},
},
},
{
@ -604,10 +609,11 @@ func TestBuild(t *testing.T) {
Target: "windows_amd64_v1",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: ".exe",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T=w"},
artifact.ExtraExt: ".exe",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T=w"},
},
},
{
@ -618,10 +624,11 @@ func TestBuild(t *testing.T) {
Target: "js_wasm",
Type: artifact.Binary,
Extra: map[string]interface{}{
artifact.ExtraExt: ".wasm",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
"testEnvs": []string{"TEST_T="},
artifact.ExtraExt: ".wasm",
artifact.ExtraBinary: "foo-v5.6.7",
artifact.ExtraID: "foo",
artifact.ExtraBuilder: "go",
"testEnvs": []string{"TEST_T="},
},
},
}

94
internal/builders/zig/all_targets.txt generated Normal file
View File

@ -0,0 +1,94 @@
aarch64-linux
aarch64-linux-gnu
aarch64-linux-musl
aarch64-macos
aarch64-macos-none
aarch64-windows
aarch64-windows-gnu
aarch64_be-linux
aarch64_be-linux-gnu
aarch64_be-linux-musl
aarch64_be-windows
aarch64_be-windows-gnu
arm-linux
arm-linux-gnueabi
arm-linux-gnueabihf
arm-linux-musleabi
arm-linux-musleabihf
arm-windows
arm-windows-gnu
armeb-linux
armeb-linux-gnueabi
armeb-linux-gnueabihf
armeb-linux-musleabi
armeb-linux-musleabihf
armeb-windows
armeb-windows-gnu
csky-linux
csky-linux-gnueabi
csky-linux-gnueabihf
loongarch64-linux
loongarch64-linux-gnu
loongarch64-linux-musl
m68k-linux
m68k-linux-gnu
m68k-linux-musl
mips-linux
mips-linux-gnueabi
mips-linux-gnueabihf
mips-linux-musl
mips64-linux
mips64-linux-gnuabi64
mips64-linux-gnuabin32
mips64-linux-musl
mips64el-linux
mips64el-linux-gnuabi64
mips64el-linux-gnuabin32
mips64el-linux-musl
mipsel-linux
mipsel-linux-gnueabi
mipsel-linux-gnueabihf
mipsel-linux-musl
powerpc-linux
powerpc-linux-gnueabi
powerpc-linux-gnueabihf
powerpc-linux-musl
powerpc64-linux
powerpc64-linux-gnu
powerpc64-linux-musl
powerpc64le-linux
powerpc64le-linux-gnu
powerpc64le-linux-musl
riscv32-linux
riscv32-linux-gnuilp32
riscv32-linux-musl
riscv64-linux
riscv64-linux-gnu
riscv64-linux-musl
s390x-linux
s390x-linux-gnu
s390x-linux-musl
sparc-linux
sparc-linux-gnu
sparc64-linux
sparc64-linux-gnu
thumb-linux
thumb-linux-gnueabi
thumb-linux-gnueabihf
thumb-linux-musleabi
thumb-linux-musleabihf
wasm32-wasi
wasm32-wasi-musl
x86-linux
x86-linux-gnu
x86-linux-musl
x86-windows
x86-windows-gnu
x86_64-linux
x86_64-linux-gnu
x86_64-linux-gnux32
x86_64-linux-musl
x86_64-macos
x86_64-macos-none
x86_64-windows
x86_64-windows-gnu

View File

@ -0,0 +1,228 @@
package zig
import (
"errors"
"fmt"
"os/exec"
"path/filepath"
"slices"
"strings"
"github.com/caarlos0/log"
"github.com/goreleaser/goreleaser/v2/internal/artifact"
"github.com/goreleaser/goreleaser/v2/internal/gio"
"github.com/goreleaser/goreleaser/v2/internal/tmpl"
api "github.com/goreleaser/goreleaser/v2/pkg/build"
"github.com/goreleaser/goreleaser/v2/pkg/config"
"github.com/goreleaser/goreleaser/v2/pkg/context"
)
// Default builder instance.
//
//nolint:gochecknoglobals
var Default = &Builder{}
//nolint:gochecknoinits
func init() {
api.Register("zig", Default)
}
// Builder is golang builder.
type Builder struct{}
// Parse implements build.Builder.
func (b *Builder) Parse(target string) (api.Target, error) {
parts := strings.Split(target, "-")
if len(parts) < 2 {
return nil, fmt.Errorf("%s is not a valid build target", target)
}
t := Target{
Target: target,
Os: convertToGoos(parts[1]),
Arch: convertToGoarch(parts[0]),
}
if len(parts) > 2 {
t.Abi = parts[2]
}
return t, nil
}
// WithDefaults implements build.Builder.
func (b *Builder) WithDefaults(build config.Build) (config.Build, error) {
log.Warn("you are using the experimental Zig builder")
if len(build.Targets) == 0 {
build.Targets = defaultTargets()
}
if build.GoBinary == "" {
build.GoBinary = "zig"
}
if build.Command == "" {
build.Command = "build"
}
if build.Dir == "" {
build.Dir = "."
}
if build.Main != "" {
return build, errors.New("main is not used for zig")
}
if len(build.Ldflags) > 0 {
return build, errors.New("ldflags is not used for zig")
}
if len(slices.Concat(
build.Goos,
build.Goarch,
build.Goamd64,
build.Go386,
build.Goarm,
build.Goarm64,
build.Gomips,
build.Goppc64,
build.Goriscv64,
)) > 0 {
return build, errors.New("all go* fields are not used for zig, set targets instead")
}
if len(build.Ignore) > 0 {
return build, errors.New("ignore is not used for zig, set targets instead")
}
if build.Buildmode != "" {
return build, errors.New("buildmode is not used for zig")
}
if len(build.Tags) > 0 {
return build, errors.New("tags is not used for zig")
}
if len(build.Asmflags) > 0 {
return build, errors.New("asmtags is not used for zig")
}
if len(build.BuildDetailsOverrides) > 0 {
return build, errors.New("overrides is not used for zig")
}
for _, t := range build.Targets {
switch checkTarget(t) {
case targetValid:
// lfg
case targetBroken:
log.Warnf("target might not be supported: %s", t)
case targetInvalid:
return build, fmt.Errorf("invalid target: %s", t)
}
}
return build, nil
}
// Build implements build.Builder.
func (b *Builder) Build(ctx *context.Context, build config.Build, options api.Options) error {
prefix := filepath.Dir(options.Path)
options.Path = filepath.Join(prefix, "bin", options.Name)
t := options.Target.(Target)
a := &artifact.Artifact{
Type: artifact.Binary,
Path: options.Path,
Name: options.Name,
Goos: convertToGoos(t.Os),
Goarch: convertToGoarch(t.Arch),
Target: t.Target,
Extra: map[string]interface{}{
artifact.ExtraBinary: strings.TrimSuffix(filepath.Base(options.Path), options.Ext),
artifact.ExtraExt: options.Ext,
artifact.ExtraID: build.ID,
artifact.ExtraBuilder: "zig",
},
}
env := []string{}
env = append(env, ctx.Env.Strings()...)
tpl := tmpl.New(ctx).
WithBuildOptions(options).
WithEnvS(env).
WithArtifact(a)
zigbin, err := tpl.Apply(build.GoBinary)
if err != nil {
return err
}
command := []string{
zigbin,
build.Command,
"-Dtarget=" + t.Target,
"-p", prefix,
}
for _, e := range build.Env {
ee, err := tpl.Apply(e)
if err != nil {
return err
}
log.Debugf("env %q evaluated to %q", e, ee)
if ee != "" {
env = append(env, ee)
}
}
tpl = tpl.WithEnvS(env)
flags, err := processFlags(tpl, build.Flags)
if err != nil {
return err
}
command = append(command, flags...)
/* #nosec */
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
cmd.Env = env
cmd.Dir = build.Dir
log.Debug("running")
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%w: %s", err, string(out))
}
if s := string(out); s != "" {
log.WithField("cmd", command).Info(s)
}
// TODO: move this to outside builder for both go and zig
modTimestamp, err := tpl.Apply(build.ModTimestamp)
if err != nil {
return err
}
if err := gio.Chtimes(a.Path, modTimestamp); err != nil {
return err
}
ctx.Artifacts.Add(a)
return nil
}
func processFlags(tpl *tmpl.Template, flags []string) ([]string, error) {
var processed []string
for _, rawFlag := range flags {
flag, err := tpl.Apply(rawFlag)
if err != nil {
return nil, err
}
if flag == "" {
continue
}
processed = append(processed, flag)
}
return processed, nil
}

View File

@ -0,0 +1,186 @@
package zig
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/goreleaser/goreleaser/v2/internal/testctx"
"github.com/goreleaser/goreleaser/v2/internal/testlib"
api "github.com/goreleaser/goreleaser/v2/pkg/build"
"github.com/goreleaser/goreleaser/v2/pkg/config"
"github.com/stretchr/testify/require"
)
func TestParse(t *testing.T) {
for target, dst := range map[string]Target{
"x86_64-linux": {
Target: "x86_64-linux",
Os: "linux",
Arch: "amd64",
},
"x86_64-linux-gnu": {
Target: "x86_64-linux-gnu",
Os: "linux",
Arch: "amd64",
Abi: "gnu",
},
"aarch64-linux-gnu": {
Target: "aarch64-linux-gnu",
Os: "linux",
Arch: "arm64",
Abi: "gnu",
},
"aarch64-linux": {
Target: "aarch64-linux",
Os: "linux",
Arch: "arm64",
},
"aarch64-macos": {
Target: "aarch64-macos",
Os: "darwin",
Arch: "arm64",
},
} {
t.Run(target, func(t *testing.T) {
got, err := Default.Parse(target)
require.NoError(t, err)
require.IsType(t, Target{}, got)
require.Equal(t, dst, got.(Target))
})
}
t.Run("invalid", func(t *testing.T) {
_, err := Default.Parse("linux")
require.Error(t, err)
})
}
func TestWithDefaults(t *testing.T) {
t.Run("valid", func(t *testing.T) {
build, err := Default.WithDefaults(config.Build{})
require.NoError(t, err)
require.Equal(t, config.Build{
GoBinary: "zig",
Command: "build",
Dir: ".",
Targets: defaultTargets(),
}, build)
})
t.Run("invalid", func(t *testing.T) {
cases := map[string]config.Build{
"main": {
Main: "a",
},
"ldflags": {
BuildDetails: config.BuildDetails{
Ldflags: []string{"-a"},
},
},
"goos": {
Goos: []string{"a"},
},
"goarch": {
Goarch: []string{"a"},
},
"goamd64": {
Goamd64: []string{"a"},
},
"go386": {
Go386: []string{"a"},
},
"goarm": {
Goarm: []string{"a"},
},
"goarm64": {
Goarm64: []string{"a"},
},
"gomips": {
Gomips: []string{"a"},
},
"goppc64": {
Goppc64: []string{"a"},
},
"goriscv64": {
Goriscv64: []string{"a"},
},
"ignore": {
Ignore: []config.IgnoredBuild{{}},
},
"overrides": {
BuildDetailsOverrides: []config.BuildDetailsOverride{{}},
},
"buildmode": {
BuildDetails: config.BuildDetails{
Buildmode: "a",
},
},
"tags": {
BuildDetails: config.BuildDetails{
Tags: []string{"a"},
},
},
"asmflags": {
BuildDetails: config.BuildDetails{
Asmflags: []string{"a"},
},
},
}
for k, v := range cases {
t.Run(k, func(t *testing.T) {
_, err := Default.WithDefaults(v)
require.Error(t, err)
})
}
})
}
func TestBuild(t *testing.T) {
testlib.CheckPath(t, "zig")
modTime := time.Now().AddDate(-1, 0, 0).Round(1 * time.Second).UTC()
dist := t.TempDir()
ctx := testctx.NewWithCfg(config.Project{
Dist: dist,
ProjectName: "proj",
Env: []string{
"OPTIMIZE_FOR=ReleaseSafe",
},
Builds: []config.Build{
{
Dir: "./testdata/proj/",
ModTimestamp: fmt.Sprintf("%d", modTime.Unix()),
BuildDetails: config.BuildDetails{
Flags: []string{"-Doptimize={{.Env.OPTIM}}"},
Env: []string{
"OPTIM={{.Env.OPTIMIZE_FOR}}",
},
},
},
},
})
build, err := Default.WithDefaults(ctx.Config.Builds[0])
require.NoError(t, err)
options := api.Options{
Name: "proj",
Path: filepath.Join(dist, "proj-aarch64-macos", "proj"),
Target: nil,
}
options.Target, err = Default.Parse("aarch64-macos")
require.NoError(t, err)
require.NoError(t, Default.Build(ctx, build, options))
bins := ctx.Artifacts.List()
require.Len(t, bins, 1)
bin := bins[0]
require.Equal(t, filepath.Join(dist, "proj-aarch64-macos", "bin", "proj"), filepath.FromSlash(bin.Path))
require.FileExists(t, bin.Path)
fi, err := os.Stat(bin.Path)
require.NoError(t, err)
require.True(t, modTime.Equal(fi.ModTime()), "inconsistent mod times found when specifying ModTimestamp")
}

38
internal/builders/zig/error_targets.txt generated Normal file
View File

@ -0,0 +1,38 @@
aarch64_be-windows
aarch64_be-windows-gnu
arm-windows
arm-windows-gnu
armeb-linux
armeb-linux-gnueabi
armeb-linux-gnueabihf
armeb-linux-musleabi
armeb-linux-musleabihf
armeb-windows
armeb-windows-gnu
csky-linux
csky-linux-gnueabi
csky-linux-gnueabihf
loongarch64-linux
loongarch64-linux-gnu
loongarch64-linux-musl
m68k-linux
m68k-linux-gnu
m68k-linux-musl
powerpc-linux
powerpc-linux-gnueabi
powerpc-linux-gnueabihf
riscv32-linux
riscv32-linux-gnuilp32
riscv32-linux-musl
riscv64-linux
riscv64-linux-gnu
s390x-linux
s390x-linux-gnu
s390x-linux-musl
sparc-linux
sparc-linux-gnu
sparc64-linux
sparc64-linux-gnu
thumb-linux
thumb-linux-gnueabi
thumb-linux-gnueabihf

View File

@ -0,0 +1,109 @@
package zig
import (
"slices"
"strings"
"sync"
_ "embed"
"github.com/goreleaser/goreleaser/v2/internal/tmpl"
)
var (
//go:embed all_targets.txt
allTargetsBts []byte
//go:embed error_targets.txt
errTargetsBts []byte
allTargets []string
errTargets []string
targetsOnce sync.Once
)
const keyAbi = "Abi"
// Target is a Zig build target.
type Target struct {
// The zig formatted target (arch-os-abi).
Target string
Os string
Arch string
Abi string
}
// Fields implements build.Target.
func (t Target) Fields() map[string]string {
return map[string]string{
tmpl.KeyOS: t.Os,
tmpl.KeyArch: t.Arch,
keyAbi: t.Abi,
}
}
// String implements fmt.Stringer.
func (t Target) String() string {
return t.Target
}
func convertToGoos(s string) string {
switch s {
case "macos":
return "darwin"
default:
return s
}
}
func convertToGoarch(s string) string {
switch s {
case "aarch64":
return "arm64"
case "x86_64":
return "amd64"
default:
return s
}
}
type targetStatus uint8
const (
targetInvalid targetStatus = iota
targetBroken
targetValid
)
func (t targetStatus) String() string {
return [3]string{
"invalid",
"broken",
"valid",
}[t]
}
func checkTarget(target string) targetStatus {
targetsOnce.Do(func() {
allTargets = strings.Split(string(allTargetsBts), "\n")
errTargets = strings.Split(string(errTargetsBts), "\n")
})
if slices.Contains(errTargets, target) {
return targetBroken
}
if slices.Contains(allTargets, target) {
return targetValid
}
return targetInvalid
}
func defaultTargets() []string {
return []string{
"x86_64-linux",
"x86_64-macos",
"x86_64-windows",
"aarch64-linux",
"aarch64-macos",
}
}

View File

@ -0,0 +1,41 @@
package zig
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCheckTarget(t *testing.T) {
t.Run("invalid", func(t *testing.T) {
for _, target := range []string{
"fake-target",
"x86_64-windows-abcde",
} {
t.Run(target, func(t *testing.T) {
require.Equal(t, targetInvalid, checkTarget(target))
})
}
})
t.Run("broken", func(t *testing.T) {
for _, target := range []string{
"arm-windows",
"arm-windows-gnu",
} {
t.Run(target, func(t *testing.T) {
require.Equal(t, targetBroken, checkTarget(target))
})
}
})
t.Run("valid", func(t *testing.T) {
for _, target := range []string{
"aarch64-linux-musl",
"aarch64-linux",
"aarch64-macos",
} {
t.Run(target, func(t *testing.T) {
require.Equal(t, targetValid, checkTarget(target))
})
}
})
}

View File

@ -0,0 +1,3 @@
a.*
*.txt
!version.txt

3
internal/builders/zig/testdata/main.c vendored Normal file
View File

@ -0,0 +1,3 @@
#include <stdio.h>
int main(int argc, char *argv[]) { return 0; }

2
internal/builders/zig/testdata/proj/.gitignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
.zig-cache
zig-out

91
internal/builders/zig/testdata/proj/build.zig generated vendored Normal file
View File

@ -0,0 +1,91 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const lib = b.addStaticLibrary(.{
.name = "proj",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
// This declares intent for the library to be installed into the standard
// location when the user invokes the "install" step (the default step when
// running `zig build`).
b.installArtifact(lib);
const exe = b.addExecutable(.{
.name = "proj",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);
test_step.dependOn(&run_exe_unit_tests.step);
}

72
internal/builders/zig/testdata/proj/build.zig.zon generated vendored Normal file
View File

@ -0,0 +1,72 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "proj",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

24
internal/builders/zig/testdata/proj/src/main.zig generated vendored Normal file
View File

@ -0,0 +1,24 @@
const std = @import("std");
pub fn main() !void {
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
// stdout is for the actual output of your application, for example if you
// are implementing gzip, then only the compressed bytes should be sent to
// stdout, not any debugging messages.
const stdout_file = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer();
try stdout.print("Run `zig build test` to run the tests.\n", .{});
try bw.flush(); // don't forget to flush!
}
test "simple test" {
var list = std.ArrayList(i32).init(std.testing.allocator);
defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
try list.append(42);
try std.testing.expectEqual(@as(i32, 42), list.pop());
}

10
internal/builders/zig/testdata/proj/src/root.zig generated vendored Normal file
View File

@ -0,0 +1,10 @@
const std = @import("std");
const testing = std.testing;
export fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add functionality" {
try testing.expect(add(3, 7) == 10);
}

19
internal/builders/zig/testdata/targets.sh vendored Executable file
View File

@ -0,0 +1,19 @@
#!/bin/bash
rm -f ./*targets.txt
zig version >version.txt
zig targets | jq -r '.libc[]' | grep -v freestanding | sort | uniq | while read -r target; do
# tries to compile a simple hello world in C:
if zig cc -target "$target" main.c 2>/dev/null; then
echo "$target" >>./success_targets.txt
echo "$target" | cut -f1,2 -d- >>./success_targets.txt
else
echo "$target" >>./error_targets.txt
echo "$target" | cut -f1,2 -d- >>./error_targets.txt
fi
echo "$target" >>./all_targets.txt
echo "$target" | cut -f1,2 -d- >>./all_targets.txt
done
sort <./all_targets.txt | uniq >../all_targets.txt
sort <./error_targets.txt | uniq >../error_targets.txt

1
internal/builders/zig/testdata/version.txt generated vendored Normal file
View File

@ -0,0 +1 @@
0.13.0

View File

@ -21,6 +21,7 @@ import (
// langs to init.
_ "github.com/goreleaser/goreleaser/v2/internal/builders/golang"
_ "github.com/goreleaser/goreleaser/v2/internal/builders/zig"
)
// Pipe for build.
@ -160,11 +161,6 @@ func doBuild(ctx *context.Context, build config.Build, opts builders.Options) er
func buildOptionsForTarget(ctx *context.Context, build config.Build, target string) (*builders.Options, error) {
ext := extFor(target, build.BuildDetails)
parts := strings.Split(target, "_")
if len(parts) < 2 {
return nil, fmt.Errorf("%s is not a valid build target", target)
}
buildOpts := builders.Options{
Ext: ext,
}

View File

@ -258,8 +258,7 @@ builds:
dir: go
# Builder allows you to use a different build implementation.
# This is a GoReleaser Pro feature.
# Valid options are: `go` and `prebuilt`.
# Valid options are: `go`, `zig`, and `prebuilt` (pro-only).
#
# Default: 'go'.
builder: prebuilt
@ -472,6 +471,39 @@ GoReleaser:
- Remove uses of the `time` template function. This function returns a new value
on every call and is not deterministic.
## Build Zig binaries
<!-- md:version 2.5 -->
<!-- md:alpha -->
You can now build Zig binaries using `zig build` and GoReleaser!
Simply set the `builder` to `zig`, for instance:
```yml
# .goreleaser.yaml
builds:
- # Use zig
builder: zig
targets:
- aarch64-macos
- x86_64-linux-gnu
```
Some options are not supported yet[^fail], but it should be usable at least for
simple projects already!
### Caveats
GoReleaser will translate Zig's Os/Arch pair into a GOOS/GOARCH pair, so
templates should work the same as before. The original target name is available
in templates as `.Target`, and so is the ABI as `.Abi`.
[^fail]:
GoReleaser will error if you try to use them. Give it a try with
`goreleaser r --snapshot --clean`.
## Import pre-built binaries
<!-- md:pro -->
@ -581,7 +613,7 @@ Since you can have GoReleaser build for multiple different `GOAMD64` targets, it
adds that suffix to prevent name conflicts. The same thing happens for `arm` and
`GOARM`, `mips` and `GOMIPS` and others.
### Go's first class ports
## Go's first class ports
The `targets` option can take a `go_first_class` special value as target, which
will evaluate to the list of first class ports as defined in the Go wiki.

View File

@ -19,6 +19,7 @@ def on_page_markdown(markdown: str, *, page: Page, config: MkDocsConfig, files:
elif type == "pro": return _pro_ad(page, files)
elif type == "featpro": return _pro_feat_ad(page, files)
elif type == "templates": return _templates_ad()
elif type == "alpha": return _alpha_block()
# Otherwise, raise an error
raise RuntimeError(f"Unknown shortcode: {type}")
@ -48,6 +49,9 @@ def _pro_ad(page: Page, files: Files):
def _version_block(text: str):
return f"> Since :material-tag-outline: <a href=\"/blog/goreleaser-{text}\">{text}</a>."
def _alpha_block():
return f"> :material-flask-outline: This feature is in alpha, and your feedback is very welcome!"
def _templates_ad():
return "".join([
f"<div class=\"admonition tip\">",