sonar-validator
Version:
SonarQube Quality Gateway validator
126 lines (99 loc) • 3.26 kB
JavaScript
const propertiesReader = require('properties-reader');
const axios = require('axios')
// Sonar-Scanner creates a .scannerwork folder with the information on the task carried
const properties = propertiesReader(`${process.cwd()}/.scannerwork/report-task.txt`);
// Read the CE URL from the properties file
const CE_TASK_URL = properties.get('ceTaskUrl');
const SONAR_LOGIN = process.env.SONAR_LOGIN;
const SONARQUBE_URL = process.env.SONARQUBE_URL;
const SKIP_SONAR = process.env.SKIP_SONAR || false;
// Convert the token to base64 string
const tokenBase64 = Buffer.from(`${SONAR_LOGIN}:`).toString('base64');
/**
* Http client
* @param {*} url
* @param {*} headers
* @returns
*/
const getResponse = (url, headers) => {
return axios.get(url, {
headers: {...headers}
})
.then((response) => {
return [null, response.data]
})
.catch((error) => {
return [error, null]
});
};
/**
*
* @param {string} word in the format new_security_rating
* @returns {string} in the first word captalized form
*/
const getCaptalizedWord = (word) => {
if (!word) return '';
return word.split('_').map((str) => str[0].toUpperCase() + str.substr(1, str.length)).join(' ');
}
const getLogColor = (status) => {
if (status === 'ERROR' || status === 'FAILED') {
return `\x1b[31m${status}\x1b[0m`;
}
return `\x1b[32m${status}\x1b[0m`;
};
/**
* Return a basic logger wrapping the console log
* @returns
*/
const getLogger = () => {
const logger = {};
logger.info = console.log;
logger.error = console.error;
logger.warn = console.warn;
return logger;
}
// General logger
const LOGGER = getLogger();
// Auth header
const authHeader = {
Authorization: `Basic ${tokenBase64}`
}
const getSonarTaskInformation = () => {
return getResponse(CE_TASK_URL, authHeader);
}
const getQualityGateInformation = (analysisId) => {
const sonarReportUrl = `${SONARQUBE_URL}/api/qualitygates/project_status?analysisId=${analysisId}`;
return getResponse(sonarReportUrl, authHeader);
};
// Main code
if (SKIP_SONAR) {
LOGGER.info('Skipping sonar')
return;
}
getSonarTaskInformation()
.then(([error, response]) => {
if (error) {
console.error(error);
process.exit(1);
}
// Extract the analysisId from the response to get quality gate information
const analysisId = response.task.analysisId;
getQualityGateInformation(analysisId)
.then(([err, sonarReport]) => {
if(err) {
LOGGER.error(err)
process.exit(1);
}
const projectStatus = sonarReport.projectStatus;
const qualityGatewayPassed = projectStatus.status !== 'ERROR';
LOGGER.info('Sonar Report ---------------\n');
projectStatus.conditions.forEach((condition) => {
LOGGER.info(getCaptalizedWord(condition['metricKey']), getLogColor(condition['status']));
});
LOGGER.info(`\nQuality Gateway ${getLogColor(qualityGatewayPassed ? 'PASSED' : 'FAILED')}\n`);
if(!qualityGatewayPassed) {
// Fail the pipelie state if the quality gate failed
process.exit(1);
}
})
});