1

I want to find the target branch when a pull request is submitted on GitHub, in my Jenkins pipeline. To achieve this I am doing the following:

I am invoking a windows batch file from my Jenkinsfile, which in turn invokes a nodejs script. This script internally invokes GitHub APIs to get the target branch which is to be set on some variable in Jenkinsfile(code snippet given below): Jenkinsfile

env.TARGET_BRANCH = bat "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}"

BatchFile:

node getTargetBranchForPR.js %1

But unfortunately, the variable env.TARGET_BRANCH is not getting set to the target branch even though the nodejs script gets the right value. I am in fact not able to return the value from the batch file. Could someone please help me here?

Anee
  • 463
  • 9
  • 26
  • test to see if you can have the value echoed to screen, before the node line, do `echo %* &` and add `pause` below it. – Gerhard Jan 19 '19 at 17:00
  • you rather need to check this - https://stackoverflow.com/questions/36547680/how-to-do-i-get-the-output-of-a-shell-command-executed-using-into-a-variable-fro – npocmaka Jan 19 '19 at 18:02
  • @npocmaka This will definitely help me in achieving what I want, but I am not able to find the git command to retrieve the target branch(base) of a commit. – Anee Jan 20 '19 at 05:05
  • I am trying to get the target branch in the JenkinsFile. I have checked lot of sites and links, but not able to find a way of getting that information. – Anee Jan 20 '19 at 05:15
  • check if the git command is in the %path% variable – npocmaka Jan 20 '19 at 09:46

1 Answers1

0

@npocmaka mention is the right way: How to do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Accodring to Jenkins' documentation.

returnStdout (optional) If checked, standard output from the task is returned as the step value as a String, rather than being printed to the build log. (Standard error, if any, will still be printed to the log.) You will often want to call .trim() on the result to strip off a trailing newline.

So your code should look like

env.TARGET_BRANCH = bat( script: "GetTargetBranchFromGit.bat ${env.BRANCH_NAME}",
                         returnStdout: true
).trim()

If you get back more than expected you probably need to parse it.

hakamairi
  • 4,464
  • 4
  • 30
  • 53
  • This one turned out to be a bit complex than i expected. Anyone knows any other way of finding out the target branch when a pull request is opened(in JenkinsFile)? I have a multibranch pipeline and i would want to have different behaviours based on source and the target branch. – Anee Feb 15 '19 at 16:12