import java.util.regex.Pattern def SETTINGS = "/var/jenkins_home/tools/apache-maven-3.6.0/settings.xml" def ENCODE = "ISO-8859-1" def MODULO = "adm" def TAG_SELECTOR = "UNINTIALIZED" //====================================================================================================== def build(SETTINGS, ENCODE, jdk) { if (jdk == 'JDK8.202') { withEnv(["JAVA_HOME=/var/jenkins_home/tools/hudson.model.JDK/JDK8.202"]) { sh "mvn -B -f pom.xml -s ${SETTINGS} clean deploy -DskipTests -Dfile.encoding=${ENCODE} -Dproject.build.sourceEncoding=${ENCODE}" } } else { sh "mvn -B -f pom.xml -s ${SETTINGS} clean deploy -DskipTests -Dfile.encoding=${ENCODE} -Dproject.build.sourceEncoding=${ENCODE}" } } //====================================================================================================== def gitCheckout(branch_name, url_name) { if (branch_name == null || branch_name.isEmpty()) { branch_name = "master" } SCM = checkout([ $class: 'GitSCM', branches: [[name: "*/${branch_name}"]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'AuthorInChangelog']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'admin-gitea', url: url_name]] ]) } //====================================================================================================== def geraVersao() { TAG_SELECTOR = readMavenPom file: 'pom.xml' VERSAO = TAG_SELECTOR.getVersion() VERSAO_TEXTO = "Versao: ${VERSAO}@${env.BUILD_TIMESTAMP_VERSAO}#${env.BUILD_NUMBER}" println(VERSAO_TEXTO) // writeFile file: "src/java/versionADM.info", text: VERSAO_TEXTO } //====================================================================================================== @NonCPS def verificaTicket(mensagem) { def M = mensagem =~ /#\D{2}-\d{4}/ if(M){ return M[0].substring(1) } } //====================================================================================================== @NonCPS String getChangedFilesList() { changedFiles = "" for (changeLogSet in currentBuild.changeSets) { for (entry in changeLogSet.getItems()) { for (file in entry.getAffectedFiles()) { changedFiles += "${file.editType.name} - ${file.path}\n" } } } return changedFiles } //====================================================================================================== @NonCPS String getChangedLog() { changedLog = "" for (changeLogSet in currentBuild.changeSets) { for (entries in changeLogSet.getItems()) { for (entry in entries) { changedLog += "*Commit: ${entry.commitId}\n" changedLog += "Message: ${entry.msg}\n" for (file in entry.getAffectedFiles()) { changedLog += "${file.editType.name} - ${file.path}\n" } changedLog += "Author: ${entry.author} \n" } } } return changedLog } //Valida formato do arquivo de migracao def validateFlywayMigrations() { def migrationExclusions = [/* Adiocine aqui algum nome de arquivo que nao ira entrar na regra abaixo */] sh "ls src/main/resources/db/migration/ > listsqlFiles" def fileList = readFile( "listsqlFiles" ).split( "\\r?\\n" ); //def fileList = "ls src/main/resources/db/migration".execute() def migrationPattern = "^V\\d{4}\\d{2}\\d{2}_\\d+__[A-Z_]+-\\d+\\.sql" def datePattern = Pattern.compile("\\d{4}\\d{2}\\d{2}") //doLast { for (def file in fileList) { final String migrationName = file.getName() if (!file.isFile() || migrationExclusions.contains(migrationName)) { continue } if (!migrationName.matches(migrationPattern)) { throw new Exception("Migracao '$migrationName' nao esta no padrao pattern '$migrationPattern'") } def matcher = datePattern.matcher(migrationName) if (matcher.find()) { def date = matcher.group() try { LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyyMMdd")) } catch (Exception e) { throw new Exception( "Migracao '$migrationName' tem valor de data invalido. Nao esta compativel com o padrao'yyyyMMdd'", e ) } } else { throw new Exception("Migracao '$migrationName' nao te o padrao '$datePattern'") } } //} } //compileJava.dependsOn validateFlywayMigrations //====================================================================================================== pipeline { agent any tools { maven 'mvn_3.6.0' jdk 'JDK8.202' // jdk 'OpenJDK17' } stages { stage('Info') { steps { sh ''' echo "PATH = ${PATH}" echo "M2_HOME = ${M2_HOME}" echo "DOCKER_HOST = ${DOCKER_HOST}" ''' echo "VERSÃO: #${env.BUILD_TIMESTAMP_VERSAO}#${env.BUILD_NUMBER}" } } stage('Checkout Git') { steps { cleanWs() script { try { gitCheckout('master', 'http://18.235.188.113:3000/utilidades/flyway.git') } catch (err) { echo err.getMessage() } } } } stage('Build') { steps { script { validateFlywayMigrations() if( getChangedFilesList()) { if(getChangedFilesList().contains(".sql")){ echo 'TODO: Implementar modulo_flyway do git' parallel ( "Flyway" : { b1 = build(job: "modulo_flyway", parameters: [ [$class: 'StringParameterValue', name: 'CALL', value: "ES_J2_${env.BUILD_TIMESTAMP_VERSAO}#${env.BUILD_NUMBER}"], [$class: 'StringParameterValue', name: 'MODULO_MASTER', value: "${MODULO}"], [$class: 'StringParameterValue', name: 'BUILD_MASTER', value: "${env.BUILD_NUMBER}"]], propagate: false).result if(b1 == 'FAILURE' || b1 == 'UNSTABLE') { echo "Flyway job failed" // currentBuild.result = 'UNSTABLE' } } ) } geraVersao() build(SETTINGS, ENCODE, 'JDK8.202') }else{ echo 'Não foram encontradas mudanças desde o ultimo build' currentBuild.result = 'SUCCESS' } } } } stage('Test') { steps { script { echo "Em construção" } } } } post { success { script { if( getChangedFilesList()) { //gravando e publicando as mudanças def publisher = LastChanges.getLastChangesPublisher "PREVIOUS_REVISION", "LINE", "LINE", true, true, "", "", "", "", "" publisher.publishLastChanges() def changes = publisher.getLastChanges() def textoJira = "Alterações no projeto Flyway:\n" def textoTag = "TAG: **${VERSAO_TEXTO}** \n" def changedLog = getChangedLog() def TICKET = verificaTicket(changedLog) textoJira += "${getChangedFilesList()}" for (commit in changes.getCommits()) { def commitInfo = commit.getCommitInfo() textoJira += "${commitInfo}\n\n" textoTag += "- Commit: ${commitInfo.commitId} \n"+ "- Autor: ${commitInfo.committerEmail} \n"+ "- Data: ${commitInfo.commitDate} \n"+ "- Message: ${commitInfo.commitMessage} \n\n" } //geração automatica de versão try { def giteaversion = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: '''{ "body": "'''+textoTag+'''", "draft": false, "name": "'''+VERSAO+'''", "prerelease": false, "tag_name": "'''+VERSAO+'''", "target_commitish": "master" }''', responseHandle: 'NONE', url: 'http://18.235.188.113:3000/api/v1/repos/utilidades/Flyway/releases?access_token=6231bd083b69e47f5ad34329891ed6b3128a154e', wrapAsMultipart: false } catch (err) { echo err.getMessage() } //integrando ao jira if( TICKET ){ jiraComment body: textoJira, issueKey: TICKET } else { echo 'Ticket não encontrado' } } } } } }