Search code examples
gitjenkinsparentgerritgerrit-trigger

How to get parent ID for a commit in a gerrit triggered jenkins pipeline job


In the pipeline code, I need to retrieve the parent ID for a commit in the jenkins pipeline job triggered by gerrit trigger.

I tried to get the parent ID from the gerrit trigger environment variable $GERRIT_PATCHSET_REVISION

        echo "$GERRIT_PATCHSET_REVISION^"
        echo "${GERRIT_PATCHSET_REVISION}^"
        echo "${env.GERRIT_PATCHSET_REVISION}^"
        echo "$GERRIT_PATCHSET_REVISION^^"
        echo "${GERRIT_PATCHSET_REVISION}^^"
        echo "${env.GERRIT_PATCHSET_REVISION}^^"

Actual result: SHA1 value of current commit, GERRIT_PATCHSET_REVISION value followed by 1 or 2 carets ("^")

Expected result: SHA1 value of parent commit

Jenkins is unable to interpret and escape "^". Any pointers would be of great help!


Solution

  • Use git rev-parse instead of echo, supposing in bash:

    firstparent=$(git rev-parse ${GERRIT_PATCHSET_REVISION}^)
    echo ${firstparent}
    

    To successfully retrieve the parent commit, the commit object of the patchset revision must be available from a local git repository. If the snippet runs outside the repository, use git --git-dir=<path_to_repo_.git> rev-parse ${GERRIT_PATCHSET_REVISION}^.