grace/dots

dotfiles/nix configs

git clone https://git.gae.moe/grace/dots

Grace Yodersecrets + lix2aaa11a

main
6.9 KiB252 linesraw
1{
2  config,
3  pkgs,
4  lib,
5  ...
6}:
7
8let
9  gitDir = "/mnt/ext/git";
10
11  deploy = pkgs.writeShellScript "git-deploy" ''
12    set -euo pipefail
13
14    export PATH="${
15      lib.makeBinPath [
16        pkgs.git
17        pkgs.gnutar
18        pkgs.coreutils
19        pkgs.nix
20        pkgs.util-linux
21      ]
22    }:$PATH"
23
24    export NIX_PATH="nixpkgs=${pkgs.path}"
25
26    repo="$1"
27    rev="$2"
28    artifactDir="$3"
29    htmlDir="$4"
30    ref="$5"
31
32    mkdir -p "$XDG_RUNTIME_DIR/git-deploy"
33    lock=$(printf '%s' "$repo" | sha256sum | cut -d' ' -f1)
34    exec 9>"$XDG_RUNTIME_DIR/git-deploy/$lock.lock"
35    flock 9
36
37    current=$(git -C "$repo" rev-parse --verify "$ref^{commit}" 2>/dev/null) || exit 0
38    if [ "$current" != "$rev" ]; then
39      echo "Skipping obsolete deployment for $ref"
40      exit 0
41    fi
42
43    tmp="$(mktemp -d)"
44    finish() {
45      status=$?
46      trap - EXIT
47      rm -rf "$tmp"
48      if [ "$status" -eq 0 ]; then
49        outcome=succeeded
50      else
51        outcome=failed
52      fi
53      credentials=${config.sops.secrets.git-build-notify.path}
54      if [ -r "$credentials" ]; then
55        printf 'Build/deploy %s: %s (%s) at %s\nArtifacts: %s\n' \
56          "$outcome" "$repo" "$ref" "$rev" "$artifactDir" |
57          ${pkgs.curl}/bin/curl --config "$credentials" \
58            --fail --silent --show-error --connect-timeout 3 --max-time 10 \
59            --header "Title: Git build/deploy $outcome" \
60            --data-binary @- --output /dev/null \
61            https://ntfy.gae.moe/githooks || true
62      fi
63      exit "$status"
64    }
65    trap finish EXIT
66
67    while read -r key; do
68      unset "$key"
69    done < <(git rev-parse --local-env-vars)
70
71    git -C "$repo" archive "$rev" | tar -xf - -C "$tmp"
72    cd "$tmp"
73
74    result="$(nix-build --out-link "$tmp/result" ./hook.nix \
75      --argstr artifactDir "$artifactDir" \
76      --argstr htmlDir "$htmlDir")"
77
78    mkdir -p "$artifactDir" "$htmlDir"
79    "$result/bin/deploy"
80
81    commitDate="$(git -C "$repo" log -1 --format=%ct "$rev^{commit}")"
82
83    find "$artifactDir" "$htmlDir" \
84      -exec touch -h -d "@$commitDate" {} +
85  '';
86
87  queue = pkgs.writeShellScript "git-queue-deploy" ''
88    set -euo pipefail
89    export PATH=${
90      lib.makeBinPath [
91        pkgs.git
92        pkgs.coreutils
93        pkgs.systemd
94      ]
95    }:$PATH
96    XDG_RUNTIME_DIR="/run/user/$(id -u)"
97    export XDG_RUNTIME_DIR
98    if [ "$(id -un)" != git ]; then
99      echo "Run this command as the git user" >&2
100      exit 1
101    fi
102
103    repoPath=$(realpath "$1")
104    ref="$2"
105    rev="$3"
106    root=${gitDir}
107    case "$repoPath" in
108      "$root"/*) ;;
109      *) echo "Repository must be beneath $root" >&2; exit 1 ;;
110    esac
111    case "$ref" in
112      refs/heads/*) name="''${ref#refs/heads/}"; otherNamespace=refs/tags ;;
113      refs/tags/*) name="''${ref#refs/tags/}"; otherNamespace=refs/heads ;;
114      *) exit 0 ;;
115    esac
116    commit=$(git -C "$repoPath" rev-parse --verify "$rev^{commit}" 2>/dev/null) || exit 0
117    git -C "$repoPath" cat-file -e "$commit:hook.nix" 2>/dev/null || exit 0
118    others=$(git -C "$repoPath" for-each-ref --format='%(refname)' "$otherNamespace")
119    while IFS= read -r other; do
120      [ -n "$other" ] || continue
121      otherName="''${other#"$otherNamespace"/}"
122      if [ "$name" = "$otherName" ] || [[ "$name" = "$otherName/"* ]] || [[ "$otherName" = "$name/"* ]]; then
123        if git -C "$repoPath" cat-file -e "$other:hook.nix" 2>/dev/null; then
124          echo "Cannot deploy $ref: $other overlaps its output path" >&2
125          exit 1
126        fi
127      fi
128    done <<< "$others"
129
130    repo="''${repoPath#"$root"/}"
131    repo="''${repo%.git}"
132    systemd-run --user --no-block --collect \
133      --unit="git-deploy-$(date +%s%N)-$RANDOM" \
134      ${deploy} "$repoPath" "$commit" \
135      "$root/artifacts/$repo/$name" "$root/www/$repo/$name" "$ref"
136    echo "Queued deployment for $ref" >&2
137  '';
138
139  regenerate = pkgs.writeShellScriptBin "git-regenerate" ''
140    set -euo pipefail
141    export PATH=${
142      lib.makeBinPath [
143        pkgs.git
144        pkgs.coreutils
145      ]
146    }:$PATH
147    if [ "$#" -gt 1 ]; then
148      echo "Usage: git-regenerate [REPOSITORY]" >&2
149      exit 2
150    fi
151    repo=$(realpath "''${1:-.}")
152    refs=$(git -C "$repo" for-each-ref --format='%(refname)' refs/heads refs/tags)
153    status=0
154    while IFS= read -r ref; do
155      [ -n "$ref" ] || continue
156      ${queue} "$repo" "$ref" "$ref" || status=1
157    done <<< "$refs"
158    exit "$status"
159  '';
160
161  mirror = pkgs.writeShellScript "git-mirror" ''
162    set -euo pipefail
163    export PATH=${
164      lib.makeBinPath [
165        pkgs.git
166        pkgs.coreutils
167        pkgs.util-linux
168      ]
169    }:$PATH
170    export GIT_TERMINAL_PROMPT=0
171    export GIT_SSH_COMMAND='${pkgs.openssh}/bin/ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=2'
172    repo="$1"
173    mkdir -p "$XDG_RUNTIME_DIR/git-deploy"
174    lock=$(printf '%s' "$repo" | sha256sum | cut -d' ' -f1)
175    exec 9>"$XDG_RUNTIME_DIR/git-deploy/$lock-mirror.lock"
176    flock 9
177
178    for remote in tangled github codeberg; do
179      git -C "$repo" remote get-url --push "$remote" &>/dev/null || continue
180      echo "Pushing $repo to $remote..." >&2
181      failed=0
182      timeout 120 git -C "$repo" push --force "$remote" --all || failed=1
183      timeout 120 git -C "$repo" push --force "$remote" --tags || failed=1
184      if [ "$failed" -ne 0 ]; then
185        credentials=${config.sops.secrets.git-build-notify.path}
186        if [ -r "$credentials" ]; then
187          printf 'Failed to push %s to %s\n' "$repo" "$remote" |
188            ${pkgs.curl}/bin/curl --config "$credentials" \
189              --fail --silent --show-error --connect-timeout 3 --max-time 10 \
190              --header 'Title: Git mirror failed' \
191              --data-binary @- --output /dev/null https://ntfy.gae.moe/githooks || true
192        fi
193      fi
194    done
195  '';
196in
197{
198  sops.secrets.git-build-notify = {
199    sopsFile = ../secrets/knuth/git-build-notify.json;
200    format = "binary";
201    owner = "git";
202  };
203
204  environment.systemPackages = [ regenerate ];
205  users.users.git.linger = true;
206
207  programs.git = {
208    enable = true;
209    config.core.hooksPath = "/etc/git/hooks";
210  };
211
212  environment.etc."git/hooks/post-receive".source = pkgs.writeShellScript "post-receive" ''
213    set -euo pipefail
214
215    export PATH="${
216      lib.makeBinPath [
217        pkgs.git
218        pkgs.coreutils
219        pkgs.systemd
220      ]
221    }:$PATH"
222
223    XDG_RUNTIME_DIR="/run/user/$(id -u)"
224    export XDG_RUNTIME_DIR
225
226    root="${gitDir}"
227    repoPath="$(pwd -P)"
228
229    case "$repoPath" in
230      "$root"/*) ;;
231      *) exit 0 ;;
232    esac
233
234    updates="$(cat)"
235
236    status=0
237    while read -r _old new ref; do
238      [[ "$new" =~ ^0+$ ]] && continue
239      ${queue} "$repoPath" "$ref" "$new" || status=1
240    done <<< "$updates"
241
242    systemd-run --user --no-block --collect \
243      --unit="git-mirror-$(date +%s%N)-$RANDOM" ${mirror} "$repoPath" || status=1
244
245    localHook="$repoPath/hooks/post-receive"
246
247    if [ -x "$localHook" ]; then
248      printf '%s\n' "$updates" | "$localHook" || status=1
249    fi
250    exit "$status"
251  '';
252}