Files
dev/configs/nixos/modules/shell/fish/functions/deploy-to.fish

87 lines
2.5 KiB
Fish

if test (count $argv) -lt 1; or test (count $argv) -gt 2
echo "usage: deploy-to <host> [branch]" >&2
return 2
end
set host $argv[1]
set branch $argv[2]
set branch_source explicit
if test -z "$branch"
set branch_source current
set branch (git branch --show-current)
end
git rev-parse --show-toplevel >/dev/null 2>&1
or begin
echo "deploy-to: run this from a git checkout" >&2
return 2
end
git fetch origin
or return $status
if test -z "$branch"; or not git rev-parse --verify --quiet refs/remotes/origin/$branch >/dev/null
if test "$branch_source" = explicit
echo "deploy-to: origin/$branch does not exist" >&2
return 1
end
set branch_source upstream
set upstream_ref (git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null)
set branch (string replace -r '^origin/' '' -- $upstream_ref)
end
if test -z "$branch"; or not git rev-parse --verify --quiet refs/remotes/origin/$branch >/dev/null
set branch_source default
set origin_head (git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null)
set branch (string replace -r '^origin/' '' -- $origin_head)
end
if test -z "$branch"
echo "deploy-to: could not determine a deploy branch" >&2
return 2
end
set remote_ref refs/remotes/origin/$branch
git rev-parse --verify --quiet $remote_ref >/dev/null
or begin
echo "deploy-to: origin/$branch does not exist" >&2
return 1
end
set has_local_changes false
if not git diff --quiet $remote_ref --
set has_local_changes true
end
set escaped_branch (string escape -- $branch)
set escaped_host (string escape -- $host)
set remote_command "cd ~/dev && git fetch origin && git switch -- $escaped_branch && git reset --hard origin/$escaped_branch && git clean -fd"
set patch_file ""
set remote_patch_file ""
if test "$has_local_changes" = true
set patch_file (mktemp)
set remote_patch_file "/tmp/deploy-to-$host.patch"
git diff --binary $remote_ref -- >$patch_file
or begin
rm -f $patch_file
return $status
end
scp $patch_file $host:$remote_patch_file
set scp_status $status
rm -f $patch_file
if test $scp_status -ne 0
return $scp_status
end
set escaped_remote_patch_file (string escape -- $remote_patch_file)
set remote_command "$remote_command && git apply --index $escaped_remote_patch_file && rm -f $escaped_remote_patch_file"
end
set remote_command "$remote_command && sudo nixos-rebuild switch --flake .#$escaped_host --print-build-logs"
ssh -t $host $remote_command