Bash Job Clone script

From Eclipsepedia

Jump to: navigation, search

This is a similar version of the Ant Job Clone script but is done as a bash script and is useful for agile iterative development where each week/month a new iteration is created for all of the projects and thus a new subversion branch is created so we need hudson to point at that new branch. The only real dependency is on curl.

#!/bin/bash

# Copyright (c) 2010, Jon Scott Stevens
# This script will add a new branch for all of our projects to hudson based
# on an existing set of projects. This script can be run multiple times without
# causing duplicate projects to be created. If the from project doesn't exist,
# then the script won't do anything.
#
# ex: hudson_add_branch.sh iteration-0001 iteration-0002

HUDSON_URL="http://hudson"
USERNAME=hudson
PASSWORD=nosduh
PROJECTS="acdc efgh llkiw"

TMP_DIR="/tmp/hudsonJobs"
CURL="curl --user $USERNAME:$PASSWORD -s "

FROM_BRANCH=$1
TO_BRANCH=$2
if [ -z $FROM_BRANCH ]; then
	echo "Please specify a from branch, such as iteration-0001"
	exit
fi
if [ -z $TO_BRANCH ]; then
	echo "Please specify a to branch, such as iteration-0002"
	exit
fi

mkdir -p $TMP_DIR

for i in $PROJECTS
do
	FROM_PROJECT="$i-$FROM_BRANCH"
	TO_PROJECT="$i-$TO_BRANCH"

	FROM_CONFIG_URL="$HUDSON_URL/job/$FROM_PROJECT/config.xml"
	TO_CONFIG_URL="$HUDSON_URL/job/$TO_PROJECT/config.xml"

	FROM_CONFIG_XML="$TMP_DIR/$FROM_PROJECT-config.xml"
	TO_CONFIG_XML="$TMP_DIR/$TO_PROJECT-config.xml"

	# check for existing job
	`$CURL -f -o /dev/null $TO_CONFIG_URL`
	if [ $? -eq 0 ]; then
		echo "WARN: $TO_PROJECT already exists on the hudson server. No action taken."
		continue
	fi
	# download the config.xml for the job, continue if it doesn't exist
	`$CURL -o $FROM_CONFIG_XML $FROM_CONFIG_URL`
	grep "Error 404" "$FROM_CONFIG_XML" > /dev/null
	if [ $? -eq 0 ]; then
		echo "FAIL: $FROM_CONFIG_URL is not a valid project url"
		continue
	fi

	# replace the branch name in the config.xml file.
	sed "s/$FROM_BRANCH/$TO_BRANCH/g" "$FROM_CONFIG_XML" > "$TO_CONFIG_XML"

	# create a new job based on the existing job
	`$CURL -o /dev/null --data " " "$HUDSON_URL/createItem?name=${TO_PROJECT}&mode=copy&from=${FROM_PROJECT}"`

	# upload new job data
	`$CURL -o /dev/null --data "@$TO_CONFIG_XML" "$HUDSON_URL/job/$TO_PROJECT/config.xml"`		

	# enable the job, there seems to be a bug where we need to first disable and then enable
	`$CURL -o /dev/null --data disable "$HUDSON_URL/job/$TO_PROJECT/disable"`
	`$CURL -o /dev/null --data enable "$HUDSON_URL/job/$TO_PROJECT/enable"`
done

rm -rf $TMP_DIR