Dani bISHOP
Dani bISHOP

Reputation: 1289

How to show current Git branch in an Android application programatically?

I want to show the current Hash/Branch Ref of the GIT repo in the About dialog of my Android Application. I can copy it by hand, but it's much more interesting to do it programmatically.

I have a library for my apps, so my activities and my applications inherit from my own library classes. So, I thought of adding a method [getGitHash()] to my library application class. I can refer to the current branch by reading .git/HEAD, which is virtually referenced in a res/raw file under Eclipse project (look here to see how it's done). My project has the R.raw.HEAD resource now.

But now the library can't reference the R.raw.HEAD, so I can't implement the method in the library. The method in the library should be something like this:

public static String getGitHash(int nDigits) {
    
    String hash = "";
    SB_ResourceReader.LoadRAWFile(R.raw.HEAD,SB_Application.getContext());
    return hash;
}

LoadRAWFile() is a static method to read raw file content and SB_Application.getContext() is another static method to retrieve... well, the app context.

Is it possible for the library to 'trust' that there will be a certain resource although it is not accessible when compiling?

Upvotes: 7

Views: 3558

Answers (5)

moshe navon
moshe navon

Reputation: 74

write in the end of build.gradle reuse fun to execute some commands,

static def getExecute(command) {
  def result = ""
  def proc = command.execute()
  proc.in.eachLine { line -> result = line }
  proc.err.eachLine { line -> println line }
  proc.waitFor()
  return result 
}

then you have 2 options:

  • 1: buildConfig

     buildConfigField "String", "BUILD_TIME", "\"${getExecute("git rev-parse --abbrev-ref HEAD")}\""
     buildConfigField "String", "GIT_BRANCH", "\"${getExecute("git rev-parse --abbrev-ref HEAD")}\""
     buildConfigField "String", "GIT_COMMIT", "\"${getExecute("git rev-parse --short HEAD")}\""
     buildConfigField "String", "GIT_COMMIT_NAME", "\"${getExecute("git show-branch --no-name HEAD")}\""
     buildConfigField "String", "GIT_LAST_COMMIT_TIME", "\"${getExecute(" git log -1 --format=%cd")}\""
     buildConfigField "String", "GIT_UESRNAME", "\"${getExecute("git config user.name")}\""
     buildConfigField "String", "GIT_EMAIL", "\"${getExecute("git config user.email")}\""
    

    and call them like this,

    private fun getGitInfo() :String {
      var gitInfo = ""
    
      gitInfo += "build time: " + BuildConfig.BUILD_TIME + "\n"
      gitInfo += "branch: " + BuildConfig.GIT_BRANCH + "\n"
      gitInfo += "commit: " + BuildConfig.GIT_COMMIT + "\n"
      gitInfo += "commit name: " + BuildConfig.GIT_COMMIT_NAME + "\n"
      gitInfo += "time: " + BuildConfig.GIT_LAST_COMMIT_TIME + "\n"
      gitInfo += "username: " + BuildConfig.GIT_UESRNAME
      gitInfo += "email: " + BuildConfig.GIT_EMAIL
    
      return gitInfo
    }
    
  • 2: resValue

    resValue "string", "build_time", getExecute("date")
    resValue("string", "git_branch", "\"${getExecute("git rev-parse --abbrev-ref HEAD")}\"")
     resValue("string", "git_commit", "\"${getExecute("git rev-parse --short HEAD")}\"")
     resValue("string", "git_commit_name", "\"${getExecute("git show-branch --no-name HEAD")}\"")
     resValue("string", "git_last_commit_time", "\"${getExecute(" git log -1 --format=%cd")}\"")
     resValue("string", "git_username", "\"${getExecute("git config user.name")}\"")
     resValue("string", "git_email", "\"${getExecute("git config user.email")}\"")
    

    and call them like this,

    private fun getGitInfo() :String {
      var gitInfo = ""
      gitInfo += "build time: " + getString(R.string.build_time) + "\n"
      gitInfo += "branch: " + getString(R.string.git_branch) + "\n"
      gitInfo += "commit: " + getString(R.string.git_commit) + "\n"
      gitInfo += "commit name: " + getString(R.string.git_commit_name) + "\n"
      gitInfo += "time: " + getString(R.string.git_last_commit_time) + "\n"
      gitInfo += "username: " + getString(R.string.git_username) + "\n"
      gitInfo += "email: " + getString(R.string.git_email)
    
      return gitInfo
    }
    

Upvotes: 4

HBB20
HBB20

Reputation: 2968

Thanks @Hugo Gresse for your answer. If you are using gradle.kts (Kotlin), then you will need following modifications:

In your build.gradle.kts file:

    android {
        defaultConfig {
            compileSdkVersion(29)
            applicationId = "xxx.xxxxxx.xxxx"
            minSdkVersion(21)
            targetSdkVersion(29)
            versionCode = 3
            versionName = "0.0.3"
            resValue("string", "gitBranch", getGitBranchName())
        }
    }

    // function to read current git branch name
    fun getGitBranchName(): String {
        val process = Runtime.getRuntime().exec("git rev-parse --abbrev-ref HEAD")
        val sb: StringBuilder = StringBuilder()
        while (true) {
            val char = process.inputStream.read()
            if (char == -1) break
            sb.append(char.toChar())
        }
        return sb.toString()
    }

Then you will have access to new string res named gitBranch:

getString(R.string.gitBranch)

Upvotes: 0

Hugo Gresse
Hugo Gresse

Reputation: 17899

More easily (without any plugin), you can achieve this by setting a new resource in your app.gradle like so:

android {
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1"
        resValue "string", "gitBranch", gitBranch()
    }
    buildTypes {...}
}


def gitBranch() {
    def branch = ""
    def proc = "git rev-parse --abbrev-ref HEAD".execute()
    proc.in.eachLine { line -> branch = line }
    proc.err.eachLine { line -> println line }
    proc.waitFor()
    branch
}

So you'll have access to a new string resource

getString(R.string.gitBranch)

Upvotes: 9

Pal Szasz
Pal Szasz

Reputation: 3225

If you are using eclipse, try the following: add the .git folder as a source folder, and as inclusion pattern just write "HEAD". This will result in the HEAD file to be stored as an asset (not an android resource!) in the jar. You can access it using the getClass().getResourceAsStream("/HEAD") method:

    try {
        InputStream is = getClass().getResourceAsStream("/HEAD");
        byte buff[] = new byte[256];
        int len = is.read(buff);
        String s = new String(buff, 0, len);
        System.out.println("!!! HEAD: " + s);
    } catch (Exception e) {
        e.printStackTrace();
    }

Upvotes: 2

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

So the way to do this is to script it in your ant build file. You should checkout the various ant file tasks. I think in you case the ReplaceRegEx is just what you need. Put some sort of unique string in the file where you want to put the current git branch your on, run a command to get the current git branch, and replace the unique string with the output of that command.

Upvotes: 0

Related Questions