0

I am trying to fetch the branch the current git head is in as:

String branchName = gitBranchName().toLowerCase()

String gitBranchName() {
    def branch = System.env.GIT_BRANCH
    if (!branch){
        // For local build
        def proc = "git rev-parse --abbrev-ref HEAD".execute()
        proc.in.eachLine { line -> branch = line }
        proc.err.eachLine { line -> println line }
        proc.waitFor()
    }
    return branch
}

on running this it always returns null and hence code breaks when executing gitBranchName().toLowerCase() as toLowerCase() throws error on running for null.

* What went wrong:
Execution failed for task ':init_env'.
> Cannot invoke method toLowerCase() on null object

I guess it is sending the value of branch returned from System.env.GIT_BRANCH which is not set on local machine and it is not waiting for the if block to complete.

Any idea what is wrong and why?

torek
  • 448,244
  • 59
  • 642
  • 775
Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
  • 'I guess it is sending the value of branch returned from System.env.GIT_BRANCH which is not set on local machine and it is not waiting for the if block to complete.'- Looks like you answered your own question. – Ashutosh Vaish Sep 05 '22 at 13:53
  • Are you sure the `if` block is ever entered? – Koenigsberg Sep 05 '22 at 13:56
  • @AshutoshVaish yeah may be, but then how do I make it work? I am already using proc.waitFor() – Varun Sukheja Sep 05 '22 at 14:40
  • @Koenigsberg yes it goes inside the IF block – Varun Sukheja Sep 05 '22 at 14:40
  • Try restarting your IDE and system after you have set the environment variable. – Ashutosh Vaish Sep 05 '22 at 15:17
  • This has almost nothing to do with Git (except that you're running a Git command to produce some output) and almost everything to do with Groovy, which is a downright weird language. See [Groovy executing shell commands](https://stackoverflow.com/q/159148/1256452). – torek Sep 05 '22 at 15:36

1 Answers1

0

I'm using org.ajoberstar.grgit Gradle plugin with success:

plugins {
  id 'org.ajoberstar.grgit' version '5.0.0' apply false
}

import org.ajoberstar.grgit.Grgit

Grgit git = Grgit.open currentDir:project.rootDir
String commit = git.head().abbreviatedId
injecteer
  • 20,038
  • 4
  • 45
  • 89