DEV Community

Dennis Zhang
Dennis Zhang

Posted on

Jenkins Pipeline

pipeline {
    agent any

    environment {
        // 假设生成的文件名会以时间戳为基础
        REPORT_PATH = "report/build_report_${env.BUILD_ID}.html"  // 动态生成文件名
    }

    stages {
        stage('Build') {
            steps {
                script {
                    // 使用动态生成的文件路径生成报告
                    sh "echo 'Build report content' > ${env.REPORT_PATH}"
                    echo "Report generated at: ${env.REPORT_PATH}"
                }
            }
        }
 stage('Archive') {
            steps {
                // 归档构建过程中生成的文件
                archiveArtifacts artifacts: 'build/output.zip', allowEmptyArchive: true
            }
        }
        stage('Check Report Existence') {
            steps {
                script {
                    // 检查动态生成的报告文件是否存在
                    def fileExists = sh(script: "test -f ${env.REPORT_PATH} && echo 'yes' || echo 'no'", returnStdout: true).trim()

                    if (fileExists == "yes") {
                        echo "Report file exists at: ${env.REPORT_PATH}. Proceeding to send email."
                    } else {
                        error "Report file does not exist at: ${env.REPORT_PATH}. Aborting email sending."
                    }
                }
            }
        }

        stage('Send Email') {
            steps {
                script {
                    // 使用动态路径发送邮件
                    def fileExists = sh(script: "test -f ${env.REPORT_PATH} && echo 'yes' || echo 'no'", returnStdout: true).trim()

                    if (fileExists == "yes") {
                        emailext (
                            subject: "Build Report - ${env.BUILD_ID}",
                            body: "Please find the attached build report.",
                            attachmentsPattern: "${env.REPORT_PATH}"  // 使用动态路径
                        )
                    } else {
                        echo "Report file not found, skipping email sending."
                    }
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)