pipeline {
    agent any
    tools {
        maven 'Maven 3.8.8'
        jdk 'jdk20'
    }
    stages {
        // 拉取代码
        stage('Pull Code') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '${git_version}']], extensions: [], userRemoteConfigs: [[credentialsId: '0f6d6eaa8754e735262afa495fe2828d611fca17', url: 'http://39.105.23.186:3000/develop/digimeta-MultiSaas.git']]])
            }
        }
        // 代码静态检查
        stage('Maven Package and Sonar') {
            steps {
                withSonarQubeEnv('Sonar') {
                    sh "java -version"
                    sh "which java"
                    echo "打包子目录并进行代码检查 ${project_name}"
                    sh "mvn clean install"
                    sh "mvn -f ${project_name} clean package -e -U -Dmaven.test.skip=true -P${build_env} -Dsonar.login=admin -Dsonar.password=Digimeta@2023 sonar:sonar"
                }
            }
        }
        stage('Quality Gate') {
            steps {
                //休息10s等待结果
                sleep(10)
                script {
                    def workspace=pwd()
                    // 删除所有report报告
                    sh "find ${workspace} -name report-task.txt | xargs rm -f"
                    // 删除所有sonar锁
                    sh "find ${workspace} -name .sonar_lock | xargs rm -f"
                }
                timeout(time: 5, unit: 'MINUTES') {
                    // Parameter indicates whether to set pipeline to UNSTABLE if Quality Gate fails
                    // true = set pipeline to UNSTABLE, false = don't waitForQualityGates abortPipeline: true
                    waitForQualityGate abortPipeline: true
                }
            }
        }
        // build Docker并推送镜像仓库
        stage('Push to Registry') {
            steps {
                script {
                    def workspace=pwd()
                    // 版本
                    def tag = "0.8"
                    def ali_registry = "registry.cn-beijing.aliyuncs.com"
                    def mavenPath="/usr/share/maven"
                    if  ("${project_name}" ==  'digimeta-MultiSaas' ) {
                        echo '仅做代码检查，不打包目录'
                    } else {
                        echo  "构件微服务 ${module_name}，并推送到镜像仓库"
                        sh """
                            cd ${workspace}/${project_name}
                            docker login --username=缔智元2023 --password=digimeta@2023 ${ali_registry}
                            docker build --tag ${ali_registry}/digitalman-multisaas/${module_name}:${git_version}-${build_env} .
                            docker push ${ali_registry}/digitalman-multisaas/${module_name}:${git_version}-${build_env}
                            docker rmi ${ali_registry}/digitalman-multisaas/${module_name}:${git_version}-${build_env}
                        """
                    }
                }
            }
        }
    }
}