Dynamically add an Android project dependency during Jenkins build

Viewed 233

I currently have a Jenkins pipeline that builds my Android APK. I am struggling to figure out a good way to add a dependency dynamically during the build process.

I don't want to change the current build.grade file in the main repository:

dependencies {
    api 'androidx.appcompat:appcompat:1.1.0'
    ...
}

I have a dependency coming from another private repository:

api 'com.private.library:some-library:1.0'

Is it possible to access the build.gradle files dependencies from a Jenkins pipeline and dynamically add a dependency? Can I wrap the current android project in another gradle file that contains the dependency? Or possibly another good way to add the dependency at build time?

1 Answers

Depending on how your pipeline is defined.. You can add a step that runs a shell command in your pipeline after you cloned the repository and before you build the apk. For instance, if running on linux, use sed to add the line you want to add.

stages {
    stage('Clone repo') {...}
    stage('Add dependency') {
        steps {
            sh '''
                sed -i "/api 'androidx.appcompat:appcompat:1.1.0'/a api 'com.private.library:some-library:1.0'" ./path/to/build.gradle
            '''
        }
    }
    stage('Build') {...}
}

This would add the private repo dependency on a new line after the appcompat dependency.

EDIT: In case you want to go with this approach, this command might be a better option.

echo "dependencies { api 'com.private.library:some-library:1.0' }" >> path/to/build.gradle 

This command doesn't have the sed text dependency (less risk in case the original build.gradle is changed in the main repo). It just adds another dependencies block with your private repo dependency at the end of the file. You can define multiple dependency blocks in the same file so it's no problem if other dependencies are defined, it will not override.

Related