pipeline {
agent any
environment {
ACCESS_TOKEN = credentials('ACCESS_TOKEN')
API_BASE = 'https://api.codeant.ai'
}
stages {
stage('Test Coverage') {
steps {
script {
// Extract repository information
def repoUrl = env.GIT_URL
def repoName = ""
if (repoUrl && repoUrl.contains('github.com')) {
repoName = repoUrl.replaceAll(/.*github\.com[\/:]([^\/]+\/[^\/]+)\.git.*/, '$1')
} else if (repoUrl && repoUrl.contains('gitlab.com')) {
repoName = repoUrl.replaceAll(/.*gitlab\.com[\/:]([^\/]+\/[^\/]+)\.git.*/, '$1')
} else {
// Fallback: use a configured value or extract from job name
repoName = "org/repo_name" // Replace with your actual repo
}
def branchName = env.GIT_BRANCH.replaceAll(/^origin\//, '')
echo "Running tests and generating coverage"
sh """
# Activate virtual environment if exists
if [ -f .venv/bin/activate ]; then
source .venv/bin/activate
fi
# Install coverage tools
pip install coverage pytest
# Run tests with coverage
coverage run -m pytest tests/
coverage xml -o coverage.xml
# Display coverage report
cat coverage.xml
"""
echo "Fetching coverage-upload script"
sh """
curl -sS -X GET "${API_BASE}/pr/analysis/coverage/script/get" \\
--output upload_coverage.sh.b64
"""
echo " Making script executable"
sh """
base64 -d upload_coverage.sh.b64 > upload_coverage.sh
chmod +x upload_coverage.sh
"""
echo "Uploading coverage and setting status"
sh """
bash upload_coverage.sh \\
-t "${ACCESS_TOKEN}" \\
-r "${repoName}" \\
-c "${env.GIT_COMMIT}" \\
-f coverage.xml \\
-p github \\
-b "${branchName}"
"""
}
}
post {
always {
// Archive coverage report
archiveArtifacts artifacts: 'coverage.xml', allowEmptyArchive: true
// Clean up temporary files
sh """
rm -f upload_coverage.sh upload_coverage.sh.b64
"""
}
success {
echo " Coverage report uploaded successfully"
}
failure {
echo "Failed to upload coverage report"
}
}
}
}
}