Skip to content

Instantly share code, notes, and snippets.

@alexilyaev
Last active May 19, 2020 16:55
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 alexilyaev/2672fe6d99756377fbffaabad6db1f45 to your computer and use it in GitHub Desktop.
Save alexilyaev/2672fe6d99756377fbffaabad6db1f45 to your computer and use it in GitHub Desktop.
Git CI authentication with SSH keys
#!/usr/bin/env bash
# References:
# https://docs.travis-ci.com/user/environment-variables
#
# Inspired by:
# https://gist.github.com/willprice/e07efd73fb7f13f917ea
# But using SSH keys instead of Personal Access Token:
# https://gist.github.com/alexilyaev/2672fe6d99756377fbffaabad6db1f45
# https://misc.flogisoft.com/bash/tip_colors_and_formatting
ANSI_GREEN_BOLD="\033[32;1m"
ANSI_RED="\033[31m"
ANSI_BLUE="\033[34m"
ANSI_RESET="\033[0m"
targetRepoSshUrl="git@github.com:${TRAVIS_REPO_SLUG}.git"
ciBranch="$TRAVIS_BRANCH"
function log() {
local msg="$1"
echo -e "\n${ANSI_GREEN_BOLD}LOG:${ANSI_RESET} ${ANSI_BLUE}$msg${ANSI_RESET}"
}
function logError() {
local msg="$1"
echo -e "\n${ANSI_RED}ERROR: $msg${ANSI_RESET}"
}
log "Running deploy-ci script..."
# Immediately exit if we're in a PR build.
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
log "This is a PR build, nothing to do."
exit 0
fi
# Use an SSH connection instead of the default read-only https connection.
function setupRepo() {
log "Setup Git SSH connection"
# Ensure proper branch matching when multiple remotes are set
git config --global checkout.defaultRemote origin
git remote rm origin || true
git remote add origin "$targetRepoSshUrl"
git fetch --all
}
function mergeFromTo() {
local fromBranch=$1
local targetBranch=$2
log "Switch to branch '$targetBranch'"
git checkout "$targetBranch"
if [ "$?" = "1" ]; then
logError "Failed to checkout branch: '$targetBranch'"
return 1
fi
# Must use --no-ff, otherwise GitHub won't emit any events when we 'push',
# and Vercel won't deploy our branch.
# Must also provide a commit message when using '--no-ff'.
log "Merge '$fromBranch' into '$targetBranch'"
git merge --no-ff "$fromBranch" -m "Merge '$fromBranch' into '$targetBranch'"
if [ "$?" = "1" ]; then
logError "Failed to merge '$fromBranch' into '$targetBranch'"
return 1
fi
# Using '--force' in case the branch was tampered with manually.
log "Push '$targetBranch'"
git push --force
if [ "$?" = "1" ]; then
logError "Failed to push branch: '$targetBranch'"
return 1
fi
}
if [ "$ciBranch" == "master" ]; then
targetBranch="staging"
log "'$ciBranch' branch updated, merge and push to '$targetBranch'"
setupRepo || exit 1
mergeFromTo "origin/$ciBranch" "$targetBranch" || exit 1
fi
log "Finished deploy-ci script."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment