I am writing a rake task for my rails app to do some stuff after I've determined what the current branch is, but I'm having trouble comparing the current branch to master. My rake task is bellow:
desc "TODO"
task repo: :environment do
branch = `git rev-parse --abbrev-ref HEAD`
if branch.eql? "master"
puts "On master!"
else
puts "Not on master!"
end
end
I've checked, and git rev-parse --abrev-ref HEAD returns "master". I also double checked that the class of branch is String. I'm pretty confused why this isn't working.
Any suggestions?
Related
I'm using shared libraries in groovy.
I have this variable which will return : feature/nameofthebranch
def BRANCH = steps.sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
However I only need the character after the "/"
I've tried split and other stuff but doesn't work as I would like to, maybe because I'm clumsy at groovy.
Expected result should be from feature/nameofthebranch to "nameofthebranch"
You can do it like this
def BRANCH = steps.sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
echo "${BRANCH.split('/')[1]}"
I have jenkins job for with GitHub Pull Request Builder.
In build, I added first step to set the JIRA_ISSUE variable.
JIRA: Add related environment variables to build
Extracts JIRA information for the build to environment variables.
Available variables:
JIRA_ISSUES - A comma separated list of issues which are referenced in the version control system changelog
JIRA_URL - Primary URL for the JIRA server
Typical usage:
Add this build step
Use the "Progress JIRA issues by workflow action" or "Move issues matching JQL to the specified version" with JQL like:
issue in (${JIRA_ISSUES})
Second step is to update these jira issues.
<builders>
<hudson.plugins.jira.JiraEnvironmentVariableBuilder plugin="jira#3.0.0"/>
<hudson.plugins.jira.JiraIssueUpdateBuilder plugin="jira#3.0.0">
<jqlSearch>issue in (${JIRA_ISSUES})</jqlSearch>
<workflowActionName>Ready for Review</workflowActionName>
<comment>add comment</comment>
</hudson.plugins.jira.JiraIssueUpdateBuilder>
</builders>
When I create PR, and it trigger the job, it not set JIRA_ISSUES
GitHub pull request #356 of commit 2e2b92d107a5460c4cc593fcab78c63f800d6472, no merge conflicts.
Setting status of 2e2b92d107a5460c4cc593fcab78c63f800d6472 to PENDING with url https://myjenkins.com/job/cicd-myjob-prtest-unittest/69/ and message: 'running tox...'
Using context: tox testing
[EnvInject] - Loading node environment variables.
Building remotely on myslave.node.box.com (linux) in workspace /var/lib/jenkins/workspace/cicd-myjob-prtest-unittest
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://mygithub.com/myuser/myproject.git # timeout=10
Fetching upstream changes from https://mygithub.com/myuser/myproject.git
> git --version # timeout=10
using GIT_ASKPASS to set credentials Github Service Account Username with token
> git fetch --tags --progress https://mygithub.com/myuser/myproject.git +refs/pull/*:refs/remotes/origin/pr/*
> git rev-parse refs/remotes/origin/pr/356/merge^{commit} # timeout=10
> git rev-parse refs/remotes/origin/origin/pr/356/merge^{commit} # timeout=10
Checking out Revision 0ff9e43bbc1385303429f7bcf93fea36e8c455d3 (refs/remotes/origin/pr/356/merge)
> git config core.sparsecheckout # timeout=10
> git checkout -f 0ff9e43bbc1385303429f7bcf93fea36e8c455d3
Commit message: "Merge 2e2b92d107a5460c4cc593fcab78c63f800d6472 into 731994024e723b1257374f521b4784060df9e5b5"
First time build. Skipping changelog.
[JIRA] Setting JIRA_ISSUES to .
[JIRA] Updating issues using workflow action Ready for Review.
[JIRA] JQL: issue in ()
[JIRA] Updating issue MYPROJECT-1234
Setting status of 2e2b92d107a5460c4cc593fcab78c63f800d6472 to SUCCESS with url https://myjenkins.com/job/cicd-myjob-prtest-unittest/69/ and message: 'All is well.
'
Using context: tox testing
Finished: SUCCESS
The [JIRA] Updating issue MYPROJECT-1234 is from publisher
<publishers>
<hudson.plugins.jira.JiraIssueUpdater plugin="jira#3.0.0">
<issueSelector class="hudson.plugins.jira.selector.JqlIssueSelector">
<jql>issue=MYPROJECT-1234</jql>
</issueSelector>
<labels/>
</hudson.plugins.jira.JiraIssueUpdater>
</publishers>
If I look for change log for commit 2e2b92d107a5460c4cc593fcab78c63f800d6472 it has the jira issue in comment and title.
commit 2e2b92d107a5460c4cc593fcab78c63f800d6472 (HEAD -> MYPROJECT-1234, origin/MYPROJECT-1234)
Author: myuser <myuser#mygithub.com>
Date: Tue Aug 21 15:55:41 2018 -0500
MYPROJECT-1234: Tox testing
MYPROJECT-1234 change the data.
Why JiraEnvironmentVariableBuilder is not able to set JIRA_ISSUES to MYPROJECT-1234? while same exists in changelog.
I am writing my first Jenkins pipeline. Its basic goal for now is just to sequentially run a bunch of jobs in a pipeline, to which I will later add different functionality. I am trying to use propagate: false so I can handle specific failures myself, instead of the pipeline exiting with an error as soon as a job fails. Note that in the code snippet I'm showing 2 different approaches I've tried (job a and job b. In reality there are about a dozen jobs) that basically return the same stacktrace. I'm stumped. If I try it in the pipeline's script box, it works. But if I do it in the jenkinsfile I get an error.
EDIT: forgot to mention - jenkins version - 2.7.4
Code:
#!groovy
def SUCCESS_LIST = ["SUCCESS", "UNSTABLE"]
stage "Unit Tests"
node ('k8s'){
echo 'Running unit tests..'
currentBuild.result = "SUCCESS"
a = build job 'Some Unit Tests', propagate: false
b = build("Other System Unit Tests"), propagate: false
jobsList<Object> = [a, b]
// check if there was a failure. if so - mark job as 'failed'.
for (job in jobsList){
if (!SUCCESS_LIST.contains(job.result)) {
//currentBuild.result = "FAILURE"
mail to: amos#company_mail.com, subject: 'The Pipeline failed at unit-tests'
}
}
}
stacktrace:
Started by user Amos B
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/my-company/companyone.git # timeout=10
Fetching upstream changes from https://github.com/my-company/companyone.git
> git --version # timeout=10
using .gitcredentials to set credentials
> git config --local credential.username automation#my-company.com # timeout=10
> git config --local credential.helper store --file=/tmp/git6347898027159980380.credentials # timeout=10
> git -c core.askpass=true fetch --tags --progress https://github.com/my-company/companyone.git +refs/heads/*:refs/remotes/origin/*
> git config --local --remove-section credential # timeout=10
> git rev-parse refs/remotes/origin/develop^{commit} # timeout=10
> git rev-parse refs/remotes/origin/origin/develop^{commit} # timeout=10
Checking out Revision 5d349a17a9ee89d340b63db92a71e159780ea7ad (refs/remotes/origin/develop)
> git config core.sparsecheckout # timeout=10
> git checkout -f 5d349a17a9ee89d340b63db92a71e159780ea7ad
> git rev-list 65a8a33381ae18a1aefdd57a7d64fd3a475407fb # timeout=10
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 8: expecting '}', found ',' # line 8, column 49.
ild job 'Knowledge Unit Tests', propagat
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(ErrorCollector.java:150)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:120)
at org.codehaus.groovy.control.ErrorCollector.addError(ErrorCollector.java:132)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:360)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:145)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:111)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:237)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:167)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:931)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:546)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:67)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:410)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:373)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:213)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
Finished: FAILURE
It's the exact same error no matter which syntax (a or b) is used. what am I missing?
You should do this to call other jobs from your pipeline. The lack of a colon after job is throwing the error:
build job: 'job-name'
In gradle I'd like to add both the current branch-name and commit-number as suffix to my versionName. (Why? Because when I build my app in Jenkins to release it in HockeyApp, it's useful to show what branch & commit that app was built from!)
So when I enter this in command prompt, my current branch name is returned:
git rev-parse --abbrev-ref HEAD
Same happens when I use this line in Android gradle, using the code in either this answer, or as shown in this piece of gradle code:
def getVersionNameSuffix = { ->
def branch = new ByteArrayOutputStream()
exec {
// The command line to request the current branch:
commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
standardOutput = branch
}
println "My current branch: " + branch
def versionNameSuffix = "-" + branch
// ... some other suffix additions ...
return versionNameSuffix
}
buildTypes {
debug {
applicationIdSuffix ".test"
versionNameSuffix getVersionNameSuffix()
}
}
Resulting log (this is exactly what I want):
"My current branch: feature/MyFeature"
However, when I build my app in a Jenkins job, it will output a different result:
"My current branch: HEAD"
Why does this happen, and how to correctly retrieve my current branch name in Jenkins?
EDIT:
I've used a different approach, which returns the branchName correctly in most cases, also on Jenkins:
git name-rev --name-only HEAD
Example output in prompt:
"My current branch: feature/MyFeature"
Example output in Jenkins:
"My current branch: remotes/origin/feature/MyFeature"
I can remove "remotes/origin/" if i like, so that's okay!
But this approach causes different trouble (both in prompt, gradle and on Jenkins). When I have tagged the last commit, it won't output the branch-name, but this:
"My current branch: tags/MyTag^0"
EDIT 2:
A third approach can be found here.
Including the comments below the answer, I could use grep * to retrieve the branch in prompt. However, I cannot use the backslash in the gradle code. This fails:
commandLine 'git', 'branch', '|', 'grep', '\\*'
Any advice?
Try the env: BRANCH_NAME
BRANCH_NAME
For a multibranch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches.
Access it with env.BRANCH_NAME
I'm following the this site.
And I'm in step 6(6. Deploy!).
So I executed below the command in turn.
$ git add .
$ git commit -am "add deployment configs"
$ git push master
$ cap deploy:setup
And all command was successfully executed.
Next, I tried to cap deploy command.
But I get some error.
$ cap deploy
* 2013-06-04 19:19:27 executing `deploy'
triggering before callbacks for `deploy'
* 2013-06-04 19:19:27 executing `deploy:check_revision'
WARNING: HEAD is not the same as origin/master
Run `git push` to sync changes.
$
So, I try git push and I get a message...
$ git push
Everything up-to-date
...
What is the problem??
I don't know that...
What should I do??
more informateion---
$ git branch
* master
$ git status
# On branch master
nothing to commit (working directory clean)
$ git remote
origin
Edit:
I also tried to $ git push origin master. And I get a same message that is nothing to commit (working directory clean)
Edit2:
$ git rev-parse HEAD
c3e758f2d47bb0bc126de91560905a1893fe08c6
$ git rev-parse origin/master
c3e758f2d47bb0bc126de91560905a1893fe08c6
Check your current branch and deploy.file.
In the deploy.file, it could exist the following code snippet:
task :check_revision, roles: :web do
unless `git rev-parse HEAD` == `git rev-parse origin/master`
puts "WARNING: HEAD is not the same as origin/master"
puts "Run `git push` to sync changes."
exit
end
end
So you must be on the same branch set in this code.
To fix, change the following line:
unless `git rev-parse HEAD` == `git rev-parse origin/${YOUR_CURRENT_BRANCH}`
The following worked nice for/to me.
Try:
git remote show origin
If you get an error, ask for all remotes:
git remote -v
and set remote origin:
git remote add origin git#bitbucket.org:xyz/abc.git
Now 'show origin' will provide the correct answer:
git remote show origin
try:
git push origin master
Looks like you may not be pushing the code back to the remote repo.
You should be able to edit your .git/config file so in the future you can just type "git push"
I think your deploy.rb file is not set up correctly. Check line 14 where your repository is set up. Make sure it matches your github repo.
If that doesn't work, try this: after task :check_revision, roles: :web do add these lines:
puts `git rev-parse HEAD`
puts `git rev-parse origin/master`
Hopefully that will give you some more info and you can post the results.