Skip to content

Instantly share code, notes, and snippets.

@helciodasilva
Last active April 22, 2020 15:23
Show Gist options
  • Save helciodasilva/d9b20b0448001a2dbb139e80a33c7666 to your computer and use it in GitHub Desktop.
Save helciodasilva/d9b20b0448001a2dbb139e80a33c7666 to your computer and use it in GitHub Desktop.
Include topic branch

git hooks

Enable hook

Indiviual repository

mv .git/hooks/commit-msg.sample .git/hooks/commit-msg
chmod +x .git/hooks/commit-msg
vim .git/hooks/commit-msg

Enable Globally

git config --global core.hooksPath /e/dev/.git/hooks

Enable git hook templates

# This tells git to copy everything in ~/.git-templates to your per-project .git/ directory when you run git init
git config --global init.templatedir '~/.git-templates'

# Create a directory to hold the global hooks
mkdir -p ~/.git-templates/hooks

# Write your hooks in ~/.git-templates/hooks.
touch ~/.git-templates/hooks/post-commit

# Make sure the hook is executable.
chmod a+x ~/.git-templates/hooks/post-commit

# Re-initialize git in each existing repo you'd like to use this in:
git init

Examples

Automatically Prepend a Jira Issue ID to Git Commit Messages

prepare-commit-msg

#!/bin/bash

# get current branch
branchName=`git rev-parse --abbrev-ref HEAD`

# search jira issue id in a pattern such a "feature/ABC-123-description"
jiraId=$(echo $branchName | sed -r 's/^(feature|topic)\/(.*)/\2/')

# 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/^/$jiraId: /" $1
fi
git branch
* feature/MARK-01

git commit -m "Add placeholders on the options page instead of defaults"
[feature/MARK-01 b558e7b] MARK-01: Add placeholders on the options page instead of defaults
 1 file changed, 1 insertion(+), 1 deletion(-)

Prevent commits in master branch

pre-commit

#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ] || [ "$branch" = "develop" ]; then
  echo "You can't commit directly to $branch branch"
  exit 1
fi
$ git branch
* develop
  feature/MARK-01
  master

git commit -m "Add placeholders on the options page instead of defaults"
You can't commit directly to develop branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment