Getting SVN revision number into a program automatically

Viewed 31955

I have a python project under SVN, and I'm wanting to display the version number when it is run. Is there any way of doing this (such as automatically running a short script on commit which could update a version file, or querying an SVN repository in Python?)

11 Answers

Re-answering because I had trouble finding all the information for python 3. In python 3 you can use the following:

import re

revstring = '$Revision: 123 $'
revnumber = re.sub(r'\D', '', revstring)

For SVN to replace the number, the file-keyword "Revision" has to be set. you achieve this by typing the following command into a terminal:

svn propset svn:keywords Revision YOURFILE.py

Moreover, in the subversion configuration file the property enable-auto-props has to be set to yes. This should already be the case. In Tortoise SVN this config file can be accessed by clicking the button "edit" next to "subversion configuration file" in the general settings tab.

This worked for me in Python:

Get all the svn info:

svn_info = subprocess.check_output('svn info').decode("utf-8") 
print(svn_info)

Do your search and split off the number:

revisionNum = re.search("Revision:\s\d+", svn_info)
print(revisionNum.group().split(":")[1])

You could do this programmatically by parsing the output from 'svn info --xml' to an xml Element:

def get_svn_rev(dir: Union[str, Path]) -> str:
    """Get the svn revision of the given directory"""
    dir = str(dir)
    svn_info_cmd = ['svn', 'info', '--xml', dir]
    print(' '.join(svn_info_cmd))
    svn_info_process = subprocess.run(svn_info_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if svn_info_process.returncode:
        eprint(svn_info_process.stderr.decode().strip())
        raise subprocess.CalledProcessError(returncode=svn_info_process.returncode, cmd=svn_info_cmd,
                                            output=svn_info_process.stdout,
                                            stderr=svn_info_process.stderr)
    else:
        info = ElementTree.fromstring(svn_info_process.stdout.decode().strip())
        entry = info.find('entry')
        revision = entry.get('revision')

    return revision
Related