Skip to content

Instantly share code, notes, and snippets.

@cjbarker
Created February 8, 2018 22:45
Show Gist options
  • Save cjbarker/142c8b0fab22a9c382e35d7dcf6dd55d to your computer and use it in GitHub Desktop.
Save cjbarker/142c8b0fab22a9c382e35d7dcf6dd55d to your computer and use it in GitHub Desktop.
Validate GitLab YAML via Linting API
#!/bin/bash
# ##########################################################################
# Validate GitLab CI YAML (VGLCIYML) file via GL linter API
#
# Usage: vglciyml <yaml-file>
#
# echo $?
#
# Exit code of 0 denotes success. Non zero exit code denotes failure.
# Error message associated with non zero exit code sent to STDERR.
#
# Example: ./vglciyml.sh .gitlab-ci.yml
# ##########################################################################
function echoerr {
echo "$@" 1>&2;
}
function cmd_exist() {
which $1 > /dev/null
if [ $? -ne 0 ]; then
echoerr "${1} not installed - required for script"
exit 2
fi
}
if [ $# -ne 1 ]; then
echoerr "GitLab YAML file required as command line param: ${0} <yaml-file>"
exit 1
fi
cmd_exist perl
cmd_exist python
python -c 'import yaml' 2> /dev/null
if [ $? -ne 0 ]; then
echoerr "Python module 'yaml' is not installed - required for script. 'pip install yaml'"
exit 4
fi
yml_file=$1
# validate file exists
if [ ! -f ${yml_file} ]; then
echoerr "Invalid file ${yml_file}"
exit 5
fi
# Convert YAML to JSON
json=`python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < ${yml_file}`
# escape quotes
json_content=$(echo $json | perl -pe 's/(?<!\\)"/\\"/g')
# Added object contect for GitLab linter
json_content='{"content": "'${json_content}'"}'
result=$(echo ${json_content} | curl -d @- --header "Content-Type: application/json" https://gitlab.com/api/v4/ci/lint 2>/dev/null)
# check if succeeded
echo $result | grep '"errors":\[\]'
if [ $? -ne 0 ]; then
# Failed show results
echoerr $result
#echo $json
exit 6
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment