Unable to get right git branch name in bash - linux

I'm working on the post-receive of my git server so that it automatically uploads the latest version of my website in a folder named after the branch that the commit was in, but somehow doing this code doesn't work as intended.
Somehow my value branch gets the values of all the branches instead of the branch I'm trying to get. Hash does get the right hash code. I have tested it outside of the program, so does branch when I type the right hash. Did I use the wrong syntax in this program?
#!/bin/sh
hash=$(git log -n 1 --pretty=format:"%h")
branch=$(git branch --contains $(git log -n 1 --pretty=format:"%H"))
if [ branch ]
then
GIT_WORK_TREE="/data/site/'$branch'"
echo "/data/site/'$branch'"
git checkout -f $branch
fi

Alright, I got it to work as I wanted! After hearing that post-receive got refname as stdin, found out that I had to trim down refname to get only the branch name and came up with this bit of code. Thanks guys. :)
#!/bin/sh
while read oldrev newrev refname
do
branch=${refname##*/}
if [ branch ]
then
path="/data/site/$branch"
mkdir $path
unset GIT_INDEX_FILE
export GIT_WORK_TREE=$path
git checkout -f $refname
echo "Successfully pushed to $path"
fi
done

Related

Git Throws Error If Nothing To Commit. How To Surpress?

I have a CI/CD pipeline in GitHub Actions that runs and one of the steps is to commit to another repository. What it does is that it clones to external repository, moves files into it, and then commits it back to the external repository.
The thing is, there is no grantee that there will be a new file to commit.
When that happens, the repository fails because Git throws an error as shown
How can I get around that?
You could use the git status --porcelain command (reference 1 + reference 2) to check if some changes occurred.
It could look like this using bash:
run:
if [[ `git status --porcelain` ]]; then
echo "OK: Changes detected."
else
echo "WARNING: No changes were detected."
fi
shell: bash
Obs: I'm using it in a action to git commit push changes.

Passing parameter to linux shell to clone from git repository

I have a script.sh that performs the "clone" operation of a git repository. Currently, the script works correctly with the target branch written in hard on the corresponding line.
/usr/bin/git clone https://my-url-repository --branch master --single-branch
If I replace "master" with "$1",
/usr/bin/git clone https://my-url-repository --branch $1 --single-branch
it can't complete the operation because it doesn't correctly take the branch and throws a fatal error.
warning: Could not find remote branch e to clone.
fatal: Remote branch e not found in upstream origin
However, if I print on screen the parameter $1 or ${1}, the entered value is displayed correctly.
#!/bin/bash
if [ -n "$1" ]; then
echo Building from branch "["$1"]"
else
echo "Please, enter branch name"
exit
fi
Can you help me?
I could not specifically solve the problem, but I did find an equally valid alternative. Instead of waiting for the parameter in the script call, within the same script I request the entry of the branch name, and then the clone is done without problems.
The code looks like this:
#!/bin/bash
echo "Please, enter branch name"
read branchName
And then I use the variable like this:
/usr/bin/git clone https://my-url-repository --branch $branchName --single-branch

How to check for the presence of a git repository in a directory using bash script

I am trying to work with git on my project.
I want to set up the terminal such that whenever I cd into a directory that contains a git project, the terminal should indicate which git branch I am currently on.
If there is a git project, the terminal show only the name of the branch,
for example
(master) $
otherwise it should show the current directory path.i.e
username#machinename:path/to/directory $
I found a similar question answered here but i don't know how to modify the answer to suit my need, because am not good with bash scripting.
Any suggestion will be highly appreciated.
Have a look at this project https://github.com/jimeh/git-aware-prompt, it should solve your whole problem and when not, you can change it to meet your needs. Main logic is in prompt.sh.
To find current git branch name in directory, you can always run
git rev-parse --abbrev-ref HEAD
It will return branch name, HEAD (when detached) or nothing when directory is not par of git repository. If you need only this information, you can update your .bashrc. Edit variable PS1, which is bash prompt format.
PS1='(`git rev-parse --abbrev-ref HEAD 2> /dev/null`) \$ '
This is example how to display branch name anywhere in the prompt. The git script will help you and recognize whether to show branch or directory. It will update your PROMPT_COMMAND, which is called every time the bash prompt line is displayed, by checking for git branch name which you can then use in PS1 as a variable. You can then update your existing PS1='${debian_chroot:+($debian_chroot)}\u#\h:\w\$ ' to
PS1='${debian_chroot:+($debian_chroot)}\u#\h:\w \(\$git_branch\)\$ '
You have many tools which do it.
myzsh for example or just a simplt bash that you add to your bashrc
http://martinvalasek.com/blog/current-git-branch-name-in-command-prompt
example:
function parse_git_branch () {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
PS1="$GREEN\u#\h$NO_COLOR:\w$YELLOW\$(parse_git_branch)$NO_COLOR\$ "
The Git package in Linux usually comes with a prompt script that you can use to see the repository status. To enable it, source the git-prompt.sh script in a shell startup file (e.g. ~/.bashrc), then set a custom prompt with the %s parameter. For example, in ArchLinux you could do:
[ -r /usr/share/git/completion/git-prompt.sh ] && . /usr/share/git/completion/git-prompt.sh
PS1='[\u#\h \W$(__git_ps1 " (%s)")]\$ '
When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt (see the link above).

Make "git pull" ask for confirmation when pulling different branch

When working with many projects and branches at the same time, I occasionally do stupid mistake like pulling into the wrong branch. For example being on branch master I did git pull origin dangerous_code and didn't notice that for quite some time. This small mistake caused a lot of mess.
Is there any way to make git ask for confirmation when I attempt to pull a branch other than branch that is currently checked out? Basically I want it to ask for confirmation if the branch name doesn't match (checked out and the one being pulled).
For now, I'll focus on how to prompt the user for confirmation before any pull is carried out.
Unfortunately, because there is no such thing as a pre-pull hook, I don't think you can get the actual pull command to directly do that for you. As I see it, you have two options:
1 - Use fetch then merge (instead of pull)
Instead of running git pull, run git fetch, then git merge or git rebase; breaking down pull into the two steps it naturally consists of will force you to double-check what you're about to merge/rebase into what.
2 - Define an alias that asks for confirmation before a pull
Define and use a pull wrapper (as a Git alias) that prompts you for confirmation if you attempt to pull from a remote branch whose name is different from the current local branch.
Write the following lines to a script file called git-cpull.sh (for confirm, then pull) in ~/bin/:
#!/bin/sh
# git-cpull.sh
if [ "$2" != "$(git symbolic-ref --short HEAD)" ]
then
while true; do
read -p "Are you sure about this pull?" yn
case "$yn" in
[Yy]*)
git pull $#;
break
;;
[Nn]*)
exit
;;
*)
printf %s\\n "Please answer yes or no."
esac
done
else
git pull $#
fi
Then define the alias:
git config --global alias.cpull '!sh git-cpull.sh'
After that, if, for example, you run
git cpull origin master
but the current branch is not master, you'll be asked for confirmation before any pull is actually carried out.
Example
$ git branch
* master
$ git cpull origin foobar
Are you sure about this pull?n
$ git cpull origin master
From https://github.com/git/git
* branch master -> FETCH_HEAD
Already up-to-date.

How to prevent remote branch deletion in git without using gitolite

Is there any way to block deletion of remote branches?
I want to block deletion of remote branches but normal flow like code checking and check out should work fine!!
without using gitolite! is it possible ?
please help !
Yes, it is possible. Just add a suitable server side git hook.
You probably want to use a pre-receive hook. For details have a look at here or here.
Example:
#create repositories
git init a
git init --bare b
#add the hook in "b"
echo -e '#!/usr/bin/bash\nread old new ref\ntest $new != 0000000000000000000000000000000000000000' >>b/hooks/pre-receive
chmod +x b/hooks/pre-receive
#create a commit in "a"
cd a
echo foo >test
git add .
git commit -m testcommit
#push it to "b"
git push ../b master
#try to delete remote branch
git push ../b :master
refs/heads/*,delete)
# delete branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a branch is not allowed in this repository" >&2
exit 1
fi
adding this in update hook solved my problem
Hope this will help someone else too
I'm not sure why you're avoiding gitolite (which is sort of the end point of all access control, as it were), but I have a sample pre-receive script here that uses hooks.* git config entries to do some simple access controls. It's not as fancy as gitolite but it does some things I cared about once. :-)

Resources