Donnerstag, 28. November 2013

Reading Subversion information in scripts

Sometimes it is useful to know something about a Subversion repository. The "svn diff" command for example works only with URLs. If you have to write a wrapper for "svn diff" to perform some standard tasks it is necessary to get the repository URL for a directory. This is possible with the "svn info" command. Some people propose to use grep and sed to parse the output of "svn info". But parsing with grep and sed is often not very reliable, because they search only for string patterns. This makes it for example hard to distinguish a revision number of a commit from a revision number of a entry, because they share the same label.

But Subversion provides a far better option, which makes parsing much easier. The "svn info" command can generate XML output, which can be parsed with "xmllint" and an appropriate XPath expression to get the exact information. The following Bash script is a small wrapper around "svn info --xml" and "xmllint --xpath".

#! /bin/bash
if [ "$2" ] ; then
    TARGET=$1
    shift
else
    TARGET=.
fi
svn info --xml "$TARGET" | 
if [ "$1" ] ; then
    if [ '@' = $(cut -c 1 <<<$(basename "$1")) ] ; then
        xmllint --xpath 'string('"$1"')' -
    else
        xmllint --xpath "$1"'/text()' -
    fi
    echo
else
    xmllint --format -
fi

The script makes it quite easy to get the right information:

trunk$ svninfo /info/entry/@revision
2647
trunk$ svninfo /info/entry/commit/@revision
2646
Running the script without any argument pretty prints the raw XML date. This is useful to write the exact XPath expression.

Keine Kommentare: