|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +exit_trap () { |
| 4 | + local lc="$BASH_COMMAND" rc=$? |
| 5 | + if [ $rc != 0 ]; then |
| 6 | + echo "Command [$lc] exited with code [$rc]" |
| 7 | + fi |
| 8 | +} |
| 9 | + |
| 10 | +git_retry () { |
| 11 | +# Retry git on exit code 128 |
| 12 | +( |
| 13 | + set +e |
| 14 | + RETRY_ON_SIGNAL=128 |
| 15 | + COMMAND=$@ |
| 16 | + local TRY_NUM=1 MAX_TRIES=3 RETRY_WAIT=60 |
| 17 | + until [[ "$TRY_NUM" -ge "$MAX_TRIES" ]]; do |
| 18 | + $COMMAND |
| 19 | + EXIT_CODE=$? |
| 20 | + if [[ $EXIT_CODE == 0 ]]; then |
| 21 | + break |
| 22 | + elif [[ $EXIT_CODE == "$RETRY_ON_SIGNAL" ]]; then |
| 23 | + echo "$COMMAND failed with Exit Code $EXIT_CODE - try $TRY_NUM " |
| 24 | + TRY_NUM=$(( ${TRY_NUM} + 1 )) |
| 25 | + sleep $RETRY_WAIT |
| 26 | + else |
| 27 | + break |
| 28 | + fi |
| 29 | + done |
| 30 | + return $EXIT_CODE |
| 31 | + ) |
| 32 | +} |
| 33 | + |
| 34 | +trap exit_trap EXIT |
| 35 | +set -e |
| 36 | + |
| 37 | +[ -z "$REVISION" ] && (echo "missing REVISION var" | tee /dev/stderr) && exit 1 |
| 38 | + |
| 39 | +echo "$PRIVATE_KEY" > /root/.ssh/codefresh |
| 40 | +chmod 700 ~/.ssh/ |
| 41 | +chmod 600 ~/.ssh/* |
| 42 | + |
| 43 | +cd $WORKING_DIRECTORY |
| 44 | + |
| 45 | +git config --global credential.helper "/bin/sh -c 'echo username=$USERNAME; echo password=$PASSWORD'" |
| 46 | + |
| 47 | +# Check if the cloned dir already exists from previous builds |
| 48 | +if [ -d "$CLONE_DIR" ]; then |
| 49 | + |
| 50 | + # Cloned dir already exists from previous builds so just fetch all the changes |
| 51 | + echo "Preparing to update $REPO" |
| 52 | + cd $CLONE_DIR |
| 53 | + |
| 54 | + # Reset the remote URL because the embedded user token may have changed |
| 55 | + git remote set-url origin $REPO |
| 56 | + |
| 57 | + echo "Cleaning up the working directory" |
| 58 | + git reset -q --hard |
| 59 | + git clean -df |
| 60 | + git gc |
| 61 | + git_retry git remote prune origin |
| 62 | + |
| 63 | + echo "Fetching the updates from origin" |
| 64 | + git_retry git fetch --tags -v |
| 65 | + |
| 66 | + if [ -n "$REVISION" ]; then |
| 67 | + |
| 68 | + echo "Updating $REPO to revision $REVISION" |
| 69 | + git checkout $REVISION |
| 70 | + |
| 71 | + CURRENT_BRANCH="`git branch 2>/dev/null | grep '^*' | cut -d' ' -f2-`" |
| 72 | + |
| 73 | + # If the revision is identical to the current branch we can rebase it with the latest changes. This isn't needed when running detached |
| 74 | + if [ "$REVISION" == "$CURRENT_BRANCH" ]; then |
| 75 | + echo 'Rebasing current branch $REVISION to latest changes...' |
| 76 | + git rebase |
| 77 | + fi |
| 78 | + fi |
| 79 | +else |
| 80 | + |
| 81 | + # Clone a fresh copy |
| 82 | + echo "cloning $REPO" |
| 83 | + git_retry git clone $REPO $CLONE_DIR |
| 84 | + cd $CLONE_DIR |
| 85 | + |
| 86 | + if [ -n "$REVISION" ]; then |
| 87 | + git checkout $REVISION |
| 88 | + fi |
| 89 | +fi |
0 commit comments