Jenkins GitSCM detached head

Viewed 804

I've a problem when using Jenkins GIT plugin as it returns a detached head.
What I want to accomplish:

  • Pull code from git repository
  • Make changes to specific files in this repository
  • Use Jenkins to push changes to same repository

Following code to pull from my Repository:

checkout([
     $class: 'GitSCM',
      branches: [[name: "branch1"]],
      userRemoteConfigs: [[credentialsId: "credentials", url: "repository"]],
      extension: [[
        $class: 'SubmoduleOption',
        disableSubmodules: false,
        parentCredentials: true,
        recursiveSubmodules: true,
        reference: '',
        trackinSubmodule: false
      ]],
    submoduleCfg:[]
  ])
}

Code to push to my Repository:

(Changes to file)
 
      ...

stage('Push to repo') {
  steps {
    sh """
      git checkout master
      git pull origin master
      git add test.txt
      git commit -m "Added string"
      git push origin master
    """
  }
}

Error:

From gitlab.com:USERNAME/test-jenkins
 * branch            master     -> FETCH_HEAD
Already up-to-date.
error: Your local changes to the following files would be overwritten by checkout:
    test.txt
Please commit your changes or stash them before you switch branches.
Aborting
[detached HEAD 2adf034] Added string
 1 file changed, 1 insertion(+)

If I remove checkout:

! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@gitlab.com:USERNAME/test-jenkins.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for detail

I've tried to follow the steps in Git branch detached HEAD .

1 Answers

Since the documentation mentions the detached head state, you could add to your pipeline a sh step

sh("git checkout branch1")

That would be enoufh for the rest of your operation to operate on a branch, instead of a detached HEAD.

Related