Files
MarkdownNotes/git tricks.md
2023-04-27 14:37:44 -04:00

3.8 KiB

Git Tricks

Rename the master branch

NOTE: This only works in your local repository BEFORE pushing to a remote

git branch -m master main

mass rename

Example: For each .txt file, git mv it to itself, replacing the extension .txt with .md

for i in $(find . -iname "*.txt"); do git mv "$i" "$(echo $i | rev | cut -d '.' -f 2- | rev).md"; done

Git hooks

Git has a built-in powerful automation platform called Git hooks. Git hooks allows you to execute scripts that will run when certain events happen in Git. You can write scripts in any scripting language you prefer that is available to your environment. There are 17 hooks available.

If you look in any repo's .git/hooks folder, you see a collection of .sample files. These are pre-written samples meant to get you started. Some of them contain some odd-looking code. Odd, perhaps, until you remember that these mainly were added to serve the original use case for Linux kernel work and were written by people living in a sea of Perl and Bash scripts. You can make the scripts do anything you want.

Here's an example of a hook I use for personal repos:

#!/sur/bin/env bash
curl https://icanhazdadjoke.com
echo “”

In this example, every time I run git commit but before the commit message is committed to my Git history, Git executes the script. (Thanks to Edward Thomson's git-dad for the inspiration.)

Of course, you can do practical things, too, like checking for hardcoded secrets before making a commit. To read more about Git Hooks and to find many, many example scripts, check out Matthew Hudson's fantastic GitHooks.com site.


List top 3 oldest commits on all branches

for branch in `git branch --format='%(refname:short)'`; do echo $branch; git log --format="%cs, %cr, %an, %ae" $branch | sort -r | head -3; done

Example:

add-windows
2023-01-26, 5 days ago, chawley (tfadmin), chawley@overdrive.com
2023-01-26, 5 days ago, Charles Hawley, 56652268+chawley-od@users.noreply.github.com
2022-12-13, 7 weeks ago, chawley (tfadmin), chawley@overdrive.com
main
2023-01-26, 5 days ago, chawley (tfadmin), chawley@overdrive.com
2023-01-26, 5 days ago, Charles Hawley, 56652268+chawley-od@users.noreply.github.com
2022-12-13, 7 weeks ago, chawley (tfadmin), chawley@overdrive.com

git merge dry-run

As noted previously, pass in the --no-commit flag, but to avoid a fast-forward commit, also pass in --no-ff, like so:

git merge --no-commit --no-ff $BRANCH

To examine the staged changes:

git diff --cached

And you can undo the merge, even if it is a fast-forward merge:

git merge --abort

make it a shell function

Add to .zsh_functions or .bash_functions

# git testmerge
testmerge() {
    git merge --no-commit --no-ff $1
    git diff --cached
    git merge --abort
}

Reference