Skip to content

Instantly share code, notes, and snippets.

@avnik
Created April 18, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avnik/686eb565b4b4ac84e3c5ad70d9953435 to your computer and use it in GitHub Desktop.
Save avnik/686eb565b4b4ac84e3c5ad70d9953435 to your computer and use it in GitHub Desktop.
{ fetchgit, writeScript, openssh, stdenv, config}:
with stdenv.lib;
let
gitConf = config.fetchGitPrivate or {};
hosts = mapAttrsToList (host: attrs: attrs // { host = host; identityFileInternal = "identity_host_${host}"; }) (gitConf.hosts or {});
identities = imap (i: attrs: attrs // { identityFileInternal = "identity_${toString i}"; } ) (gitConf.identities or []);
in
args: derivation ((fetchgit args).drvAttrs // {
GIT_SSH = writeScript "fetchgit-ssh" ''
#! ${stdenv.shell} -e
tmpTemplate="''${TMPDIR:-/tmp}/git-checkout-tmp-XXXXXXXX"
tmpPath="$(mktemp -d $tmpTemplate)"
# shellcheck disable=SC2064
trap "rm -rf \"$tmpPath\"" EXIT
sshConfig=$tmpPath/ssh_config
chmod 0700 $tmpPath
# Copy identity files and fix permissions
${concatMapStrings (item: ''
cp ${item.identityFile} $tmpPath/${item.identityFileInternal}
chmod 0600 $tmpPath/${item.identityFileInternal}
'') (filter (h: h ? identityFile) hosts ++ identities) }
cat >$sshConfig <<EOF
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
# Common identities from config.fetchGitPrivate.identities
${concatMapStrings (item: ''
IdentityFile $tmpPath/${item.identityFileInternal}
'') identities}
# Per host definitions
${concatMapStrings (item: ''
Host ${item.host}
HostName ${item.hostName}
Port ${toString item.port}
${optionalString (item ? identityFile) "IdentityFile $tmpPath/${item.identityFileInternal}"}
'') hosts}
EOF
# not exec, because we perform some cleanup in trap
${openssh}/bin/ssh -F $sshConfig "$@"
'';
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment