Skip to content

Instantly share code, notes, and snippets.

@justnom
Last active February 14, 2018 17:55
Show Gist options
  • Save justnom/5879951 to your computer and use it in GitHub Desktop.
Save justnom/5879951 to your computer and use it in GitHub Desktop.
Jenkins post commit hook. Allows building for multiple folders and support for parameters. If you don't require any parameters for the Jenkins build then just leave an empty string in the `JOBS_PARAMETERS` array.
#!/bin/bash
REPOS="$1"
REV="$2"
urlencode () {
tab="`echo -en "\x9"`"
local i="$@"
i=${i//%/%25} ; i=${i//' '/%20} ; i=${i//$tab/%09}
i=${i//!/%21} ; i=${i//\"/%22} ; i=${i//#/%23}
i=${i//\$/%24} ; i=${i//\&/%26} ; i=${i//\'/%27}
i=${i//(/%28} ; i=${i//)/%29} ; i=${i//\*/%2a}
i=${i//+/%2b} ; i=${i//,/%2c} ; i=${i//-/%2d}
i=${i//\./%2e} ; i=${i//\//%2f} ; i=${i//:/%3a}
i=${i//;/%3b} ; i=${i//</%3c} ; i=${i//=/%3d}
i=${i//>/%3e} ; i=${i//\?/%3f} ; i=${i//@/%40}
i=${i//\[/%5b} ; i=${i//\\/%5c} ; i=${i//\]/%5d}
i=${i//\^/%5e} ; i=${i//_/%5f} ; i=${i//\`/%60}
i=${i//\{/%7b} ; i=${i//|/%7c} ; i=${i//\}/%7d}
i=${i//\~/%7e}
echo "$i"
}
JENKINS_CREDENTIALS="svn:svn@"
JENKINS_SERVER="http://${JENKINS_CREDENTIALS}jenkins.mycompany.com"
# Jobs names in Jenkins
JOBS_NAMES=("MyJenkinsJobName" "MyOtherJobWithNoParameters")
# Relative directory to watch from your repository
JOBS_COMMIT_DIRS=("myproject/trunk" "myotherproject/branch/test_123")
# Parameters to pass into the Jenkins build, leave a blank string for none
JOBS_PARAMETERS=("MY_PARAM=123" "")
# Token required to authorize the build, leave blank if none required
JOBS_AUTH_TOKENS=("" "")
# Reason for the build
BUILD_REASON=$(urlencode "Post-commit hook for revision: ${REV}")
# Iterate over the Jenkins jobs
for ((i=0; i < ${#JOBS_NAMES[@]}; i++)); do
# Check if changes were made to the watched repository folder for the revision
if svnlook dirs-changed -r $REV $REPOS | grep -qEe "^${JOBS_COMMIT_DIRS[$i]}"; then
if [ -z "${JOBS_PARAMETERS[$i]}" ]
then
# Perform a build without any parameters
/usr/bin/curl -X POST "${JENKINS_SERVER}/job/${JOBS_NAMES[$i]}/build?token=${JOBS_AUTH_TOKENS[$i]}&cause=${BUILD_REASON}"
else
# Perform a parameterized build
/usr/bin/curl --data "${JOBS_PARAMETERS[$i]}" "${JENKINS_SERVER}/job/${JOBS_NAMES[$i]}/buildWithParameters?token=${JOBS_AUTH_TOKENS[$i]}&cause=${BUILD_REASON}"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment