Skip to content

Instantly share code, notes, and snippets.

@brunocrt
Forked from amaksoft/Jenkinsfile
Created February 22, 2019 14:03
Show Gist options
  • Save brunocrt/67eb2c96bda1a28d4583e31825235d0f to your computer and use it in GitHub Desktop.
Save brunocrt/67eb2c96bda1a28d4583e31825235d0f to your computer and use it in GitHub Desktop.

Revisions

  1. @amaksoft amaksoft revised this gist Sep 21, 2016. 1 changed file with 8 additions and 6 deletions.
    14 changes: 8 additions & 6 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -77,10 +77,12 @@ def pushSSH(Map args) {
    return;
    }

    if (username == null || email == null || creds_ids == null || branch == null)
    error "Error. Incorrect value set { username = ${username}, email = ${email}, credentials = ${creds_ids}, git branch = ${branch} }";
    if (branch == null)
    error "Error. Invalid value: git branch = ${branch}";

    if(config) {
    if (username == null || email == null || creds_ids == null)
    error "Error. Invalid value set: { username = ${username}, email = ${email}, credentials = ${creds_ids} }";
    sh """ git config push.default simple
    git config user.name \"${username}\"
    git config user.email \"${email}\"
    @@ -89,13 +91,13 @@ def pushSSH(Map args) {

    sshagent(creds_ids) {
    if (files != null) {
    sh """git add . && git commit -m \"${commitMsg}\" || true
    git push origin HEAD:refs/heads/${branch} || true
    sh """ git add . && git commit -m \"${commitMsg}\" || true
    git push origin HEAD:refs/heads/${branch} || true
    """
    }
    if (tagName != null) {
    sh """git tag -fa \"${tagName}\" -m \"${commitMsg}\"
    git push -f origin refs/tags/${tagName}:refs/tags/${tagName}
    sh """ git tag -fa \"${tagName}\" -m \"${commitMsg}\"
    git push -f origin refs/tags/${tagName}:refs/tags/${tagName}
    """
    }
    }
  2. @amaksoft amaksoft revised this gist Sep 21, 2016. 1 changed file with 7 additions and 4 deletions.
    11 changes: 7 additions & 4 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -60,10 +60,13 @@ def pushSSH(Map args) {
    String files = args.files
    String branch = args.branch != null ? args.branch : env.BRANCH_NAME;
    List<String> creds_ids = args.creds != null ? args.creds : env.J_CREDS_IDS.tokenize(" ");
    boolean config;
    try {
    config = args.config != null ? args.config : Boolean.parseBoolean(env.J_GIT_CONFIG);
    }catch (exc) {
    boolean config; // Boolean.parseBoolean() is forbidden in this DSL
    if(args.config != null)
    config = args.config
    else if (env.J_GIT_CONFIG.toLowerCase() == "true") {
    config = true
    }else {
    echo "git config = ${config}, J_GIT_CONFIG = ${env.J_GIT_CONFIG}, assuming false"
    config = false;
    }
    String username = args.username != null ? args.username : env.J_USERNAME;
  3. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -38,6 +38,7 @@ def gitLib
    timestampedNode ("AndroidBuilder") {
    stage ("Checkout") {
    checkout scm
    sh "chmod a+x ./gradlew"
    gitLib = load "git_push_ssh.groovy"
    }

  4. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 4 additions and 3 deletions.
    7 changes: 4 additions & 3 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -99,15 +99,16 @@ stage ('Release') {
    input 'Do we release this build?'
    node {
    echo "Push Release tag"
    def date = sh(returnStdout: true, script: 'date -u +%Y%m%d').trim()// = new Date().format('yyyyMMdd') // apparently we can't use Date here, not a problem
    gitLib.pushSSH(tagName: "release-${date}", commitMsg: "Jenkins promoted");
    // Do your release stuff
    def date = sh(returnStdout: true, script: 'date -u +%Y%m%d').trim()// = new Date().format('yyyyMMdd') // apparently we can't use Date here, not a problem
    gitLib.pushSSH(tagName: "release-${date}", commitMsg: "Jenkins promoted");
    // Do your release stuff
    }
    } catch (Exception e) {
    echo "Release cancelled"
    }
    }

    // To send emails to everyone relevant to this build (Requires Email-ext plugin)
    def sendEmails() {
    emailext body: "See ${env.BUILD_URL}",
    recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
  5. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 6 additions and 6 deletions.
    12 changes: 6 additions & 6 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -73,9 +73,9 @@ timestampedNode ("AndroidBuilder") {

    // Build the app
    sh "./gradlew clean"
    sh "./gradlew assembleDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleRelease ${env.COMMON_BUILD_ARGS}"
    sh """./gradlew assembleDebug ${env.COMMON_BUILD_ARGS}
    ./gradlew assembleRelease ${env.COMMON_BUILD_ARGS}
    """
    }

    stage('Save artifacts and publish') {
    @@ -88,9 +88,9 @@ timestampedNode ("AndroidBuilder") {
    }

    stage ('Crashlytics register') {
    sh "./gradlew crashlyticsUploadDistributionDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionRelease ${env.COMMON_BUILD_ARGS}"
    sh """./gradlew crashlyticsUploadDistributionDebug ${env.COMMON_BUILD_ARGS}
    ./gradlew crashlyticsUploadDistributionRelease ${env.COMMON_BUILD_ARGS}
    """
    }
    }

  6. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -31,7 +31,7 @@
    * To keep things going while we wait for official Git Publish support for pipelines (https://issues.jenkins-ci.org/browse/JENKINS-28335)
    *
    * Example call (Inline values):
    * gitPushSSH(branch: "master", commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".", config: true, username: "Jenkins CI", email: "jenkins-ci@example.com");
    * pushSSH(branch: "master", commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".", config: true, username: "Jenkins CI", email: "jenkins-ci@example.com");
    *
    * Example call (Environment variables):
    * env.BRANCH_NAME = "mycoolbranch"// BRANCH_NAME is predefined in multibranch pipeline job
    @@ -40,7 +40,7 @@
    * env.J_EMAIL = "jenkins-ci@example.com"
    * env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id from Jenkins (Does anyone know a way to reference them by name rather than by id?)
    * ...
    * gitPushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".");
    * pushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".");
    *
    * @param args Map with followinf parameters:
    * commitMsg : (String) commit message
  7. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 68 additions and 67 deletions.
    135 changes: 68 additions & 67 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -30,7 +30,8 @@
    env.J_USERNAME = "Jenkins CI"
    env.J_EMAIL = "[email protected]"
    env.J_GIT_CONFIG = "true"
    env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id from Jenkins (Does anyone know a way to reference them by name rather than by id?)
    // Use credentials id from Jenkins (Does anyone know a way to reference them by name rather than by id?)
    env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3'

    def gitLib

    @@ -41,101 +42,101 @@ timestampedNode ("AndroidBuilder") {
    }

    stage ("Build") {
    // Check environment (We define ANDROID_HOME in node settings)
    if (env.ANDROID_HOME == null || env.ANDROID_HOME == "") error "ANDROID_HOME not defined"
    if (env.JAVA_HOME == null || env.JAVA_HOME == "") error "JAVA_HOME not defined"
    // Check environment (We define ANDROID_HOME in node settings)
    if (env.ANDROID_HOME == null || env.ANDROID_HOME == "") error "ANDROID_HOME not defined"
    if (env.JAVA_HOME == null || env.JAVA_HOME == "") error "JAVA_HOME not defined"

    // Default parameters (In case file is unreadable or missing)
    def d = [versionName: 'unversioned', versionCode: '1']
    // Read properties from file (Right now we only keep versionName and VersionCode there)
    HashMap<String, Object> props = readProperties defaults: d, file: 'gradle.properties'
    // Optional user input to override parameters
    def userInput
    try {
    timeout(time: 60, unit: 'SECONDS') {
    userInput = input( id:'userInput', message: 'Override build parameters?', parameters: [
    string(defaultValue: props.versionName, description: 'App version (without build number)', name: 'versionName'),
    string(defaultValue: props.versionCode, description: 'Version code (for GooglePlay Store)', name: 'versionCode')
    ])
    logOverrides(userInput, props, "manual_override.log")
    props.putAll(userInput)
    echo("Parameters entered : ${userInput.toString()}")
    }
    } catch (Exception e) {
    echo "User input timed out or cancelled, continue with default values"
    }
    // Change build name to current app version
    currentBuild.displayName = "${props.versionName}.${env.BUILD_NUMBER}"
    // Common build arguments
    env.COMMON_BUILD_ARGS = " -PBUILD_NUMBER=${env.BUILD_NUMBER} -PBRANCH_NAME=${env.BRANCH_NAME}" +
    " -PversionName=${props.versionName} -PversionCode=${props.versionCode}"
    // Default parameters (In case file is unreadable or missing)
    def d = [versionName: 'unversioned', versionCode: '1']
    // Read properties from file (Right now we only keep versionName and VersionCode there)
    HashMap<String, Object> props = readProperties defaults: d, file: 'gradle.properties'
    // Optional user input to override parameters
    def userInput
    try {
    timeout(time: 60, unit: 'SECONDS') {
    userInput = input( id:'userInput', message: 'Override build parameters?', parameters: [
    string(defaultValue: props.versionName, description: 'App version (without build number)', name: 'versionName'),
    string(defaultValue: props.versionCode, description: 'Version code (for GooglePlay Store)', name: 'versionCode')
    ])
    logOverrides(userInput, props, "manual_override.log")
    props.putAll(userInput)
    echo("Parameters entered : ${userInput.toString()}")
    }
    } catch (Exception e) {
    echo "User input timed out or cancelled, continue with default values"
    }
    // Change build name to current app version
    currentBuild.displayName = "${props.versionName}.${env.BUILD_NUMBER}"
    // Common build arguments
    env.COMMON_BUILD_ARGS = " -PBUILD_NUMBER=${env.BUILD_NUMBER} -PBRANCH_NAME=${env.BRANCH_NAME}" +
    " -PversionName=${props.versionName} -PversionCode=${props.versionCode}"

    // Build the app
    sh "./gradlew clean"
    // Build the app
    sh "./gradlew clean"
    sh "./gradlew assembleDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleRelease ${env.COMMON_BUILD_ARGS}"
    }

    stage('Save artifacts and publish') {
    // Save build results
    step([$class: 'ArtifactArchiver', artifacts: "**/*.apk", excludes: "**/*unaligned.apk", fingerprint: true])
    // Push changes and tag
    gitLib.pushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}",
    tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}", files: ".", config: true);
    sendEmails()
    // Save build results
    step([$class: 'ArtifactArchiver', artifacts: "**/*.apk", excludes: "**/*unaligned.apk", fingerprint: true])
    // Push changes and tag
    gitLib.pushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}",
    tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}", files: ".", config: true);
    sendEmails();
    }

    stage ('Crashlytics register') {
    sh "./gradlew crashlyticsUploadDistributionDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionRelease ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionRelease ${env.COMMON_BUILD_ARGS}"
    }
    }

    stage ('Release') {
    try {
    input 'Do we release this build?'
    node {
    echo "Push Release tag"
    def date = sh(returnStdout: true, script: 'date -u +%Y%m%d').trim()// = new Date().format('yyyyMMdd') // apparently we can't use Date here, not a problem
    gitLib.pushSSH(tagName: "release-${date}", commitMsg: "Jenkins promoted");
    // Do your release stuff
    }
    } catch (Exception e) {
    echo "Release cancelled"
    try {
    input 'Do we release this build?'
    node {
    echo "Push Release tag"
    def date = sh(returnStdout: true, script: 'date -u +%Y%m%d').trim()// = new Date().format('yyyyMMdd') // apparently we can't use Date here, not a problem
    gitLib.pushSSH(tagName: "release-${date}", commitMsg: "Jenkins promoted");
    // Do your release stuff
    }
    } catch (Exception e) {
    echo "Release cancelled"
    }
    }

    def sendEmails() {
    emailext body: "See ${env.BUILD_URL}",
    recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
    subject: "Jenkins Build Successful",
    to: "[email protected]";
    emailext body: "See ${env.BUILD_URL}",
    recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
    subject: "Jenkins Build Successful",
    to: "[email protected]";
    }

    // To log manual overrides
    @NonCPS
    def logOverrides(def ov_map, def orig_map, def filename) {
    def header = "# Build ${env.BUILD_NUMBER}-${env.BRANCH_NAME} manual parameters override: ";
    def headWritten = false;
    ov_map.each{ k, v ->
    if( orig_map[k] != v ) {
    if (!headWritten) {
    sh "echo \"${header}\" >> ${filename}"; // apparently we are not allowed to use File.write() in this DSL
    headWritten = true;
    };
    sh "echo \"${k}=${v}\" >> ${filename}"
    }
    def header = "# Build ${env.BUILD_NUMBER}-${env.BRANCH_NAME} manual parameters override: ";
    def headWritten = false;
    ov_map.each{ k, v ->
    if( orig_map[k] != v ) {
    if (!headWritten) {
    sh "echo \"${header}\" >> ${filename}"; // apparently we are not allowed to use File.write() in this DSL
    headWritten = true;
    };
    sh "echo \"${k}=${v}\" >> ${filename}"
    }
    }
    }

    // Taken from jenkinsci/jenkins project (https://github.com/jenkinsci/jenkins/blob/master/Jenkinsfile)
    // to add timestamps to logs
    def timestampedNode(String label = "master", Closure body) {
    node(label) {
    wrap([$class: 'TimestamperBuildWrapper']) {
    body.call();
    }
    node(label) {
    wrap([$class: 'TimestamperBuildWrapper']) {
    body.call();
    }
    }
    }
  8. @amaksoft amaksoft revised this gist Sep 20, 2016. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -34,7 +34,7 @@ env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id f

    def gitLib

    node ("AndroidBuilder") {
    timestampedNode ("AndroidBuilder") {
    stage ("Checkout") {
    checkout scm
    gitLib = load "git_push_ssh.groovy"
    @@ -45,7 +45,7 @@ node ("AndroidBuilder") {
    if (env.ANDROID_HOME == null || env.ANDROID_HOME == "") error "ANDROID_HOME not defined"
    if (env.JAVA_HOME == null || env.JAVA_HOME == "") error "JAVA_HOME not defined"

    // Default parameters (In case file is corrupted)
    // Default parameters (In case file is unreadable or missing)
    def d = [versionName: 'unversioned', versionCode: '1']
    // Read properties from file (Right now we only keep versionName and VersionCode there)
    HashMap<String, Object> props = readProperties defaults: d, file: 'gradle.properties'
    @@ -62,7 +62,7 @@ node ("AndroidBuilder") {
    echo("Parameters entered : ${userInput.toString()}")
    }
    } catch (Exception e) {
    echo "User input timed out, continue with default values"
    echo "User input timed out or cancelled, continue with default values"
    }
    // Change build name to current app version
    currentBuild.displayName = "${props.versionName}.${env.BUILD_NUMBER}"
    @@ -81,7 +81,7 @@ node ("AndroidBuilder") {
    // Save build results
    step([$class: 'ArtifactArchiver', artifacts: "**/*.apk", excludes: "**/*unaligned.apk", fingerprint: true])
    // Push changes and tag
    gitLib.gitPushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}",
    gitLib.pushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}",
    tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}", files: ".", config: true);
    sendEmails()
    }
  9. @amaksoft amaksoft revised this gist Sep 20, 2016. 2 changed files with 87 additions and 17 deletions.
    69 changes: 62 additions & 7 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -30,11 +30,11 @@
    env.J_USERNAME = "Jenkins CI"
    env.J_EMAIL = "[email protected]"
    env.J_GIT_CONFIG = "true"
    env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3'
    env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id from Jenkins (Does anyone know a way to reference them by name rather than by id?)

    def gitLib

    node ("AndroidBouilder") {
    node ("AndroidBuilder") {
    stage ("Checkout") {
    checkout scm
    gitLib = load "git_push_ssh.groovy"
    @@ -47,8 +47,23 @@ node ("AndroidBouilder") {

    // Default parameters (In case file is corrupted)
    def d = [versionName: 'unversioned', versionCode: '1']
    // Read properties file
    def props = readProperties defaults: d, file: 'gradle.properties'
    // Read properties from file (Right now we only keep versionName and VersionCode there)
    HashMap<String, Object> props = readProperties defaults: d, file: 'gradle.properties'
    // Optional user input to override parameters
    def userInput
    try {
    timeout(time: 60, unit: 'SECONDS') {
    userInput = input( id:'userInput', message: 'Override build parameters?', parameters: [
    string(defaultValue: props.versionName, description: 'App version (without build number)', name: 'versionName'),
    string(defaultValue: props.versionCode, description: 'Version code (for GooglePlay Store)', name: 'versionCode')
    ])
    logOverrides(userInput, props, "manual_override.log")
    props.putAll(userInput)
    echo("Parameters entered : ${userInput.toString()}")
    }
    } catch (Exception e) {
    echo "User input timed out, continue with default values"
    }
    // Change build name to current app version
    currentBuild.displayName = "${props.versionName}.${env.BUILD_NUMBER}"
    // Common build arguments
    @@ -66,8 +81,8 @@ node ("AndroidBouilder") {
    // Save build results
    step([$class: 'ArtifactArchiver', artifacts: "**/*.apk", excludes: "**/*unaligned.apk", fingerprint: true])
    // Push changes and tag
    gitLib.gitPushSSH(tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}",
    commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}", files: ".", config: true);
    gitLib.gitPushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}",
    tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}", files: ".", config: true);
    sendEmails()
    }

    @@ -78,9 +93,49 @@ node ("AndroidBouilder") {
    }
    }

    stage ('Release') {
    try {
    input 'Do we release this build?'
    node {
    echo "Push Release tag"
    def date = sh(returnStdout: true, script: 'date -u +%Y%m%d').trim()// = new Date().format('yyyyMMdd') // apparently we can't use Date here, not a problem
    gitLib.pushSSH(tagName: "release-${date}", commitMsg: "Jenkins promoted");
    // Do your release stuff
    }
    } catch (Exception e) {
    echo "Release cancelled"
    }
    }

    def sendEmails() {
    emailext body: "See ${env.BUILD_URL}",
    recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
    subject: "Jenkins Build Successful",
    to: "[email protected]";
    }
    }

    // To log manual overrides
    @NonCPS
    def logOverrides(def ov_map, def orig_map, def filename) {
    def header = "# Build ${env.BUILD_NUMBER}-${env.BRANCH_NAME} manual parameters override: ";
    def headWritten = false;
    ov_map.each{ k, v ->
    if( orig_map[k] != v ) {
    if (!headWritten) {
    sh "echo \"${header}\" >> ${filename}"; // apparently we are not allowed to use File.write() in this DSL
    headWritten = true;
    };
    sh "echo \"${k}=${v}\" >> ${filename}"
    }
    }
    }

    // Taken from jenkinsci/jenkins project (https://github.com/jenkinsci/jenkins/blob/master/Jenkinsfile)
    // to add timestamps to logs
    def timestampedNode(String label = "master", Closure body) {
    node(label) {
    wrap([$class: 'TimestamperBuildWrapper']) {
    body.call();
    }
    }
    }
    35 changes: 25 additions & 10 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -27,8 +27,20 @@
    */

    /**
    * Method for pushing build results to git repo. (SSH Agent Plugin required)
    * (Unfortulately there is no Git publish support for pipelines (https://issues.jenkins-ci.org/browse/JENKINS-28335))
    * Method for pushing build results to git repo via SSH. (SSH Agent Plugin required)
    * To keep things going while we wait for official Git Publish support for pipelines (https://issues.jenkins-ci.org/browse/JENKINS-28335)
    *
    * Example call (Inline values):
    * gitPushSSH(branch: "master", commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".", config: true, username: "Jenkins CI", email: "jenkins-ci@example.com");
    *
    * Example call (Environment variables):
    * env.BRANCH_NAME = "mycoolbranch"// BRANCH_NAME is predefined in multibranch pipeline job
    * env.J_GIT_CONFIG = "true"
    * env.J_USERNAME = "Jenkins CI"
    * env.J_EMAIL = "jenkins-ci@example.com"
    * env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3' // Use credentials id from Jenkins (Does anyone know a way to reference them by name rather than by id?)
    * ...
    * gitPushSSH(commitMsg: "Jenkins build #${env.BUILD_NUMBER}", tagName: "build-${env.BUILD_NUMBER}", files: ".");
    *
    * @param args Map with followinf parameters:
    * commitMsg : (String) commit message
    @@ -41,7 +53,7 @@
    * email : (String) committer email (If not specified will check out env variable J_EMAIL)
    */

    def gitPushSSH(Map args) {
    def pushSSH(Map args) {

    String tagName = args.tagName
    String commitMsg = args.commitMsg
    @@ -66,19 +78,22 @@ def gitPushSSH(Map args) {
    error "Error. Incorrect value set { username = ${username}, email = ${email}, credentials = ${creds_ids}, git branch = ${branch} }";

    if(config) {
    sh "git config push.default simple";
    sh "git config user.name \"${username}\"";
    sh "git config user.email \"${email}\"";
    sh """ git config push.default simple
    git config user.name \"${username}\"
    git config user.email \"${email}\"
    """
    }

    sshagent(creds_ids) {
    if (files != null) {
    sh "git add . && git commit -m \"${commitMsg}\" || true";
    sh "git push origin HEAD:refs/heads/${branch} || true";
    sh """git add . && git commit -m \"${commitMsg}\" || true
    git push origin HEAD:refs/heads/${branch} || true
    """
    }
    if (tagName != null) {
    sh "git tag -fa \"${tagName}\" -m \"${commitMsg}\"";
    sh "git push -f origin refs/tags/${tagName}:refs/tags/${tagName}";
    sh """git tag -fa \"${tagName}\" -m \"${commitMsg}\"
    git push -f origin refs/tags/${tagName}:refs/tags/${tagName}
    """
    }
    }
    }
  10. @amaksoft amaksoft revised this gist Sep 20, 2016. 2 changed files with 4 additions and 4 deletions.
    4 changes: 2 additions & 2 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    #!/usr/bin/groovy

    /*
    * Copyright (c) 2016, Andrey makeev <[email protected]>
    * Copyright (c) 2016, Andrey Makeev <[email protected]>
    * All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    @@ -12,7 +12,7 @@
    * disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and|or other materials provided with the distribution.
    * documentation and|or other materials provided with the distribution.
    *
    * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    4 changes: 2 additions & 2 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    #!/usr/bin/groovy

    /*
    * Copyright (c) 2016, Andrey makeev <[email protected]>
    * Copyright (c) 2016, Andrey Makeev <[email protected]>
    * All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    @@ -12,7 +12,7 @@
    * disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and|or other materials provided with the distribution.
    * documentation and|or other materials provided with the distribution.
    *
    * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  11. @amaksoft amaksoft revised this gist Sep 20, 2016. 2 changed files with 53 additions and 0 deletions.
    26 changes: 26 additions & 0 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,31 @@
    #!/usr/bin/groovy

    /*
    * Copyright (c) 2016, Andrey makeev <[email protected]>
    * All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * 1. Redistributions of source code must retain the above copyright
    * notice unmodified, this list of conditions, and the following
    * disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and|or other materials provided with the distribution.
    *
    * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    */

    // Env variables for git push
    env.J_USERNAME = "Jenkins CI"
    env.J_EMAIL = "[email protected]"
    27 changes: 27 additions & 0 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,31 @@
    #!/usr/bin/groovy

    /*
    * Copyright (c) 2016, Andrey makeev <[email protected]>
    * All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * 1. Redistributions of source code must retain the above copyright
    * notice unmodified, this list of conditions, and the following
    * disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and|or other materials provided with the distribution.
    *
    * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    */

    /**
    * Method for pushing build results to git repo. (SSH Agent Plugin required)
    * (Unfortulately there is no Git publish support for pipelines (https://issues.jenkins-ci.org/browse/JENKINS-28335))
    @@ -14,6 +40,7 @@
    * username : (String) committer name (If not specified will check out env variable J_USERNAME)
    * email : (String) committer email (If not specified will check out env variable J_EMAIL)
    */

    def gitPushSSH(Map args) {

    String tagName = args.tagName
  12. @amaksoft amaksoft created this gist Sep 19, 2016.
    60 changes: 60 additions & 0 deletions Jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    #!/usr/bin/groovy

    // Env variables for git push
    env.J_USERNAME = "Jenkins CI"
    env.J_EMAIL = "[email protected]"
    env.J_GIT_CONFIG = "true"
    env.J_CREDS_IDS = '02aa92ec-593e-4a90-ac85-3f43a06cfae3'

    def gitLib

    node ("AndroidBouilder") {
    stage ("Checkout") {
    checkout scm
    gitLib = load "git_push_ssh.groovy"
    }

    stage ("Build") {
    // Check environment (We define ANDROID_HOME in node settings)
    if (env.ANDROID_HOME == null || env.ANDROID_HOME == "") error "ANDROID_HOME not defined"
    if (env.JAVA_HOME == null || env.JAVA_HOME == "") error "JAVA_HOME not defined"

    // Default parameters (In case file is corrupted)
    def d = [versionName: 'unversioned', versionCode: '1']
    // Read properties file
    def props = readProperties defaults: d, file: 'gradle.properties'
    // Change build name to current app version
    currentBuild.displayName = "${props.versionName}.${env.BUILD_NUMBER}"
    // Common build arguments
    env.COMMON_BUILD_ARGS = " -PBUILD_NUMBER=${env.BUILD_NUMBER} -PBRANCH_NAME=${env.BRANCH_NAME}" +
    " -PversionName=${props.versionName} -PversionCode=${props.versionCode}"

    // Build the app
    sh "./gradlew clean"
    sh "./gradlew assembleDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew assembleRelease ${env.COMMON_BUILD_ARGS}"
    }

    stage('Save artifacts and publish') {
    // Save build results
    step([$class: 'ArtifactArchiver', artifacts: "**/*.apk", excludes: "**/*unaligned.apk", fingerprint: true])
    // Push changes and tag
    gitLib.gitPushSSH(tagName: "build/${env.BRANCH_NAME}/${env.BUILD_NUMBER}",
    commitMsg: "Jenkins build #${env.BUILD_NUMBER} from ${env.BRANCH_NAME}", files: ".", config: true);
    sendEmails()
    }

    stage ('Crashlytics register') {
    sh "./gradlew crashlyticsUploadDistributionDebug ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionUat ${env.COMMON_BUILD_ARGS}"
    sh "./gradlew crashlyticsUploadDistributionRelease ${env.COMMON_BUILD_ARGS}"
    }
    }

    def sendEmails() {
    emailext body: "See ${env.BUILD_URL}",
    recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
    subject: "Jenkins Build Successful",
    to: "[email protected]";
    }
    59 changes: 59 additions & 0 deletions git_push_ssh.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    #!/usr/bin/groovy

    /**
    * Method for pushing build results to git repo. (SSH Agent Plugin required)
    * (Unfortulately there is no Git publish support for pipelines (https://issues.jenkins-ci.org/browse/JENKINS-28335))
    *
    * @param args Map with followinf parameters:
    * commitMsg : (String) commit message
    * files : (String) list of files to push (space serparated) (Won't push files if not specified)
    * tagName : (String) tag name (won't push tag if not specified)
    * branch : (String) git branch (Will use env variable BRANCH_NAME if not specified)
    * creds_ids : (List<String>) credentials ids (Will use env variable J_CREDS_IDS if not specified) (haven't figured out yet how to resolve credentials name)
    * configure : (boolean) configure git publisher (username, email). (If not specified will check out env variable J_GIT_CONFIG)
    * username : (String) committer name (If not specified will check out env variable J_USERNAME)
    * email : (String) committer email (If not specified will check out env variable J_EMAIL)
    */
    def gitPushSSH(Map args) {

    String tagName = args.tagName
    String commitMsg = args.commitMsg
    String files = args.files
    String branch = args.branch != null ? args.branch : env.BRANCH_NAME;
    List<String> creds_ids = args.creds != null ? args.creds : env.J_CREDS_IDS.tokenize(" ");
    boolean config;
    try {
    config = args.config != null ? args.config : Boolean.parseBoolean(env.J_GIT_CONFIG);
    }catch (exc) {
    config = false;
    }
    String username = args.username != null ? args.username : env.J_USERNAME;
    String email = args.email != null ? args.email : env.J_EMAIL;

    if (tagName == null && files == null) {
    echo "Neither tag nor files to push specified. Ignoring.";
    return;
    }

    if (username == null || email == null || creds_ids == null || branch == null)
    error "Error. Incorrect value set { username = ${username}, email = ${email}, credentials = ${creds_ids}, git branch = ${branch} }";

    if(config) {
    sh "git config push.default simple";
    sh "git config user.name \"${username}\"";
    sh "git config user.email \"${email}\"";
    }

    sshagent(creds_ids) {
    if (files != null) {
    sh "git add . && git commit -m \"${commitMsg}\" || true";
    sh "git push origin HEAD:refs/heads/${branch} || true";
    }
    if (tagName != null) {
    sh "git tag -fa \"${tagName}\" -m \"${commitMsg}\"";
    sh "git push -f origin refs/tags/${tagName}:refs/tags/${tagName}";
    }
    }
    }

    return this;