Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set static variable from Gradle on build-time

I've got an Android project, managed under git. Git has 2 branches (well more.. but important are those two), branch-a & branch-b. Is it possible to set up gradle to determine which branch was the project built from and set up the public static String in one of the project's classes to value depending on the branch?

Thanks.

like image 633
Mikhail Krutov Avatar asked Feb 09 '23 09:02

Mikhail Krutov


1 Answers

Yes, you may have a gradle.properties file in both your branches (you can read about properties here), containig some property, for example buildBranchName. But the value assigned to this property will differ in every brach. For example, in brach1 you have a gradle.properties file in the same directory as your build.gradle script and it has a

buildBranchName=branch1

property inside. At the same time, gradle.properties file in branch2 contains:

buildBranchName=branch2

Then, since you have an android project, you can use a BuildConfig class generation option to pass this variable into you application sources. You can read about it here, in "Enhancing your BuildConfig" section. All you need, is to add some property to this autogenerated class for your build types, just like:

android {
    ...
    buildTypes {
        debug {
            buildConfigField "String", "BUILD_BRANCH", buildBranchName
        }
        ...
    }    
}

Then, during the build, the final class BuildConfig will be generated and it will have a BUILD_BRANCH field, which you may use as a simple static field of this class.

Furthermore, if some has a non-android project, there is a plugin, which allows to do the same for all java-projects.

like image 191
Stanislav Avatar answered Feb 11 '23 00:02

Stanislav