Skip to content

Instantly share code, notes, and snippets.

@jirutka
Created September 11, 2016 12:55
Show Gist options
  • Save jirutka/50aa3c66e09fedb246465a9b9ce3d102 to your computer and use it in GitHub Desktop.
Save jirutka/50aa3c66e09fedb246465a9b9ce3d102 to your computer and use it in GitHub Desktop.
Script for deploying files to git, for example building documentation and deploying to gh-pages branch on GitHub. https://github.com/jirutka/rake-jekyll#deploy-to-git
#!/bin/sh
# vim: set ts=4:
set -e
: ${DEPLOY_BRANCH:="gh-pages"}
: ${SOURCE_BRANCH:="master"}
die() {
# bold red
printf '\033[1;31mERROR:\033[0m %s\n' "$1" >&2
exit ${2:-2}
}
info() {
# bold cyan
printf '\033[1;36m%s\033[0m\n' "$@" >&2
}
init_deploy_branch() {
local build_dir="$1"
cd "$build_dir"
git checkout --orphan "$DEPLOY_BRANCH"
find . -path ./.git -prune -o -exec rm -rf {} \; 2>/dev/null || :
cd - >/dev/null
}
has_changes() {
test -n "$(git status --porcelain)"
}
remote_origin_url() {
if [ -n "$GH_TOKEN" ]; then
git config remote.origin.url \
| sed 's|^git:|https:|' \
| sed "s|^https://|https://${GH_TOKEN}@|"
else
git config remote.origin.url
fi
}
shield() {
if [ -n "$GH_TOKEN" ]; then
eval $@ 2>&1 | sed "s/$GH_TOKEN/*****/g"
else
eval $@
fi
}
build() {
die 'You must declare function "build"!'
}
default_skip_push() {
[ -n "$TRAVIS" ] || return 1
[ "$TRAVIS_PULL_REQUEST" != 'false' ] \
|| [ "$TRAVIS_BRANCH" != "$SOURCE_BRANCH" ] \
|| [ "$TRAVIS_BUILD_NUMBER.1" != "$TRAVIS_JOB_NUMBER" ]
}
skip_push() {
default_skip_push
}
start() {
local commit_rev="$(git rev-parse --short HEAD)"
local commit_author="$(git log -n 1 --format='%aN <%aE>')"
local commit_date="$(git log -n 1 --format='%aD')"
local build_dir="$(mktemp -q -d "${TMPDIR:-"/tmp"}/docs.XXXX")"
local remote_url="$(remote_origin_url)"
test -n "$remote_url" || die 'Failed to get remote.origin.url'
if [ -n "$TRAVIS" ] && [ -z "$GIT_COMMITTER_NAME" ]; then
GIT_COMMITTER_NAME='Travis CI'
fi
export GIT_COMMITTER_NAME
shield git clone --progress "$remote_url" "$build_dir"
git -C "$build_dir" checkout "$DEPLOY_BRANCH" || {
info "Branch $DEPLOY_BRANCH doesn't exist yet, initializing..."
init_deploy_branch "$build_dir"
}
build "$build_dir"
cd "$build_dir"
if ! has_changes; then
info 'No changes'
exit 0
fi
if skip_push; then
info 'Skipping push'
exit 0
fi
info 'Commiting changes...'
git add --all
git commit \
--message="Built from $commit_rev" \
--author="$commit_author" \
--date="$commit_date"
info 'Pushing changes to the repository...'
shield git push --progress "$remote_url" "$DEPLOY_BRANCH:$DEPLOY_BRANCH"
rm -Rf -- "$build_dir"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment