lucenepp: fix darwin build (#376776)
[NixPkgs.git] / pkgs / build-support / fetchhg / nix-prefetch-hg
blob2199ccdbf4afb2f5cd6e3a0957db94c83ffabae7
1 #! /usr/bin/env bash
2 set -e
4 url=$1
5 rev=$2
6 expHash=$3
8 hashType="${NIX_HASH_ALGO:-sha256}"
9 hashFormat=${hashFormat:-"--base32"}
10 rev="${rev:-tip}"
12 LOG() {
13 echo "$@" >&2
16 die() {
17 LOG "$@"
18 exit 1
21 if [[ -z "$url" || "$url" == "--help" ]]; then
22 die "Usage: nix-prefetch-hg URL [rev [EXPECTED-HASH]]"
25 if [[ "${fetchSubrepos:-0}" == 1 ]]; then
26 subrepoClause=S
27 else
28 subrepoClause=
31 # If the hash was given, a file with that hash may already be in the
32 # store.
33 if [[ -n "$expHash" ]]; then
34 finalPath=$(nix-store --print-fixed-path --recursive "$hashType" "$expHash" hg-archive)
35 if ! nix-store --check-validity "$finalPath" 2> /dev/null; then
36 finalPath=
38 hash="$expHash"
42 # If we don't know the hash or a path with that hash doesn't exist,
43 # download the file and add it to the store.
44 if [[ -z "$finalPath" ]]; then
45 # nix>=2.20 rejects adding symlinked paths to the store, so use realpath
46 # to resolve to a physical path. https://github.com/NixOS/nix/issues/11941
47 tmpPath="$(realpath "$(mktemp -d --tmpdir hg-checkout-tmp-XXXXXXXX)")"
48 cleanup() { x=$?; rm -rf "$tmpPath"; exit $x; }; trap cleanup EXIT
50 tmpArchive="$tmpPath/hg-archive"
52 # Perform the checkout.
53 if [[ "$url" != /* ]]; then
54 tmpClone="$tmpPath/hg-clone"
55 hg clone -q -y -U "$url" "$tmpClone" >&2
56 else
57 tmpClone=$url
59 hg archive -q$subrepoClause -y -r "$rev" --cwd "$tmpClone" "$tmpArchive"
60 rm -f "$tmpArchive/.hg_archival.txt"
62 LOG "hg revision is $(cd "$tmpClone"; hg id -r "$rev" -i)"
64 # Compute the hash.
65 hash=$(nix-hash --type "$hashType" "$hashFormat" "$tmpArchive")
66 if [[ -z "$QUIET" ]]; then LOG "hash is $hash"; fi
68 # Add the downloaded file to the Nix store.
69 finalPath=$(nix-store --add-fixed --recursive "$hashType" "$tmpArchive")
71 if [[ -n "$expHash" && "$expHash" != "$hash" ]]; then
72 die "ERROR: hash mismatch for URL \`$url'"
78 if [[ -z "$QUIET" ]]; then LOG "path is $finalPath"; fi
80 echo "$hash"
82 if [[ -n "$PRINT_PATH" ]]; then
83 echo "$finalPath"