Losing the fat after an all inclusive git commit

Many of us, myself included, are guilty of getting carried away in the heat of the moment and all too quickly committing code to a fresh repository before adding a .gitignore to exclude surplus files. Wincing as you see that beautifully clean repository start to fill up with compiled objects, user preferences and 10MBs of generated garbage. At this point most of us will haphazardly throw a .gitignore file into the repository hoping that it'll magically exclude all those files from the previous commit... but it doesn't!

So, now you need to rectify your mistake by untracking all of those extra files.

Easy I hear you cry!
git rm --cached path/to/file

Perfect, now just walk through your codebase and apply that to all 3000 unwanted files...

...in this situation you may be tempted to create a new repository and move your necessary code across, and this is one potential solution. However, there is a much easier and more effective solution.

For Windows Users (Using PoshGit)

Open a new Powershell session and run the following command:

Add the following 2 highlighted lines to your $profile to create a new aliased command: git-ignore

For copying purposes:

function git-applyignore { git ls-files -ci --exclude-standard | foreach { git rm --cached $_ } } 
Set-Alias -Name git-ignore -Value git-applyignore

Now restart your Powershell session. This should allow you to retrospectively apply .gitignore rules to an all inclusive git repository by running the command git-ignore from the repository's root.

Note: You could also add the alias to your ~/.gitconfig in Windows like I have for the Linux user below.

For Linux Users

Run the following command to create a new globally assigned git alias

git config --global alias.ignore '!git ls-files -ci --exclude-standard -z | xargs -0r git rm --cached'

This will add the an [alias] section to your global .gitconfig file (assuming one doesn't already exist) and insert a new alias 'ignore'

You can now use the 'git ignore' command as shown below