Git server-side pre-receive hook - bash

I am working on enforcing git pre-commit hook as a server-side pre-receive or an update hook and unable to find proper examples on achieving it.
I was able to successfully implement/test the pre-commit hook
#!/bin/bash
echo "Running pre-commit hook"
checks=($APPSETTING_DEVPASSWORD $APPSETTING_DEVUSER $APPSETTING_DEVPASS_ELMAH) # create an array
git diff --cached --name-status | while read flag file; do
if [ "$flag" == 'D' ]; then continue; fi
for word in ${checks[#]}
do
if egrep -q "$word" "$file"; then
echo "ERROR: Disallowed expression \"${word}\" in file: ${file}" >&2
exit 1
fi
done
done
I am trying to translate the same into server-side hook where the hook should look for the checks array and exit with 1 if the diff contains the values in the checks array.
Information Found online
Bitbucket server contains only the base repository and doesn't contain the files from the local repository, Hence the diff of the commit sha needs to be evaluated while pushing.
Can someone please help translate the same into a server-side git hook.

Related

Get commit message in Git hooks

I would like to create commit-msg hook to check the commit message with some regex. So I wrote this bash script in the hooks folder:
#!/bin/sh
valid_commit_msg_regex="^[0-9]+:[a-zA-Z0-9-_ ]{20,150}$"
message="This commit violates the commit message rules. Please rename your commit."
if [[ ! $(cat $1) =~ $valid_commit_msg_regex ]]
then
echo "$message"
exit 1
fi
exit 0
But when I try to write git commit -m "9: texttexttexttexttexttexttexttext" it doesn't work properly and I get the error message from script.
Does anyone has an idea what's gone wrong?
I see two issues:
Double brackets [[ comes from bash. Change shebang to #!/bin/bash
in [a-zA-Z0-9-_ ] you have to escape - with \-

Access the changes files in git pre-receive hook & search for string pattern

I have one pre-commit script/hook working just fine to search for specific string pattern in the files and reject the commit. I'm not sure how to read the incoming files in the pre-receive script to search for string pattern.
My pre-commit scripts looks like this:
#!/usr/bin/env bash
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
EMPTY_TREE=$(git hash-object -t tree /dev/null)
against=$EMPTY_TREE
fi
FILES=$(git diff --cached --name-only $against)
if [ -n "$FILES" ]; then
string1 = $(grep -rE --line-number 'access_key' $FILES)
if [ -n "$string1" ] then
echo "string1 there so reject it"
while true; do
exit 1;
done
fi
fi
I'm not sure how to convert this to a pre-receive hook script on git server side.
I've been trying this for hours with no luck. Can someone please help me out here?

Pre-commit hook to check for Jira issue key

I am looking for somehelp to write a pre-commit hook on windows to check for Jira issue key while commiting.Commit should not be allowed if Jira key is not present.I couldnt find any way.I am new to scripting.Any help would be highly appreciated.
I assume you are talking about a hooks in a Git repository.
Navigate to your local Git repository and go into the folder .git\hooks
Create a file named commit-msg
Insert the following content (no idea how to format it correctly)
#!/bin/bash
# The script below adds the branch name automatically to
# every one of your commit messages. The regular expression
# below searches for JIRA issue key's. The issue key will
# be extracted out of your branch name
REGEX_ISSUE_ID="[a-zA-Z0-9,\.\_\-]+-[0-9]+"
# Find current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
if [[ -z "$BRANCH_NAME" ]]; then
echo "No branch name... "; exit 1
fi
# Extract issue id from branch name
ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID")
echo "$ISSUE_ID"': '$(cat "$1") > "$1"
If you have now a branch named like feature/MYKEY-1234-That-a-branch-name
and add as commit message "Add a new feature"
Your final commit message will look like
MYKEY-1234: Add a new feature
You can put the hook globally when using Git 2.9.
Please find here further useful information:
https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
Git hooks : applying `git config core.hooksPath`
You have to put the following script in your local Git repository at .git/hooks/prepare-commit-msg. This will be run whenever you add a new commit.
#!/bin/bash
# get current branch
branchName=`git rev-parse --abbrev-ref HEAD`
# search jira issue id in pattern
jiraId=$(echo $branchName | sed -nr 's,[a-z]*\/*([A-Z]+-[0-9]+)-.+,\1,p')
# only prepare commit message if pattern matched and jiraId was found
if [[ ! -z $jiraId ]]; then
# $1 is the name of the file containing the commit message
sed -i.bak -e "1s/^/\n\n$jiraId: /" $1
fi
First, we get the branch name, for example feature/JIRA-2393-add-max-character-limit.
Next, we extract the key, removing the prefix feature.
The resulting commit message will be prefixed by "JIRA-2393: "
The script also works when there is no prefix, e.g. without feature/, bugfix/, etc.
You can use git server-side pre-receive hook.
https://git-scm.com/docs/git-receive-pack
In the code below for a successful push, you must specify the Jira issue key in the comment for commit.
#!/bin/bash
#
# check commit messages for JIRA issue numbers
# This file must be named pre-receive, and be saved in the hook directory in a bare git repository.
# Run "chmod +x pre-receive" to make it executable.
#
# Don't forget to change
# - Jira id regex
jiraIdRegex="\[JIRA\-[0-9]*\]"
error_msg="[POLICY] The commit doesn't reference a JIRA issue"
while read oldrev newrev refname
do
for sha1Commit in $(git rev-list $oldrev..$newrev);
do
echo "sha1 : $sha1Commit";
commitMessage=$(git log --format=%B -n 1 $sha1Commit)
jiraIds=$(echo $commitMessage | grep -Pqo $jiraIdRegex)
if ! jiraIds; then
echo "$error_msg: $commitMessage" >&2
exit 1
fi
done
done
exit 0

How to make a git pre-commit hook that checks the commit message?

I have a git commit hook script, that checks the commit message, and if the message does not contain the word "updated", the script should reject the commit.
#!/bin/bash
read -p "Enter a commit message: " message
if [[ ${message} != *"updated"* ]];then
echo "Your commit message must contain the word 'updated'"
else
git commit -m "$message"
fi
How to make this hook automatically execute if I try to push some files in my local repo using the command
git commit -m "updated:something"
My idea is to make it not like "run this script to do commit", but rather when you open the console and try to make a commit and entering the commit message, the script will check your commit message automatically and pass it or reject it.
Taking commit-msg for example.
#!/bin/bash
MSG="$1"
if ! grep -qE "updated" "$MSG";then
cat "$MSG"
echo "Your commit message must contain the word 'updated'"
exit 1
fi
chmod 755 commit-msg and copy it as .git/hooks/commit-msg.

Git Bash Script Check Working Tree

Is there a way in Git Bash to check if the working tree is clean, that is no uncommitted changes or untracked files?
I'm working on a bash script for my group to automate the process of daily rebasing working branches. Unclean working trees is a common problem. I can manually correct the problem by executing git checkout .. This would have the desired result most of the time, but not always, so I need to be able to have my script programatically check that the working directory/tree is clean.
The git-sh-setup script included with git contains a number of useful functions for working with git repositories. Among them is require_clean_work_tree:
require_clean_work_tree () {
git rev-parse --verify HEAD >/dev/null || exit 1
git update-index -q --ignore-submodules --refresh
err=0
if ! git diff-files --quiet --ignore-submodules
then
echo >&2 "Cannot $1: You have unstaged changes."
err=1
fi
if ! git diff-index --cached --quiet --ignore-submodules HEAD --
then
if [ $err = 0 ]
then
echo >&2 "Cannot $1: Your index contains uncommitted changes."
else
echo >&2 "Additionally, your index contains uncommitted changes."
fi
err=1
fi
if [ $err = 1 ]
then
test -n "$2" && echo >&2 "$2"
exit 1
fi
}
This is in addition to being able to check the output from git status --porcelain and/or git status -z if you need to be more specific about what the state currently is.

Resources