Half a year ago, I published a script that automates inserting git build info into an iOS app with Xcode. Today, I’d like to share a solution for the same task for an Android app using gradle.
Here’s an extract with comments that does the equivalent of the script written in Groovy, that you can insert at the end of the project’s build.gradle file:
tasksaveBuildInfo{doFirst{// get the current commit hash in gitdefgit_version=newByteArrayOutputStream()exec{commandLine'git','log','-1','--format=%h'standardOutput=git_version}git_version=git_version.toString().trim()// get the current git branch, if anydefgit_branch=newByteArrayOutputStream()exec{commandLine'git','symbolic-ref','--short','-q','HEAD'standardOutput=git_branch// ignore error output as we might not be on a branchignoreExitValue=true}// if we are not on a branch, try to get a tag for the commitdefgit_branch_or_tagif(git_branch.size()>0){git_branch_or_tag=git_branch.toString().trim()}else{defgit_tag=newByteArrayOutputStream()exec{commandLine'git','describe','--tags','--exact-match'standardOutput=git_tag// ignore error outputerrorOutput=newByteArrayOutputStream()ignoreExitValue=true}git_branch_or_tag=git_tag.toString().trim()}defbuild_time=newDate().toString()// save the combined build info into assets/build.info filedefresult_line=git_branch_or_tag+"-"+git_version+" ("+build_time+")\n"defassetsDir=android.sourceSets.main.assets.srcDirs.toArray()[0]defbuildInfoFile=newFile(assetsDir,'build.info').getAbsolutePath()newFile(buildInfoFile).write(result_line)}}// once the project is evaluated and the android tasks are created,// make the new task depend on packageDebug// http://stackoverflow.com/questions/16853130/run-task-before-compilation-using-android-gradle-plugin/16853376#16853376gradle.projectsEvaluated{packageDebug.dependsOn(saveBuildInfo)}
Here’s a simple function that returns the build info:
privateStringgetBuildInfo(){StringbuildInfo=null;BufferedReaderreader=null;try{reader=newBufferedReader(newInputStreamReader(getAssets().open("build.info")));buildInfo=reader.readLine();}catch(IOExceptione){Log.d(TAG,"Can't open file with build info",e);}finally{if(reader!=null){try{reader.close();}catch(IOExceptione){e.printStackTrace();}}}returnbuildInfo;}
This is one of my first scripts in Groovy, so if you have any suggestions for improvements, please leave a comment!