| 1 | #!/usr/bin/env bash |
| 2 | # Build a universal macOS binary (arm64 + x86_64) from a crate. Needs Xcode CLT only. |
| 3 | # Usage: scripts/build-macos.sh [crate-dir, default crates/app] [binary-or-example-name, default: the crate's only binary] |
| 4 | set -euo pipefail |
| 5 | repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" |
| 6 | crateDir="$(realpath "${1:-$repoRoot/crates/app}")" |
| 7 | binaryName="${2:-}" |
| 8 | export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repoRoot/target}" |
| 9 | export PATH="$HOME/.cargo/bin:$PATH" |
| 10 | targets=(aarch64-apple-darwin x86_64-apple-darwin) |
| 11 | |
| 12 | rustup target add "${targets[@]}" >/dev/null |
| 13 | |
| 14 | buildArguments=(build --release) |
| 15 | slicePathInTarget="release" |
| 16 | if [ -n "$binaryName" ] && [ -f "$crateDir/examples/$binaryName.rs" ]; then |
| 17 | buildArguments+=(--example "$binaryName") |
| 18 | slicePathInTarget="release/examples" |
| 19 | elif [ -n "$binaryName" ]; then |
| 20 | buildArguments+=(--bin "$binaryName") |
| 21 | fi |
| 22 | |
| 23 | for target in "${targets[@]}"; do |
| 24 | (cd "$crateDir" && cargo "${buildArguments[@]}" --target "$target") |
| 25 | done |
| 26 | |
| 27 | slices=() |
| 28 | for target in "${targets[@]}"; do |
| 29 | sliceDirectory="$CARGO_TARGET_DIR/$target/$slicePathInTarget" |
| 30 | if [ -n "$binaryName" ]; then |
| 31 | slices+=("$sliceDirectory/$binaryName") |
| 32 | else |
| 33 | candidates=("$sliceDirectory"/*) |
| 34 | [ "${#candidates[@]}" -eq 1 ] && [ -f "${candidates[0]}" ] || |
| 35 | { echo "more than one binary in $sliceDirectory, pass the name" >&2; exit 1; } |
| 36 | slices+=("${candidates[0]}") |
| 37 | fi |
| 38 | done |
| 39 | |
| 40 | outputDirectory="$CARGO_TARGET_DIR/universal/release" |
| 41 | mkdir -p "$outputDirectory" |
| 42 | output="$outputDirectory/$(basename "${slices[0]}")" |
| 43 | lipo -create -output "$output" "${slices[@]}" |
| 44 | file "$output" |
| 45 | ls -la "$output" |