I am a self-taught developer with knowledge of Azure, C, C++, C#, Typescript/JavaScript, HTML and CSS along with several databases. Having been working in IT for over 30 years and co-founding and selling a successful company I am now working on products for the TV industry.Follow me on twitter @coderanger, Mastodon @coderanger/@dotnet.social and GitHub

Forcing Semantic Release Compatible Commits

We use the great semantic-release system for our Node projects at work, which is great for automating the version numbers and change logs.

The way it works is that you format your commit messages in a particular way to mark the changes as a ‘fix’, 'feature’ or 'breaking change’ … when semantic-release is run, it will determine what version numbers need increasing and will also generate a change log.

However, its easy to format the message incorrectly or forget completely, which will cause all sorts of issues when you try and do a release.

So I created a simple git hook to check my message format:

#!/bin/sh

# Config options

min_length=4
max_length=50
types=("feat" "fix" "perf")

# End config options


regexpstart="^("
regexp="${regexpstart}"

for type in "${types[@]}"
do
  if [ "$regexp" != "$regexpstart" ]; then
    regexp="${regexp}|"
  fi
  regexp="${regexp}$type"
done

regexp="${regexp})(\(.+\))?: "
regexp="${regexp}.{$min_length,$max_length}$"

function print_error() {
  echo -e "\n\e[1m\e[31m[INVALID COMMIT MESSAGE]"
  echo -e "------------------------\033[0m\e[0m"
  echo -e "\e[1mValid types:\e[0m \e[34m${types[@]}\033[0m"
  echo -e "\e[1mMax length (first line):\e[0m \e[34m$max_length\033[0m"
  echo -e "\e[1mMin length (first line):\e[0m \e[34m$min_length\033[0m\n"
}

# get the first line of the commit message
INPUT_FILE=$1
START_LINE=`head -n1 $INPUT_FILE`

if [[ ! $START_LINE =~ $regexp ]]; then
  # commit message is invalid according to semantic-release conventions
  print_error
  exit 1
fi

You can save the above script into your .git/hooks/ folder for any repos which exist already; or you can run the following commands that will set things up for every new repo you init in the future:

git config --global init.templatedir '~/.git-templates'
mkdir -p ~/.git-templates/hooks
cp commit-msg ~/.git-templates/hooks

Using nvmrc on Windows

Unfortunately nvm use on Windows does not change the node version to that specified in the `.nvmrc` file as its not supported on nvm for Windows.

So the easiest solution to this is to create a simple Powershell command that performs an approximation of the command which is to switch to the version specified and, if it doesn’t already exist, download and install it first: nvm use $(Get-Content .nvmrc).replace( 'v', '' );

However, thats a bit awkward and we can do a bit more so instead, we can create an ‘alias’ to a function that calls the command instead:

function callnvm() {
  $versionDesired = $(Get-Content .nvmrc).replace( 'v', '' );
  $response = nvm use $versionDesired;
  if ($response -match 'is not installed') {
    if ($response -match '64-bit') {
      nvm install $versionDesired x64
    } else {
      nvm install $versionDesired x86
    }
    nvm use $versionDesired;
  }
}
Set-Alias nvmu -value "callnvm"

Now we only need to type nvmu in a project folder for it to work properly.

However, this will only work for the current session, so to make it more useful for any project and every session; we can add this content to the Powershell Profile for the current user.

You can get the location of this file by typing $profile in a Powershell session and either edit or create the Profile file and place the content shown above into it.

Adding changes to the previous commit in Git

I end up needing to do this all the time, but thankfully its very easy to do; just stage the extra changes like normal and amend the commit:

Stage your missed changes:

git add .

Then just –amend the commit:

git commit --amend -m"Add new commit message which overwrites the previous one"

Separating a Subfolder into its own Git Repo

The Easy Way

It turns out that this is such a common and useful practice that the overlords of git made it really easy, but you have to have a newer version of git (>= 1.7.11 May 2012).

  1. Prepare the old repo

    pushd <big-repo>
    git subtree split -P <name-of-folder> -b <name-of-new-branch>
    popd

    Note: <name-of-folder> must NOT contain leading or trailing characters. For instance, the folder named subproject MUST be passed as subproject, NOT ./subproject/

    Note for windows users: when your folder depth is > 1, <name-of-folder> must have *nix style folder separator (/). For instance, the folder named path4\\path5\\subproject MUST be passed as path4/path5/subproject

  2. Create the new repo

    mkdir <new-repo>
    pushd <new-repo>
    
    
    git init
    git pull </path/to/big-repo> <name-of-new-branch>
    
  3. Link the new repo to Github or wherever

    git remote add origin <[email protected]:my-user/new-repo.git>
    git push origin -u master
  4. Cleanup, if desired

    popd # get out of <new-repo>
    pushd <big-repo>
    
    
    git rm -rf <name-of-folder>

    Note: This leaves all the historical references in the repository.See the Appendix below if you’re actually concerned about having committed a password or you need to decreasing the file size of your .git folder.

Clearing your history

By default removing files from git doesn’t actually remove them from git, it just commits that they aren’t there anymore. If you want to actually remove the historical references (i.e. you have a committed a password), you need to do this:

git filter-branch --tree-filter 'rm -rf <name-of-folder>' HEAD

After that you can check that your file or folder no longer shows up in the git history at all

git log -S<name-of-folder> # should show nothing

However, you can’t “push” deletes to github and the like. If you try you’ll get an error and you’ll have to git pull before you can git push - and then you’re back to having everything in your history.

So if you want to delete history from the “origin” - meaning to delete it from github, bitbucket, etc - you’ll need to delete the repo and re-push a pruned copy of the repo. But wait - there’s more! - If you’re really concerned about getting rid of a password or something like that you’ll need to prune the backup (see below).

Making .git smaller

The aforementioned delete history command still leaves behind a bunch of backup files - because git is all too kind in helping you to not ruin your repo by accident. It will eventually deleted orphaned files over the days and months, but it leaves them there for a while in case you realize that you accidentally deleted something you didn’t want to.

So if you really want to empty the trash to reduce the clone size of a repo immediately you have to do all of this really weird stuff:

rm -rf .git/refs/original/ && \\
git reflog expire --all && \\
git gc --aggressive --prune=now

git reflog expire --all --expire-unreachable=0
git repack -A -d
git prune

That said, I’d recommend not performing these steps unless you know that you need to - just in case you did prune the wrong subdirectory, y'know? The backup files shouldn’t get cloned when you push the repo, they’ll just be in your local copy.

Credit

Merging Two Git Commits

Quite often I make a commit to Git and then realise I missed a change and have to make another commit; they both solve the same issue so I just want to merge them to tidy it up.

Here is an easy way, assuming you want to merge or squash, in Git palance, the last two commits:

# Reset the current branch to the commit just before the last 2:
git reset --hard HEAD~2

# HEAD@{1} is where the branch was just before the previous command.
# This command sets the state of the index to be as it would just
# after a merge from that commit:
git merge --squash HEAD@{1}

# Commit those squashed changes.  The commit message will be helpfully
# prepopulated with the commit messages of all the squashed commits:
git commit  

I found this from one of the answers (not the accepted answer) on Stackoverflow