1#!/bin/sh
2# This script will build the compiler on any POSIX system.
3# It automatically installs a Zig compiler to ./.zig-cache
4# if needed. The output will be in ./zig-out/bin.
5#
6# `curl`, `tar`, and `xz` are required in order to download
7# and extract Zig. The rest of the dependencies are compiled
8# from source using the Zig build system.
9cd -- "$(dirname -- "$0")"
10
11ZIG_VERSION=$(grep .minimum_zig_version build.zig.zon \
12 | cut -d '"' -f 2)
13
14if [ -z "$ZIG_LOCAL_CACHE_DIR" ]; then
15 ZIG_LOCAL_CACHE_DIR=".zig-cache"
16fi
17
18ZIG="$ZIG_LOCAL_CACHE_DIR/zig/$ZIG_VERSION/zig"
19
20if [ "$1" == "--fmt" ]; then
21 # dprint.jsonc is configured to run this, however it runs in parallel.
22 # only one installation should happen, not one per file. since there
23 # is no concise way to acquire a filesystem lock on .zig-cache,
24 # formatting before an install is left unsupported.
25 if [ ! -f "$ZIG" ]; then
26 printf "Zig is not installed. Please run ./build once manually\n"
27 exit 1
28 fi
29 shift
30 exec $ZIG fmt $@
31fi
32
33if [ ! -f "$ZIG" ]; then
34 OS=$(uname -s | tr '[:upper:]' '[:lower:]')
35 if [ "$OS" = "darwin" ]; then
36 OS="macos"
37 fi
38 ARCH=$(uname -m)
39 if [ "$ARCH" = "arm64" ]; then
40 ARCH="aarch64"
41 fi
42
43 URL="https://ziglang.org/builds/zig-$OS-$ARCH-$ZIG_VERSION.tar.xz"
44
45 printf "Installing Zig v$ZIG_VERSION via $URL\n"
46
47 CURL=$(command -v curl 2>/dev/null)
48 TAR=$(command -v tar 2>/dev/null)
49 XZ=$(command -v xz 2>/dev/null)
50
51 if [ -z "$CURL" ]; then
52 printf "This script requires 'curl' to be installed.\n"
53 fi
54 if [ -z "$TAR" ]; then
55 printf "This script requires 'tar' to be installed.\n"
56 fi
57 if [ -z "$XZ" ]; then
58 printf "This script requires 'xz' to be installed.\n"
59 fi
60 if [ -z "$CURL" ] || [ -z "$TAR" ] || [ -z "$XZ" ]; then
61 exit 1
62 fi
63
64 mkdir -p "$ZIG_LOCAL_CACHE_DIR/zig/$ZIG_VERSION"
65 curl -fsSL --retry 3 --retry-delay 3 $URL \
66 | tar -xJ --strip-components=1 -C "$ZIG_LOCAL_CACHE_DIR/zig/$ZIG_VERSION"
67 if [ "$($ZIG version)" != "$ZIG_VERSION" ]; then
68 printf "Zig failed to install.\n"
69 rm -rf "$ZIG_LOCAL_CACHE_DIR/zig/$ZIG_VERSION"
70 exit 1
71 fi
72fi
73
74if [ "$1" == "--version" ]; then
75 printf '' | $ZIG fmt --stdin >/dev/null
76 printf "Zig version: "
77 exec $ZIG version
78fi
79
80exec $ZIG build $@