SVN pre-commit hooks for YAML and XML validation

352 Views Asked by At

I've Been asked to check for XML and YAML files syntax during the commit process, basically the task is that whenever a developer commit contains yaml or xml files, svn pre-commit hook needs to run a check wether they're valid (syntax and format wise).

I know that on the svn server side, we have hooks directory that contains all the hooks, and in order to activate one of them we just need to eliminate the .tmpl extension so it could run whenever an attempt to commit changes to remote repository is taking place.

What I can't find is the hook's logic (code) of detecting the XML, YAML files being committed and validating them so the commit could pass.

Down below is the default content of pre-commit hook file that's supposedly will need some more logic of knowing which file is which and then check wether they're ok or not.

pre-commit.tmpl

 REPOS="$1"
 TXN="$2"

 # Make sure that the log message contains some text.
 SVNLOOK=/usr/local/Cellar/subversion/1.14.1_4/bin/svnlook
 $SVNLOOK log -t "$TXN" "$REPOS" | \
 grep "[a-zA-Z0-9]" > /dev/null || exit 1

 # Check that the author of this commit has the rights to perform
 # the commit on the files and directories being modified.
 commit-access-control.pl "$REPOS" "$TXN" commit-access-control.cfg || exit 1

 # All checks passed, so allow the commit.
 exit 0

The script above needs more code for detecting xml and yaml files + syntax validation logic. SVNLOOK needs to pass a list of files edited or added in a commit so we could do check them by the python command.

This is linux command line that I think could go inside the pre-commit hook script

python -c 'import yaml, sys; yaml.safe_load(sys.stdin)' < cfg.yaml.

Thank you in advance

1

There are 1 best solutions below

0
Siddharth Kaul On

Using Python script this is pretty simple. Here is a template for python script that you can use. Just replace the comment with your check and based on status you can either reject the commit or accept it.

import os
import sys
from subprocess import check_output
import re
import yaml

def check_fileType(changed_list):
    """Perform File Type Check here
    """
    error = 0
    stream = sys.stderr # Use this stream if you want to debug
    for path in changed_list:
        match = re.search(r".yaml$",path)
        if match:
            # Do YAML Check here for each path
            # if YAML Check fails set error to 1
            # if no YAML error then 0 will be returned
            error = 1
    return error;
def run(argv):
    repo = argv[1]
    tranx = argv[2]
    cmd = ('svnlook','changed',repo,'-t',tranx)
    out = check_output(cmd)
    changed_paths = [ line[4:] for line in out.split('\n') if len(line) > 4 ]
    status = check_fileType(changed_paths)
    if status:
        sys.exit(1) # Non zero exit indicates error