How do I deploy the master branch if no tag is specified using Capistrano? - capistrano

Here's what I have in my deploy.rb but this always deploys a tag. If I don't specify the tag, I want to deploy master.
set :branch, "master"
set :branch do
default_tag = `git tag`.split("\n").last
tag = Capistrano::CLI.ui.ask "Tag to deploy (make sure to push the tag first): [#{default_tag}] "
tag = default_tag if tag.empty?
tag
end

Well of course this always deploys a tag because of this line tag = default_tag if tag.empty?
If you set master to the default tag like below it will deploy master unless you specify a tag.
set :branch do
default_tag = `git tag`.split("\n").last
tag = Capistrano::CLI.ui.ask "Tag to deploy (make sure to push the tag first): [#{default_tag}] "
if tag.empty?
'master'
else
tag
end
end
Note this is untested

Related

How to get source branch from google cloud build trigger on push when merging

I am merging 'feature-branch' onto 'dev-branch' from a github pull request. I am using a google cloud build trigger that is triggered on push to 'dev-branch'. From what I can tell in the documentation of substitution variables, there are no substitution variables to get the name of the branch that I am merging from - 'feature-branch' and only the branch that I merging to - 'dev-branch'. Is there a way or a workaround to get information (name, sha, id, etc.) of the branch that is being merged from on a google cloud build trigger from a push to branch event?
Presumably you can have some naming conventions on the first line of the commit message (happens at merge pull request "event"), so that this line includes the source (or head) branch name (the source of the merge - in your words - 'feature-branch').
Then, you can create a substitution variable:
substitutions:
_COMMIT_MESSAGE: $(commit.commit.message)
here is a documentation link: Creating substitutions using payload bindings
And use that variable in some build step to get the the head branch name:
mapfile -t commit_lines <<< "${_COMMIT_MESSAGE}"
source_branch="$(echo ${commit_lines[0]} | <<add your command here following naming convention for the commit message>> )"
echo "=> My source branch name: ${source_branch}"
After that you can use the source branch name.

Gitlab CI pipeline failing: a tag issue

My gitlab CI pipeline is setup to run maven tests from a docker image created from my maven project.
I have tested the pipeline on my master branch and it worked fine and ran the test.
However I have created a new feature branch and now running the pipeline yet again, however I now get this error
error checking push permissions -- make sure you entered the correct tag name, and that you are authenticated correctly, and try again: getting tag for destination: repository can only contain the runes `abcdefghijklmnopqrstuvwxyz0123456789_-./`: it2901/cs344-maven:feature/produce-allocation-pdf
ERROR: Job failed: command terminated with exit code 1
I can't seem to pinpoint the problem at all. I have also pushed the tag: tut3 to the feature branch as well.
Here is my .gitlab-ci.yml: https://controlc.com/7a94a00f
Based on what you shared, you have this configured:
VERSIONLABELMETHOD: "tut3" # options: "","LastVersionTagInGit"
It should be either:
VERSIONLABELMETHOD: ""
or
VERSIONLABELMETHOD: "LastVersionTagInGit"
or
VERSIONLABELMETHOD: "OnlyIfThisCommitHasVersion"
When you specify "tut3", the script takes it as if it was "" (empty string). Assuming you didn't define $VERSIONLABEL anywhere $ADDITIONALTAGLIST will also be empty.
And later in the code you can see that this gets executed:
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then ADDITIONALTAGLIST="$ADDITIONALTAGLIST latest"; fi
Assuming $CI_DEFAULT_BRANCH is set to master if you use a separate branch mybranch the code above won't get executed so it's likely that the Kaniko command line doesn't have any a neither a valid $FORMATTEDTAGLIST or $IMAGE_LABELS.
You can debug by seeing their output on the script which is happening at the end before calling Kaniko:
...
echo $FORMATTEDTAGLIST
echo $IMAGE_LABELS
mkdir -p /kaniko/.docker
...
A hack would be to override $CI_DEFAULT_BRANCH with your custom branch.
✌️

Fail a merge or build if a particular file has changed?

On VSTS, we have some files we want to protect on certain branches. How can one fail a merge/build if a particular file has changed?
First prize is to configure this on the build server, which in this case is VisualStudio.com (VSTS / GIT).
Scenario: we have various release branches v1, v2, v3. We want to protect the packages.json file to prevent anyone updating Nuget packages on these branches. So if the package.json file has changed on a pull request into "v3", don't allow the merge.
For Git, you can protect a certain branch (not a certain file), then all the files exist in the branch will be protected.
You can use Branch security which users/groups can contribute for the branch.
Or you can use Branch Policies to protect not commit changes on the branch directly but use pull request to make changes etc.
Or you can lock a branch to prevent updating.
To expanded Starain's answer:
First create a build definition for the branch you want to protected (such as select V3 branch in get sources step). And add a powershell task with the content below:
$head=$(git rev-parse HEAD)
$parents=$(git rev-list --parents -n 1 $head)
$p1,$p2,$p3=$parents.split(' ')
If ($p1 = $head)
{
$parent1=$p2
$parent2=$p3
}
ElseIf ($p2 = $head)
{
$parent1=$p1
$parent2=$p3
}
Else
{
$parent1=$p1
$parent2=$p2
}
$outp1=$(git diff $head $parent1 --name-only)
$outp2=$(git diff $head $parent2 --name-only)
If ($outp1 -contains 'package.json')
{
echo "changed the specified file on the branch which contains commit $parent1"
exit 1
}
If ($outp2 -contains 'package.json')
{
echo "changed the specified file on the branch which contains commit $parent2"
exit 1
}
So that when the file package.json has been change, powershell script will fail the build result.
Then add the branch policy for the branch which you want to protect.
Add build policy -> select the build definition you just created -> Policy requirement as Required -> Build expiration 0.1 hours (6 min) or other values since it’s every fast to queue a build with a powershell task -> save.
You can try to do it in the build, simple workflow:
Configure branch policy for a succeed build required
Check whether the specific file changed in that build
Fail build if specific file has been changed
You can put a required reviewer for a particular folder/file in VSTS for a particular branch.
In this way the person won't be able to check-in without getting an approval from the required reviewer.
Git doesn't really work that way; individual files don't have any sort of security on them.
You could use a pre-commit hook, but it's important to note that those hooks are client-side, not server-side -- each user would have to set up a pre-commit hook.
VSTS/TFS doesn't support Git server hooks (at least, not to the extent that it can block a push), otherwise a pre-receive or update hook would be exactly what you want.

Referencing current branch in github readme.md

In my github repo's readme.md file I have a Travis-CI badge. I use the following link:
https://travis-ci.org/joegattnet/joegattnet_v3.png?branch=staging
The obvious problem is that the branch is hardcoded. Is it possible to use some sort of variable so that the branch is the one currently being viewed?
Not that I know of.
GitHub support confirms (through OP Joe Gatt 's comment)
The only way to do this would be to pass the link through my own service which would use the github's http referrer header to determine which branch is being referenced and then fetch the appropriate image from Travis CI
I would rather make one Travis-CI badge per branch, for the reader to choose or consider the appropriate when seeing the README.md.
Update 2016 (3 years later): while nothing has changed on the GitHub side, fedorqui reports in the workaround mentioned in "Get Travis Shield on Github to Reflect Selected Branch Status" by Andrie.
Simply display all the branches and their respective TravisCI badges.
If you have only two or three branches, that could be enough.
I worked around this issue with a git pre-commit hook that re-writes the Travis line in the README.md with the current branch. An example of usage and pre-commit (Python) code (for the question as asked) are below.
Usage
dandye$ git checkout -b feature123 origin/master
Branch feature123 set up to track remote branch master from origin.
Switched to a new branch 'feature123'
dandye$ echo "* Feature123" >> README.md
dandye$ git add README.md
dandye$ git commit -m "Added Feature123"
Starting pre-commit hook...
Replacing:
[![Build Status](https://travis-ci.org/joegattnet/joegattnet_v3.png?branch=master)][travis]
with:
[![Build Status](https://travis-ci.org/joegattnet/joegattnet_v3.png?branch=feature123)][travis]
pre-commit hook complete.
[feature123 54897ee] Added Feature123
1 file changed, 2 insertions(+), 1 deletion(-)
dandye$ cat README.md |grep "Build Status"
[![Build Status](https://travis-ci.org/joegattnet/joegattnet_v3.png?branch=feature123)][travis]
dandye$
Python code for the pre-commit code
dandye$ cat .git/hooks/pre-commit
#!/usr/bin/python
"""
Referencing current branch in github readme.md[1]
This pre-commit hook[2] updates the README.md file's
Travis badge with the current branch. Gist at[4].
[1] http://stackoverflow.com/questions/18673694/referencing-current-branch-in-github-readme-md
[2] http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
[3] https://docs.travis-ci.com/user/status-images/
[4] https://gist.github.com/dandye/dfe0870a6a1151c89ed9
"""
import subprocess
# Hard-Coded for your repo (ToDo: get from remote?)
GITHUB_USER="joegattnet"
REPO="joegattnet_v3"
print "Starting pre-commit hook..."
BRANCH=subprocess.check_output(["git",
"rev-parse",
"--abbrev-ref",
"HEAD"]).strip()
# String with hard-coded values
# See Embedding Status Images[3] for alternate formats (private repos, svg, etc)
# [![Build Status](https://travis-ci.org/
# joegattnet/joegattnet_v3.png?
# branch=staging)][travis]
# Output String with Variable substitution
travis="[![Build Status](https://travis-ci.org/" \
"{GITHUB_USER}/{REPO}.png?" \
"branch={BRANCH})][travis]\n".format(BRANCH=BRANCH,
GITHUB_USER=GITHUB_USER,
REPO=REPO)
sentinel_str="[![Build Status]"
readmelines=open("README.md").readlines()
with open("README.md", "w") as fh:
for aline in readmelines:
if sentinel_str in aline and travis != aline:
print "Replacing:\n\t{aline}\nwith:\n\t{travis}".format(
aline=aline,
travis=travis)
fh.write(travis)
else:
fh.write(aline)
subprocess.check_output(["git", "add", "README.md" ])
print "pre-commit hook complete."
I updated the work of Dan Dye so it's now able to change any git variable into a readme. It also works now with python 3. For example, handling badges by branch for Github actions:
[![Integration Tests](https://github.com/{{ repository.name }}/actions/workflows/integration-tests.yaml/badge.svg?branch={{ current.branch }})](https://github.com/{{ repository.name }}/actions/workflows/integration-tests.yaml?query=branch%3A{{ current.branch }})
And in your pre-commit file add:
.githooks/replace_by_git_vars.py readme.md README.md -v
-v displays the available variables and more
https://gist.github.com/jclaveau/af2271b9fdf05f7f1983f492af5592f8
Thanks a lot for the solution and inspiration!
The best solution for me was to create a server where I send a query with username and repo's name and get a svg image with the build status for all branches.

Orphan branch in libgit2sharp

How do you create an orphan branch in libgit2sharp?
All i could find are methods which create a branch which points to a commit.
I'm looking for an effect similar to the command:
git checkout --orphan BRANCH_NAME
git checkout --orphan BRANCH_NAME actually moves the HEAD to an unborn branch BRANCH_NAME without altering the working directory nor the index.
You can perform a similar operation with LibGit2Sharp by updating the target of the HEAD reference with repo.Refs.UpdateTarget() method.
The following test demonstrates this
[Fact]
public void CanCreateAnUnbornBranch()
{
string path = CloneStandardTestRepo();
using (var repo = new Repository(path))
{
// No branch named orphan
Assert.Null(repo.Branches["orphan"]);
// HEAD doesn't point to an unborn branch
Assert.False(repo.Info.IsHeadUnborn);
// Let's move the HEAD to this branch to be created
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan");
Assert.True(repo.Info.IsHeadUnborn);
// The branch still doesn't exist
Assert.Null(repo.Branches["orphan"]);
// Create a commit against HEAD
var signature = new Signature("Me", "me#there.com", DateTimeOffset.Now);
Commit c = repo.Commit("New initial root commit", signature, signature);
// Ensure this commit has no parent
Assert.Equal(0, c.Parents.Count());
// The branch now exists...
Branch orphan = repo.Branches["orphan"];
Assert.NotNull(orphan);
// ...and points to that newly created commit
Assert.Equal(c, orphan.Tip);
}
}