Jenkins拉取Git不同分支
Jenkins拉取Git不同分支,执行后续任务,自定义任务,我这里是调用Matlab,结束后如果其中有失败的stage,就发邮件通知Git最近的提交者。
def sanitizeEmail(String email) {
// Remove any characters that are not valid in email addresses (alphanumeric, '.', '@', '_', and '-')
return email.replaceAll("[^a-zA-Z0-9@._-]", "")
}
pipeline {
agent {
node{
label "xxxx" //从节点标签,可以不填
}
}
parameters {
string(name: 'ModelName_Jenkins', defaultValue: 'xxx', description: 'Enter Model Name')
string(name: 'Folder_Name_To_CloneRepo', defaultValue: 'C:\\path\\xxxx', description: 'Folder to Clone Repository')
string(name: 'Receiver_Email', defaultValue: 'xxx@yyy.com', description: 'Add some receiver email adress')
gitParameter(name: 'GitBranchName',
type: 'PT_BRANCH',
branchFilter: 'origin/(.*)',
defaultValue: 'BRANCH',
description: 'Select Git Branch')
}
environment {
GIT_REPO_URL = 'xxx.gitURL'
WORKSPACE_DIR = "${params.Folder_Name_To_CloneRepo}" // Keep as Windows path with backslashes
MODEL_NAME = "${params.ModelName_Jenkins}"
MATLAB_PATH = "C:\\Program Files\\MATLAB\\R2019b"
BUILD_DIR = "${params.ModelName_Jenkins}_Build"
CODEGEN_SCRIPT = 'xxx.m'
STARTUP_SCRIPT = "${params.Folder_Name_To_CloneRepo}\\xxx.m"
GIT_CREDS_ID = 'xxxCredential'
ZIP_FILE = "${WORKSPACE_DIR}\\Models\\RootModel\\RootModel_JEEP_MABX\\Model\\FusaModels\\${MODEL_NAME}_CodeFiles.zip"
}
stages {
stage('Check and Clone Repository') {
steps {
script {
if (fileExists("${WORKSPACE_DIR}\\.git")) {
echo "Repository already cloned. Pulling latest changes."
dir("${WORKSPACE_DIR}") {
bat "git reset --hard" // Discards any local changes
bat "git clean -fdx"
bat "git checkout ${params.GitBranchName}"
bat "git pull --rebase=false origin --prune --verbose"
bat 'git submodule update --init --recursive'
}
} else {
echo "Cloning repository."
dir("${WORKSPACE_DIR}") {
git branch: "${params.GitBranchName}",
credentialsId: "${GIT_CREDS_ID}",
url: "${GIT_REPO_URL}"
bat 'git submodule update --init --recursive'
}
}
}
}
}
stage('Open MATLAB and Generate Code') {
steps {
script {
bat """
"${MATLAB_PATH}\\bin\\matlab.exe" -batch "addpath(genpath('${WORKSPACE_DIR}')); ModelName_Jenkins='${MODEL_NAME}'; EmbdCodegen_Jenkins=true; run('${STARTUP_SCRIPT}'); run('${CODEGEN_SCRIPT}'); exit"
"""
}
}
}
stage('Check ZIP File and Move to Artifacts') {
steps {
script {
def zipFilePath = "${WORKSPACE_DIR}\\Models\\RootModel\\RootModel_JEEP_MABX\\Model\\FusaModels\\${MODEL_NAME}_CodeFiles.zip"
def artifactsDir = "${env.WORKSPACE}\\artifacts" // Create artifacts folder inside current pipeline workspace
def windowsDirPath = "${params.Folder_Name_To_CloneRepo}\\Models\\RootModel\\RootModel_JEEP_MABX\\Model\\FusaModels"
// Clean up the 'artifacts' folder if it exists
echo "Cleaning up artifacts folder: ${artifactsDir}"
bat "if exist \"${artifactsDir}\" rd /s /q \"${artifactsDir}\""
// Recreate the 'artifacts' folder
bat "mkdir \"${artifactsDir}\""
echo "Listing files in directory: ${windowsDirPath}"
bat "dir \"${windowsDirPath}\""
// Check if the ZIP file exists and move it to artifacts folder
if (fileExists(zipFilePath)) {
echo "ZIP file found at: ${zipFilePath}"
bat "move \"${zipFilePath}\" \"${artifactsDir}\""
} else {
echo "ZIP file not found at: ${zipFilePath}"
}
}
}
}
}
post {
success {
script {
echo "Build successful"
}
}
failure {
script {
echo "Build failed"
}
}
always {
// Send email if the ZIP file does not exist
script {
//remove frist two chars
def removeFirstTwoChars = { String str ->
return str.length() > 2 ? str.substring(2) : ''
}
if (!fileExists("${env.WORKSPACE}\\artifacts\\${MODEL_NAME}_CodeFiles.zip")) {
dir("${WORKSPACE_DIR}"){
def gitLog = bat(script: "git log -1 --pretty=format:'%%ae'", returnStdout: true).trim()
// remove unsupported characters and path ,提取Email地址
gitLog = gitLog.replaceAll(".*'(.*)'.*", "\$1")
// Sanitize email addresses to remove unsupported characters
def sanitizedRecipient = sanitizeEmail(gitLog)
def resultString = removeFirstTwoChars(sanitizedRecipient)
echo "${resultString}"
echo "Sending email due to missing CodeFiles.zip"
emailext (
subject: "Compilation Error Notification",
body: "The MATLAB model compilation has failed. Please check the logs.",
to: " ${resultString};${Receiver_Email}"
)
}
}
}
// Archive artifacts from the 'artifacts' folder
archiveArtifacts artifacts: 'artifacts/*.zip', allowEmptyArchive: true
}
}
}