1#!/usr/bin/env bash
2
3# Generates a Nix expression to fetch swiftpm dependencies, and a
4# configurePhase snippet to prepare a working directory for swift-build.
5
6set -eu -o pipefail
7shopt -s lastpipe
8
9stateFile=".build/workspace-state.json"
10if [[ ! -f "$stateFile" ]]; then
11 echo >&2 "Missing $stateFile. Run 'swift package resolve' first."
12 exit 1
13fi
14
15stateVersion="$(jq .version $stateFile)"
16if [[ $stateVersion -lt 5 || $stateVersion -gt 6 ]]; then
17 echo >&2 "Unsupported $stateFile version"
18 exit 1
19fi
20
21# Iterate dependencies and prefetch.
22hashes=""
23jq -r '.object.dependencies[] | "\(.subpath) \(.packageRef.location) \(.state.checkoutState.revision)"' $stateFile \
24| while read -r name url rev; do
25 echo >&2 "-- Fetching $name"
26 hash="$(nurl "$url" "$rev" --json --submodules=true --fetcher=fetchgit | jq -r .args.hash)"
27hashes+="
28 \"$name\" = \"$hash\";"
29 echo >&2
30done
31hashes+=$'\n'" "
32
33# Generate output.
34mkdir -p nix
35# Copy the workspace state, but clear 'artifacts'.
36jq '.object.artifacts = []' < $stateFile > nix/workspace-state.json
37# Build an expression for fetching sources, and preparing the working directory.
38cat > nix/default.nix << EOF
39# This file was generated by swiftpm2nix.
40{
41 workspaceStateFile = ./workspace-state.json;
42 hashes = {$hashes};
43}
44EOF
45echo >&2 "-- Generated ./nix"