2

I need current branch name of the project where I'm deploying a plugin, So code for current branch name in the plugin's groovy class goes like this,

   def getCurrentGitBranch() {
        def gitBranch = "Unknown branch"
        try {
            def workingDir = new File(ProjectConfig.projectDir)
            def result = 'git rev-parse --abbrev-ref HEAD'.execute(null, workingDir)
            result.waitFor()
            if (result.exitValue() == 0) {
                gitBranch = result.text.trim()
            }
        } catch (Exception e) {
            throw new Exception("Problem occurred while fetching current branch name from git.")
        }
        log.info("Branch Name [ "+ gitBranch + "]")
        return gitBranch
    }

But for some reason when while deploying the project on cloud using jenkins this function return HEAD instead of current branch of the project for which I'm trying to deploy.

I tried a lot with different scenarios but no luck, how do I make sure the plugin I'm using fetches the current branch of the project for which deployment is being done.

tyro
  • 765
  • 2
  • 13
  • 34

1 Answers1

3

For any reasons, you are in detached HEAD. (Please read this article if you don't know what is a detached HEAD.) Usually, you are in this state if you do something like git checkout SHA-1; git checkout tag (these are examples between severals).

It seems Jenkins checkout the code in detached head. You can go to $JENKINS_HOME/workspace/YOUR_PROJECT to check this with git status.

To correct your issue, you have to add Additional Behaviours > Check out to a specific local branch under SCM management section of Jenkins project configuration. Reading following link may helps you : Jenkins Git plugin detached HEAD

Flows
  • 3,675
  • 3
  • 28
  • 52
  • Thanks Flows for your explanation I check on jenkins config its deploying master branch with build parameter as a version, how do I make sure on Jenkins that is in detached HEAD any idea – tyro Mar 15 '18 at 10:55
  • I give some more details in my answer – Flows Mar 15 '18 at 12:24
  • Actually I can see in the logs of Jenkins for deployment git checkout -f 63812e412cffb50d6b0debbf7baf5be359ae39d2 this means its on detached HEAD right? from whatever I have read about detached HEAD – tyro Mar 15 '18 at 12:26
  • Yes it is right. To change this, you have to add "Additional Behaviours" / "Check out to a specific local branch" in SCM management under Jenkins project configuration – Flows Mar 15 '18 at 13:10