Using env variable github.ref_name doesn't give me branch name - github

When I use in my workflow github.ref_name it doesn't provide me a branch name from where I triggered this workflow. I get 16/merge. Why? When I use github.ref_type I clearly see that my ref type is branch so why I don't get branch name?
Also it's showing when I use $GITHUB_REF or git symbolic-ref HEAD (and separating refs/heads/ off). Ah and I tried github.event.push.ref but it's not showing me anything.
How to get always branch name from where I triggered the workflow?

For following code:
Run echo running on branch ${GITHUB_REF##*/} ${GITHUB_REF}
When your workflow runs becuase of push event you will get:
running on branch main refs/heads/main
But for pulr request event it would be:
running on branch merge refs/pull/3/merge
Why's that?
If the repository is on GitHub and you have any Pull Requests that have been opened, you’ll get these references that are prefixed with refs/pull/. These are basically branches, but since they’re not under refs/heads/ you don’t get them normally when you clone or fetch from the server — the process of fetching ignores them normally.
You can also check this question here

Related

Ensure that a workflow in Github Actions is only ever triggered once

I have workflow that is triggered when a specific file is changed. Is it possible to ensure that this workflow is only triggered the first time that file is changed?
The use case is:
a repository is created from a template repository
to initialize the README and other things in the repo, some variables can be set in a JSON config file
once that file is committed, the workflow runs, creates the README from a template etc.
I have tried to do let the workflow delete itself before it commits and pushes the changed files. That doesn't work: fatal: not in a git directory and fatal: unsafe repository ('/github/workspace' is owned by someone else).
What might work is adding a topic like initialized to the repo at the end of the workflow and check for the presence of this topic at the beginning of the workflow. However, this is feels like a hack in that I'm abusing topics for something they're probably not meant to do.
So my question remains: is there a good way to only run the workflow once?
With the help of the comment by frennky I managed to do solve this by using the GitHub CLI to disable the workflow.
Here is the step at the end of the workflow that does this:
- name: Disable this workflow
shell: bash
run: |
gh workflow disable -R $GITHUB_REPOSITORY "${{ github.workflow }}"
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

How do you restrict which branches can be pulled into a target branch

I'm trying to set up policies on my Azure DevOps Branches.
I'm able to state that a branch must build and pass our unit tests before allowing a merge but is there a way to restrict which branch is allowed to merge into it.
I have two branches that this would impact.
I have my 'master' branch that I would like to restrict to only accept pull requests from a branch called 'UAT'.
I have a branch called 'UAT' that I would like to restrict to only accept pull requests coming from a branch called 'Dev'.
The closest workaround I could think of is to have a very simple pipeline that would run on pull requests and check System.PullRequest.SourceBranch and System.PullRequest.TargetBranch. If the values don't match your policy, then fail the pipeline, which in turn will block the PR.
Based on the answer by qbik i created this short yaml code. Replace the source and target as needed for your use case. The code below is only for testing in my pipeline, to create the desired failure.
- powershell: >
if ("$(System.PullRequest.SourceBranch)" -ne "refs/heads/acc" -And "$(System.PullRequest.TargetBranch)" -eq "refs/heads/test")
{
Write-Error "
=========================================================================================================
Branch check failed.
Illegal Pull Request from $(System.PullRequest.SourceBranch) into $(System.PullRequest.TargetBranch).
========================================================================================================="
}
displayName: Branch Check

Only run GitHub Actions manually while blocking Pull Request

I have a set of GitHub Actions configured to block pull requests from being merged until the Actions complete successfully. However, every time a new commit is pushed to a PR, the Actions are run again, which can be very wasteful if the author is not yet ready to merge, and intends to make future changes. Is there any way to have a GitHub Action still block a PR being merged but also not run the Action automatically?
With this recent update you can now convert pull requests back to draft status. So you could do that when you need to make changes and disable the CI for drafts. Then convert the draft to a pull request after the changes are complete to rerun CI.
on: pull_request
jobs:
build:
if: github.event.pull_request.draft == 'false'
runs-on: ubuntu-latest
steps:
...
One workaroound would be for the Action to look for a specific comment (for example: "[TO MERGE]: this commit is about ...), and:
return immediately if '[TO MERGE]' is not found, minimizing the action overhead on each commit
go on with checks, if '[TO MERGE]' is found.

Circumvent pull request for script

We use Jalopy to reformat the code. On jenkins/svn, we checked out, formatted and commited again. Now on bamboo/stash, we want to do the same.
We set up this restriction for the master branch:
Prevent changes without a pull request (Everyone)
(AFAIK, it is not possible, to exclude certain users from this rule, is it?)
Now, as expected, when we try to push the formatted sources, we get this error:
remote: Branch refs/heads/master can only be modified through pull requests.
remote: Check your branch permissions configuration with the project administrator.
remote: ----------------------------------------------------
remote:
To ssh://git#mystash.com/proj/proj1.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://git#mystash.com/proj/proj1.git'
Any suggestions on how we can keep the enforcement for pull requests, while still being able to push directly to master from a Bamboo script? Or any better approach?
That is currently correct ... kind of. The Stash UI doesn't provide a way to set this (or see if you have) at the moment. However, the REST API will actually let you set branch permissions and specify users who are exempt. For details, see this comment on the feature suggestion to add full support.

Prevent mercurial push during a jenkins build

I have a jenkins job that runs some tests on a mercurial repo, and if successful tags the local repo with a 'stable' tag and then pushes this back to the main repo. The issue I'm having is that if someone pushes changesets while the build is running, then I cannot push the 'stable' tag.
I was wondering if there was a way to set the remote repo to read-only while the build is running, then make it 'push-able' once the build finishes?
Thanks,
Vackar
Preventing the push is probably not what you want (and it's almost pretty much impossible). The promise of a DVCS like Mercurial or git is that there's no locking -- it's a step forward.
Have you considered having Jenkins just pull and update before it merges? You can still tag the proper revision. Something like this:
jenkins checks out the code and notes the revision id it's building
jenkins does the build, runs the tests, etc. and everything goes well
jenkins does a hg pull to get the latest from the server
jenkins does a hg tag -m "build number $BUILD_NUMBER" --revision X --force stable
jenkins does a hg push
Then there's (almost) no time between that final pull, tag, and push, but the tag still goes on the revision that was actually build -- because you saved that revision hash id from when you first pulled.
I've just been looking for something similar. In our case, Jenkins is performing a merge, running an extensive suite of tests and once they all pass, pushing the merged code back to the repository. So it takes ~1 hour and fails if a developer pushes while the job is executing (it can't do the final push).
I couldn't find a ready-made solution, so ended up writing a mercurial hook which checks whether the job is building (using the REST API) before allowing the push.
You'll need access to your remote mercurial repository, but other than that, it's not too complex.
Add the following to your-remote-repo/.hg/hgrc:
[hooks]
pretxnchangegroup.DisablePushDuringJenkinsBuild= python:.hg/disable_push_if_building_hook.py:check_jenkins
[jenkins]
url=http://path-to-jenkins
jobs=jenkins-job-name[,comma-separated, for-multiple, jobs]
And make sure this python script is in your-remote-repo/.hg/
import json, urllib2
from mercurial import util
TEN_SECONDS = 10
def check_jenkins(ui, repo, node, **kwargs):
jenkins_url = ui.config('jenkins', 'url', default=None, untrusted=False)
jenkins_jobs = ui.config('jenkins', 'jobs', default=None, untrusted=False)
if not jenkins_url:
raise util.Abort('Jenkins hook has not been configured correctly. Cannot find Jenkins url in .hg/hgrc.')
if not jenkins_jobs:
raise util.Abort('Jenkins hook has not been configured correctly. Cannot find Jenkins jobs in .hg/hgrc.')
jenkins_jobs = [x.strip() for x in jenkins_jobs.split(',')]
for job in jenkins_jobs:
job_url = jenkins_url + '/job/' + job + '/lastBuild/api/json'
ui.write('Checking if job is running at URL: %s\n' % job_url)
try:
job_metadata = json.load(urllib2.urlopen(job_url, timeout = TEN_SECONDS))
if 'building' in job_metadata and job_metadata['building']:
raise util.Abort('Jenkins build "%s" is in progress. Pushing is disabled until it completes.' % job_metadata['fullDisplayName'])
except urllib2.URLError, e:
raise util.Abort('Error while trying to poll Jenkins: "%s"' % e)
return False # Everything is OK, push can be accepted