Skip to content

Instantly share code, notes, and snippets.

@toomasr
Forked from aslakknutsen/blog.md
Created November 2, 2012 13:26
Show Gist options
  • Save toomasr/4001366 to your computer and use it in GitHub Desktop.
Save toomasr/4001366 to your computer and use it in GitHub Desktop.
Import your project's history in Sonar

When you do your first Sonar run on your project, you get a lot of new quality numbers to play with, but no trends. You only have one data set for comparison, the now picture.

Wouldn't it be nice if you could see the current trend of the project without waiting a couple of month for the 'daily/weekly' Sonar runs to fill up the data? Well, you're in luck! And if you're using Mercurial as a version system as well, this is your day. :)

In the Sonar Advanced Parameter documentation you will find a System Property called sonar.projectDate. The property let you tell Sonar when in time the running analysis was ran.

By combining this property and what your version system does best, track changes to source, we can now play back the history of the project as far as Sonar is concerned.

This little Bash script illustrates the concept. To spell out what it does in human readable form:

for each tag in the given Mercurial repository, checkout the source and run sonar, using the tag date as projectDate

#!/bin/bash

REPO=$1
START_TAG=$2

MVN_COMMAND="mvn clean install"
SONAR_COMMAND="mvn sonar:sonar -DskipTests=true -Psonar"

if [ -z "$REPO" ]; then
    echo "Missing program argument: repository"
    echo "Usage: ./sonar_history.sh repository_path [start-tag]"
    exit
fi

pushd $REPO
TAGS="`hg tags`"

OLDIFS=$IFS
IFS="
"

for tag in $TAGS 
do
    if [[ -n "$START_TAG" && "$START_TAG" > "$tag" ]] ; then
        echo "Skipping $tag (start tag $START_TAG)"
        continue
    fi
    
    STAG=$(echo $tag | cut -d' ' -f1)
    TAG_DATE=`hg log -r$STAG --style=compact | head -n1 | cut -d' ' -f7`
    
    echo "Checking out source from $TAG_DATE tagged as $tag"
    hg update -r $STAG -C

    SONAR_PROJECT_COMMAND="$SONAR_COMMAND -Dsonar.projectDate=$TAG_DATE"

    IFS=$OLDIFS
    echo "Executing Maven: $MVN_COMMAND"
    $MVN_COMMAND > /tmp/sonarifying.log 2>&1 
    echo "Executing Sonar: $SONAR_PROJECT_COMMAND"
    $SONAR_PROJECT_COMMAND > /tmp/sonarifying.log 2>&1 
done
popd

You can of course modify this script to fit your own need. Maybe you want to checkout the history pr week or pr month instead of using tags. It's up to you.

Have fun! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment