Skip to content

yousinix/git-for-wizards

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 

Repository files navigation

Git for Wizards

This repo is about, yeah you guessed it right, Git & GitHub. I will be exposing most of the magic spells that I have learned and the magic wands that I use regularly.

Found this Helpful?
Show some support to help improve this repo and expose more magic spells!

followers endorsements


Table of Contents


1. Magic Wands

Magic Wands are the tools and the extensions that you can use to improve your workflow and magic skills.

1.1. Git Command Line Tools

  1. hub: A command-line tool that makes git easier to use with GitHub.
  2. git-sizer: Compute various size metrics for a Git repository, flagging those that might cause problems.
  3. git-quick-stats: A simple and efficient way to access various statistics in git repository.

1.2. GitHub Chrome Extensions

  1. GitHub-Dark + Overlay-Scrollbars: Dark GitHub style.
  2. octolinker: Allow navigation through code on GitHub more efficiently.
  3. github-repo-size: Display repository size on GitHub.
  4. git-history-browser-extension: Add a button to the github file interface to see its history.
  5. github-file-icon: Gives different filetypes different icons in GitHub.

1.3. VS Code Extensions

  1. GitLens: Supercharges the Git capabilities built into Visual Studio Code.
  2. Git Blame: See git blame information in the status bar.
  3. Git Graph: View a Git Graph of your repository, and easily perform Git actions from the graph.
  4. Code Spell Checker: A basic spell checker that works well with camelCase code. No more "Fix Typo" commits.
  5. Markdown Preview Github Styling: Changes VS Code's built-in markdown preview to match Github's style.
  6. Markdown TOC: Markdown TOC (Table Of Contents) Plugin for Visual Studio Code.
  7. markdownlint: Markdown linting and style checking for Visual Studio Code.

1.4. Update Git to Latest Version

No matter how many wands you use, keeping your primary wand up-to-date is still your duty.

  1. First, check your git version

    git --version
  2. Then use only one of the following commands according to your git version

    git update                    # version between 2.14.2 and 2.16.1
    git update-git-for-windows    # version is equal to greater Git 2.16.1(2)

2. Avada Kedavra

Avada Kedavra is your magic spell to get rid of all the dead branches and files.

2.1. Clean Local Untracked Files

Casting spells for the first time isn't that safe, so you have to see which files will be deleted before you run the actual command.

git clean -n

Then when you are comfortable use the -f or -fd option.

git clean -f     # Cleans files only without cleaning directories
git clean -fd    # Cleans files & directories

2.2. Delete All Branches Except master

Your repo is getting messy, a lot of branches that you no longer need. No need to worry, a simple magic spell can get most of the work done for you.

git branch | grep -v 'master' | xargs git branch -D

You can replace master with any other branch name that you want to keep, but be careful this will delete master.
Or even use a pattern of more than one branch to keep them and delete the rest.

git branch | grep -v 'master\|gh-pages' | xargs git branch -D

2.3. Delete Remote-tracking Branches

Deleting local branches doesn't clean the repo 100%, since they were tracking remote branches, so you will need to burn all those references to the ground. (This will only work if you've already deleted the remote branch from your GitHub repo)

git fetch --prune

2.4. Delete an Entire Commit

Deleting a commit is somehow dangerous, since the SHA of all following commits will change. Please be careful using this!

git rebase --onto <commit-SHA>^ <commit-SHA>

2.5. Clean the Stash

Sometimes you need to rollback to a clean working directory without losing your changes, so you stash them away using the stash command. But it always can get messy; as this command stashes away the dirty changes in the stash list (more of a stack actually), So after a few stashes you're gonna end up with an outstretched list of stashes.

git stash list

You can always clean the whole stash list using a single a simple magic spell

git stash clear

Or you can remove one stash entry at a time using another magic spell

git stash drop

CAUTION!: Those stash entries will then be subject to pruning, and may be impossible to recover


3. Reparo

Reapro is a spell that help you fixing your repository history.

CAUTION!: Remember that those spells rewrite history, every commit included in the range will be rewritten. Don’t include any commit you’ve already pushed to a central server — doing so will confuse other developers by providing an alternate version of the same change

3.1. Rebase Without Changing Dates

Whenever you use git rebase, the CommitDate and SHA are updated to current date.

                    [Before rebase]                    |                     [After rebase]
                                                       |
    commit e7ee3464aa3c133df6f5ee622be863bc855dc8fd    |    commit eda7945c8d944e78d226b13a5c7280977f65a8c6
    Author:     Youssef Raafat <...>                   |    Author:     Youssef Raafat <...>
    AuthorDate: Sun Jun 30 02:05:07 2019 +0200         |    AuthorDate: Sun Jun 30 02:05:07 2019 +0200
    Commit:     Youssef Raafat <...>                   |    Commit:     Youssef Raafat <...>
    CommitDate: Sun Jun 30 02:05:07 2019 +0200         |    CommitDate: Mon Jul 1 02:06:20 2019 +0200
                                                       |
        Added New Feature                              |        Added New Feature
                                                       |

To avoid this from happening, use the --committer-date-is-author-date. But be careful that this option doesn't work with both -i and --root.

git rebase --committer-date-is-author-date

3.2. Set Committer Date to Author Date for Multiple Commits

Let's say we have about 10 commits that the CommitDate is not the same as the AuthorDate and we want them to be the same.

git rebase <first-bad-commit-SHA>^ --committer-date-is-author-date

Tip: Use git log --format=fuller to see both CommitDate & AuthorDate.

3.3. Set Commit's Date to Custom Date

You made a commit 2 days ago, and God knows for whatever reason you want to change that date to be today's or another date. Don't freak out, this is possible!

  1. Rebase to before said commit and stop for amendment.

    git rebase -i <commit-SHA>^
  2. Replace pick with edit on the line with that required commit (the first line usually).

  3. Use one of the following commands depending on your needs.

    # [1] Use today's date:
    GIT_COMMITTER_DATE="$(date)"
    git commit --amend --no-edit --date "$(date)"
    
    # [2] Use custom date:
    GIT_COMMITTER_DATE="Mon Jul 1 02:06:20 2019 +0200"
    git commit --amend --no-edit --date "Mon Jul 1 02:06:20 2019 +0200"

4. Expecto Patronum

Expecto Patronum is a spell for summoning stuff to help you and ease your life.

4.1. Generate .gitignore from Git Bash

Too lazy to copy and paste or download your .gitignore file each time you create a new repository? Try out this simple spell.

curl -s https://www.gitignore.io/api/{your_list} >> .gitignore

Replace {your_list} with a comma-separated-list (one or more) of Operating System or IDE or Programming Language, here are some examples:

  • https://www.gitignore.io/api/windows
  • https://www.gitignore.io/api/visualstudio
  • https://www.gitignore.io/api/c++
  • https://www.gitignore.io/api/linux,intellij,java

4.2. Export Repository's Archive

GitHub has Download as .zip option in all hosted repositories, but is it possible to achieve the same result using only your git bash? Surely it's, maybe that's why we wrote this spell and your are reading it now.

git archive master --output=master.zip

4.3. Discover Bugs Using git bisect

Finding bugs in long git histories isn't that easy, but by summoning a Patronus to help you hunting them and discover when you introduced a bug in your code, it will be much easier.

  1. To start the binary search process, you will need to checkout to your latest commit first, then provide git with 2 commits to search for the bug within, the last good commit and the commit that first introduced the bug

    git checkout <your-branch-name>
    git bisect start
    git bisect good <SHA-for-good-commit>
    git bisect bad <SHA-for-bad-commit>
  2. Git will ask for your feedback on some commits, so you will need to tell it if the commit is good or bad, use one of the following commands to do so:

    git bisect good
    git bisect bad
  3. When done, Git will guide you to bugged commit. You will need to exit the binary search process afterwards by using the following command:

    git bisect reset

5. Obliviate

Obliviate is a spell used to wipe memories, to forget about things, like old git histories, and start fresh.

5.1. Create Orphan Branch

Orphan branches aren't based on any other branches.The first commit made on this new orphan branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.
If you are using GitHub Pages this might be helpful as you can create a new branch named gh-pages. This branch is “orphaned” and therefore completely separate from your repository’s prior history.

                                                      |
              i---j---k     <== branch 'feature-1'    |
             /                                        |    a---b---c---d       <== branch 'master'
    a---b---c---d---h---l   <== branch 'master'       |
         \         /                                  |        1---2---3---4   <== branch 'gh-pages' (orphan)
          e---f---g         <== branch 'feature-2'    |
                                                      |
                   [Normal Branches]                  |                    [Orphan Branch]

To create a new empty orphan branch, use the following commands

git checkout --orphan <new-branch-name>
rm .git/index
git clean -fdx

5.2. Clean Data out of Repository History

For whatever reason, one day, you committed a file containing some Passwords and Credentials and some large video files. Seriously dude? What was going on your mind when you did this? But don't worry, there's a great tool called BFG that will help you remove Crazy Big Files, Passwords, Credentials & other Private data out of your Git repository history.

  1. Download Java Runtime Environment (Java 8 or above).
  2. Download BFG from official site.
  3. Determine the files you want to remove: Use specific names (Passwords.txt) or wildcards (*.mp4).
  4. Clone a fresh copy of {your_big_repo}, using the --mirror flag:

    git clone --mirror https://github.com/{your_big_repo}.git
  5. Run BFG to clean your repository up:

    java -jar bfg-1.13.0.jar --delete-files "{Passwords.txt,*.mp4}" {your_big_repo}.git
  6. Strip out the unwanted dirty data then push:

    cd {your_big_repo}.git
    git reflog expire --expire=now --all && git gc --prune=now --aggressive
    git push

* For better explanation read Usage from the official site.


6. Riddikulus

Riddikulus is used to transforms nasty git repositories from something scary as complicated long histories into something silly as numbers, lists, insights and statistics.

6.1. Count Occurrence of Pattern

Let's say you want to count how many lambda expressions (->) you've used in all .java files, a quick spell can count it for you in the blink of an eye.

git grep '\->' '*.java' | wc -l

6.2. Count Number of Commits

You've been committing for so long now, maybe it's time to know how many commits are out there now.

git rev-list --count <branch-name>    # One branch
git rev-list --count --all            # All branches

6.3. Count Lines of Code

Curiosity is an enough reason to know loc.

git ls-files | xargs wc -l          # Detailed
git ls-files | xargs cat | wc -l    # Total

6.4. Count Lines Changed

You have been working on multiple features, and now you wanna know how many lines you have touched. It's fine spells got your back. Note: Add --staged if your changes were staged.

git diff --stat         # Detailed
git diff --shortstat    # Total

6.5. Export Full Log to File

Exporting your repository log to a file might be helpful sometimes, just learn this spell until the time comes and you need it.

  1. Text File

    git log > log.txt
  2. JSON File (refer to pretty-formats for more placeholders)

    git log --pretty=format:'{
        "commit": "%H",
        "subject": "%s",
        "body": "%b",
        "author": {
            "name": "%aN",
            "email": "%aE",
            "date": "%aD"
        }
    },' > log.json

6.6. List Ignored Files

You wanna make sure that your .gitignore is working fine and that all files that you want to ignore are really ignored. Here's a quick spell for you.

git ls-files --others --ignored --exclude-standard

6.7. List Large Files

Keeping track of your repository size is something that you need to learn, this spell might be helpful if you managed to do so.

git rev-list --objects --all \
| git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
| sed -n 's/^blob //p' \
| sort --numeric-sort --key=2 \
| cut -c 1-12,41- \
| $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest

7. Markdown Beautifio

Some spells that you can use on GitHub to add a bit of "beautifulness" to your markdown files.

7.1. Keyboard Key Strokes

Writing key strokes as plain text is the unforgivable sin that we are trying to void here using this spell.

Press the following to save: <kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>s</kbd>

Press the following to save: ctrl + shift + s

7.2. Mathematics Equations

Mathematicians are somehow wizards too, they need to write their equations and formulas.
CodeCogs provides a good solution for embedding mathematics equations as images in markdown files, like the following equation.

My Awesome Equation

  1. Write your equation in the Equation Editor.
  2. Edit Image type, font, and size.
  3. Choose URL (encoded) from the combobox at the end of the page.
  4. Use the copied URL in a markdown image as follows:
![My Awesome Equation](Endoded_URL_Here)

7.3. Icons

Adding icons to markdown files isn't that hard, you can use any of those two providers to help you:

  1. ImgPlaceholder

    • Supports Font Awesome, Ionicons & Glyphicons.
    • Customizable size, foreground color & background color.
    • Can be written in markdown or HTML syntax.
    • Lower quality.

    ![imgplaceholder](https://imgplaceholder.com/80x80/transparent/000000/fa-github?font-size=92)

    imgplaceholder

  2. Simple Icons

    • Supports SVG icons for popular brands only.
    • Black color only.
    • HTML syntax only.
    • Higher quality.

    <img alt="simple-icons" width="80" src="https://cdn.jsdelivr.net/npm/simple-icons@latest/icons/github.svg" />
    simple-icons

7.4. Contributors Image

contributors-img provides a good way for adding a good looking image of your contributors in your markdown file.

[![Contributors][contributors-img]][contributors]

[contributors]: https://github.com/USERNAME/REPONAME/graphs/contributors
[contributors-img]: https://contributors-img.firebaseapp.com/image?repo=USERNAME/REPONAME

Angular Contributors

7.5. Dropdowns

Keep the less useful content collapsed, no one needs to see it!

<details>

<summary><b>Example</b></summary>
<br/>

1. Remove the `<b>` & `<br/>` tags if you want, it's fine.
1. Don't forget to surround the body with blank lines.
1. Supports **Markdown** _Syntax_. Including Images.

![git-for-wizards](https://imgplaceholder.com/1000x200/992c2c/ffffff?text=Git+for+Wizards&font-family=OpenSans_Bold)

</details>
Example
  1. Remove the <b> & <br/> tags if you want, it's fine.
  2. Don't forget to surround the body with blank lines.
  3. Supports Markdown Syntax. Including Images.

git-for-wizards

7.6. Badges

A wise wizard once said "Just add more badges!".
Maybe that's why they created shields.io.

![GitHub last commit](https://img.shields.io/github/last-commit/YoussefRaafatNasry/git-for-wizards.svg)
![GitHub repo size](https://img.shields.io/github/repo-size/YoussefRaafatNasry/git-for-wizards.svg)

GitHub last commit GitHub repo size

7.7. Captions

Some photos are meaningless without captions, but wizards know how to handle that!

<div align="center">
    <img src="https://imgplaceholder.com/480x200/992c2c/ffffff?text=Git+for+Wizards&font-family=OpenSans_Bold" />
    <br/>
    <sub><sup>© 2019, licensed under the <a href="https://opensource.org/licenses/MIT">MIT License</a>.</sup></sub>
</div>

© 2019, licensed under the MIT License.

7.8. README Headers

This will be enough as a start to add a cool header for your README file, but try to be more creative.

<div align="center">
    <img src="https://imgplaceholder.com/100x100/transparent/323232/ion-ios-color-wand?font-size=100" />
    <h3>Git for Wizards</h3>
    <strong>Some magic spells and wands for Git & GitHub</strong>
</div>

Git for Wizards

Some magic spells and wands for Git & GitHub

8. The THANK YOU Spell ❤️

8.1. References and Acknowledgments

  1. BFG Repo-cleaner
  2. Change the date of a git commit
  3. How to discover a bug using git bisect?
  4. How to find/identify large commits in git history?
  5. Orphaned Branches in Git

8.2. Contributors

contributors


Congratulations!

You have finally reached the end!
You've done it all. You are FREE now!
* Please don't forget to turn off the lights on your way out.


© 2019 git-for-wizards, licensed under the MIT License.