#git#github#ReviewGit#vcs#sourceControl

After installing git check the version to see if you are good to go.

git --version

Using git for the first time

The first time you use git , you have to make configuration You have to specify :

  • 🔖 The Name
  • 🔖 The Email
  • 🔖 Default Editor
  • 🔖 Line Ending These settings can be specified at three different levers
  • 🔥 System Level
    • 💡 Applied to the whole system
  • 🔥 Global
    • 💡 All repositories for the current user
  • 🔥 Local
    • 💡 The current repository

System Level

  # List your configuration
   #git config --system settings.to.configure
 
# Set the name
# user.name can be your name, not only username
git config --global user.name "danielerat"
 
#Set the email
git config --global user.email davidodo2015@gmail.com
 
#set the editor
git config --global core.editor "core --wait"
 
# Configure the end of line in git:
#!!!!!!Very important
# If you are on windows
git config --global core.autocrlf true
# If you are on mac or linux
git config --global core.autocrlf input
 
# Set vscode as the default diff tool
git config --global diff.tool vscode
 
# set how to run vs code
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOVE"
 

On windows, end of lines are marked with \r or \n where \r is Carriage Return and \n is Line feed, while in linux and mac os it is \n

Editing our configurations

Sometimes you want to configure the configuration to your needs, you would want to open the text file where they are written and manually edit them or simply type

#Open the configuration file
git config --global -e

User Level

git config --global

Project Level

    git config

Before working with git you must set these up to be able to make commits

Set First configuratiosn

Configure Username

git config --global user.name 'danielerat'
 

Setting up Email

 
git config --global user.email "davidodo2015@gmaiil.com"

Setting up username

 git config --global user.name 'danielerat'

Check your configurations

Before startin to work with git, check your configurations

git config user.name
git config user.username

Best Practices with Commit Message

  • ✅ A short Line Summary (Less Than 50 Characted Optionally Followed By a blank line and a more complete Description
  • ✅ Be clear And Description

Example of a good and back commit

  • [?] question

  • [p] Good “Add Missing Hyphen in project section of html”

  • [?] bad: “Update login code”

  • [p] good: “Change User Authentication to use Blowfish”

Example OF a good Commit


ghi2394 - Fixes bug in admin logout

When an admin logged out of the admin area, they

could not log in to the members area because their

session[:user_id] was stil set to the admin ID.

This patch Fixes the bug by setting session[:user_id]

to null when any use logs out of any area.

VIEW COMMITS

git log
  Output:
    commit 3fe8a51d15454494457526af69e78a6ccb4d3c1d (HEAD -> master)
    Author: danielerat <davidodo2015@gmail.com>
    Date:   Tue Jun 7 07:03:39 2022 +0200
Initial Commit
 
 
git log # Full history
git log --oneline # Summary
git log --reverse # Lists the commits from the oldest to the newest
 

Get the 5 Last Logs

git log -n 5
#Output:
#Provide the five latest Commit made

Show commits applied since the specified date

git log --since=2019-01-01   

Show commits applied until the specified date

git log --unti=2019-01-01

Commits from a particular author

git log --autho="danielerat"

Search For a commit message

git log --grep="Init"

Last two commits that happened before September 10, 2020?

git log 2 --until=2020-09-10

Which will output the log for all of Karen’s commits labeled “refactor” during March 2019

git log --since=2019-03-01 --until=2019-03-31 --author="Karen" --grep="refactor"

THE THREE TREE ARCHITECTURE

#STAGGING INDEX(About to commit)
git add file  
#REPOSITORY (Commited files)
git commit file
#Restore from staging to current working directory
git restore --stagged filename
 
#WORKING (Current working dir)
git restore filename
 
git restore file.js # Copies file.js from index to working directory
git restore file1.js file2.js # Restores multiple files in working directory
git restore . # Discards all local changes (except untracked files)
git clean -fd # Removes all untracked files

TAKE A LOOK AT MODIFIED FILES (diff program)

View on working directory

git diff
  • By default compare the working directory againt the stagging tree
  • The git diff command shows the differenct or the things added to a certain file
  • 💡 Shows us what was added and what was changed in the file , just a snapshot of the things though

View On stagged file only

git diff --staged
git diff --color-words
 

Deleting a file in git

When you delete a file manually (normal delete), you will need to use the:

git rm filename
#to add the file to the stagging environment
 
 
#To direcltly add it to the deeted file list in your directory
 
git rm filename
 

Renaming and moving files


It will show that one was deleted and another one was added

but if you add them to stagging , it will dhow you that it was actually a rename

git mv second_file.txt primary.txt

giv mv second.txt folder/newname.txt

commits

To commit your files you are going to use the git commit command

git commit -m "your commit"
 
# skip the add process
git commit -am "Your commit "
#Stage And Commit the automatically , you don't have to follow the steps

check a commit , see what is inside a commit

 
 
#git show hash
 
# SHow all the changes introduced on this commit
git show d94f9f449c0b86a34ec02be780b360c07b7c20b
 
# show the changes in a linear kind of style
git show d94f9f449c0b86a34ec02be780b360c07b7c20b --color-words
 
git show 921a2ff # Shows the given commit
 
git show HEAD # Shows the last commit
 
git show HEAD~2 # Two steps before the last commit
 
git show HEAD:file.js # Shows the version of file.js stored in the last commit

COMPARE TWO COMMITS

CHECK DIFFERENCT BETWEEN TWO COMMITS You can use the: git diff d94f9f449..f91d45g81 --color-words

git diff d94f9f449c0..HEAD --color-words
 
#Where HEAD Does mean the last COMMIT

Short commit

Checking one line commit of your codes

git log --oneline

MAKING ATOMIC COMMITS

To make good commits you must respect the following

  • Small commits

  • Only affect a single aspect

  • Easier to understand, to work with , and to find bugs

  • improves collaboration

  • Make commits to data that are only realated, as in only commit files or data in an ATOMIC way

Do not make a bunch of changes and make single commit, It's really annoying and the more you get advanced it will become harder to debug,

Tagging

#tag sometimes we need to bookmark some point in our commits, like the commit that represent a given version , we use tags for this version .

# git tag v1.0 log_hash
git tag v1.0 5e72e21
 
# we can represent the commit with a tag instead of the id
git checkout v1.0
 
# List tags
git tag
 
# Creating an annotaged tag(name, email of tagger etc..)
git tag -a v1.1 -m "My version 1.1"
# get tag with message
git tag -n
 
# Check the annotated tag
git show v1.1
 
# Deleting a tag
git tag -d v1.1

Branching

#branch

  • 🔥 Using branches
  • 🔥 Compare Branches
  • 🔥 Merge Branches
  • 🔥 Resolve Conflict
  • 🔥 Undo A faulty Merge
  • 🔥 Essential Tools(Stashing,Cherry Picking)

Branching allow us to diverge form main land of work and work on something else in isolation, a branch can be thought of a separate isolated workspace.

  • We work in an isolated space, make sure everything is working
  • Merge our changes when done.

The Way git manages branches.

The way git manages branches, it is very different from other version control system. A branch is simply a pointer to a commit The master branch is simply a pointer to a commit , as you make new commit git moves automatically to the new branch.

Creating a new branch

To create a new branch you simply type

#git branch branchname
git branch bugfix
 
# check your branches
git branch
	#output
		 # bugfix
		 # *master
git status
	#output
		# On branch master
		# nothing to commit, working tree clean

Switching to a branch

To be able to work on your branch you have to move to it, to change to your branch you use the switch command the checkout command used to work , but it had a lot of applications so switch is the new way

# Old way
git checkout branch
 
# new way
git switch bugfix

Renaming your branch

Sometimes you need to rename your branch and for that you use the -m flag

#git branch -m old_name new_name
git branch -m bugfix bugfix/signup-form

Code you have in a branch are isolated, if you switch to another branch then you will the old code excluding the branch one

Viewing commits across different branches.

To view commits across different branches you simply use the —all flag

git log --all
 
#one line versions
git log --oneline --all

Deleting a branch

Sometime when you are done working on a branch you need to delete it. and for that it is very simple you use the -d flag.

git branch -d bugfix/signup-form

When you want to delete a branch , and it happens to have commits they will tell you that it is not merged. you won't be able to delete it. great safety.

If you are really sure not to need a branch then you can simply use -D to delete the branch.

#git branch -D branchname
git branch -D bugfix/signup-form

Comparing branches

Sometimes we need to see how branches are diverging from our main or master branch. we need to know the commits and all those kings of stuffs.

See commits in one branch not in the other

sometimes you want to see commits in the detached branch not in you master branch. you will use a command like this.

#commits that are coming in master
# Commits in bugfixbranch not in master branch
git log master..bugfix/signup-form
 
# list them on one line
git log master..bugfix/signup-form --oneline

Getting the actual changes and not the lists of commits

You want to see the actual changes in a branch ? well yes you can do that too using diff.

git diff master..bugfix/signup-form
 
 
# If you are already in the master branch, there is no need to specigy the master..
git diff bugfix/signup-form
 
 
# sometimes you wan to see the changes in terms of modified file.
git diff --name-status bugfix/signup-form
 

Stashing

When we switch branches, git resets our working directory to the snapshot stored in the last commit of the target branch.

If we have changes in our working directory that we have not committed yet, these changes could get lost. So git does not allow use to make changes.`

error: Your local changes to the following files would be overwritten by checkout:

     **audience.txt**
    Please commit your changes or stash them before you switch branches. Aborting`

Scenario

  • 💡 You are working on your master branch
  • 💡 You wat to switch to your new branch called Bugfix
  • 💡 But you have untagged files in your working directory
  • 💡 You don’t want to commit them cause you are not done yet. This is where stashing comes into play

Stashing our changes means storing it in a save place, store it in our git repository but it wont be part of our history

Creating our stash

# git stash push -m "Name of your stash"
git stash push -m "New Tax Rules."
 

New Untracked files are not included in your stash by default. To include it you have to use the --all -a flag

git stash push --all -m "New Tax Rules."
 
#or
git stash push -a -m "New Tax Rules."
 
#or
git stash push -am "New Tax Rules."

View or list your stash

#stashlist#list To view of list all your stashed you are gonna use the list command

git stash list
#output
	# stash@{0}: On master: New untracked file added to stash
	#stash@{1}: On master: New Audience Rules

Examine a stash, See what is in a given stash

You are back to a given branch and you would like to bright the stashed changes back to your working directory. but before you would wanna see the content of that stash

# git stash show sequence_number
git stash show stash@{1}
#or
git stash show 1

Apply stash to our working directory

You now want to move changes from your stash to your working directory? yes you can do that .

#git stash apply sequence_number
git stash apply stash@{1}
#of
git stash apply 1
# will bring changes from your stash to your working directory.

Removing your stash

You have applied your changes and no longer need your stash ? then yes you can remove them.

#git stash drop sequence_number
git stash drop stash@{1}
#or
git stash drop 1

You can remove all your stashes too with

git stash clear

Merges (Merging your branches)

In git we have 2 types of merges

  • Fast Forward merges
  • 3-ways merges

Fast Forward Merge

Used if branches has not diverged

We Create a branch and we apply changes to that branch and we now want to merge the changes from that branch to our master branch. In fast forward we will simply move the master pointer forward to the merge we desire.

3 Ways merge

Used if branches has diverged

You create you branch bring changes to your branch and after that you simply you do the same care to the master branch . you can not do fast ford otherwise you will loose the changes in the master from your branch.

You will do a 3ways marge to achieve the desired effect.

Merging you branches

You want to check whether you have a linear / non diverging merge

git log --oneline --all --graph
#will show you the commits and you will be able to see whether a branch diverged or not.
# If you have a linear path(no diversion) (then git will fast forward)

Merge using fast forward

#git merge branchname
# Make sure you are in the branch you want changes int(eg:master branch)
# git switch master
git merge bugfix/signup-form
# git will do a fast forward merge.

You can can merge disabling the fast forward

git merge --no-ff bugfix/login-form
# We are basically telling git that, hey even if the fast forward is possible we don't want it , create a merge comit that combines the cahnges in the branch and bring them to master.
 
 
# usually a window open where you write your commit, but you can leave the default one too.
#for a better visualiztion
git log --oneline --graph
#*   951ee7a (HEAD -> master) Merge branch #'bugfix/login-form'
#|\
#| * e2ca4eb (bugfix/login-form) Update Toc.txt
#|/
#* 0cb2b37 (bugfix/signup-form) Fixing the bug  that prevented the user from signing up
#* a642e12 Add header to all pages.

You ca be working in a company that has a no fast forward policy you can simply disable the fast forward like this: git config ff no in your current settings/repo

Deleting A branch in git.

As a best practice , we should always delete our merged branch.

Sometimes you might have a list of branches you merged then forget about it and leave them hanging .

See the list of merged branches.

to view the list of branch we have merged in the master we use

git branch --merged
# will return a list of merged branch
To view the list of unmerged branch we use
git branch --no-merged
# will return a list of merged branch
Delete a branch
#git branch -d branch_name
git branch -d bugfix/login-form

Merge Conflicts

In the real world, sometimes wen we merge changes, we get conflicts. they occur when

  • Same codes is changed on different branches in different places.
  • Changed in one branch and deleted in another
  • Same file is added twice in two different branches and the content are not the same.

    You can manually merge the changes, which is simply by manually accessing the file and add remove or delete what is not needed then you save your change.

Aborting a merge.

#abbort Let’s say you want to merge and you get a hundred conflicts, what if you want to revert the merge and first deal with some stuffs and come back to the merge later ? well yo can do that, you can undo the merge .

#aborting a merge.
git merge --abort

Undoing a faulty merge.

sometimes we do a merge and find out that our code does not compile or our application does not work. that happens if we screw the merge. In situations like this, we need to undo a merge and remerge.

  • First way is removing a commit/log
    • here you are rewriting history, and when doing so, you surely don’t want that if you shared your codes online already.
  • Reverting a commit approach, we will simply create a new commit that will cancel the changes.

Removing the last commit

When you made a bunch of nonsense commit, you might wanna remove the last commit.

git reset --hard HEAD~1
# Roll back to the last 1 commit
 
 
# When we use reset hard, we can still go back to that commit and be as in nothing happend
git reset --hard 5aae93 #PREVIOUS MERGE COMMIT

If you have shared you commits, eg: github with some people instead of resetting you can instead undo the changes to the state you wish. much more safer.

Reverting a commit

git revert -m 1 HEAD

Squash merging

You create your branch and make a bunch of commit in there and you want to merge now, but here is a thing, you don’t want to merge with all these commits not to pollute your master branch what can you do ? squash merging it is a commit that combines commits from a given branch, all the changes for that , applied to master, it is not a merge, as for it does not have a parent

#git merge --squash branch_name
git merge --squash bugs
 
# on this stage files are moves from that branch to your staging branch you have to commit
git commit -m "Squash mergins changes from the branch x"

When doing squash merge it is simper important to really remove that branch or it will create a real confusion in the future, cause if you use git branch --merged it will not show as merged yet you technically merged the change in the main

Because squash merge is technically not merged, deleting your branch has to be forced git branch -D bug.

Rebasing

Another technique for bringing changed into another branch is Rebasing

Rebasing Rewrites History, thus do not use it with codes you have shared.

#step1: Switch to our target branch
git switch bugs
#step2: Execute the rebase command
git rebase master
 
# in the real world when rebasing you might find conflicts.
 
#step3: Go back to master and merge
git switch master
#step3: Mergins our branch
git merge bugs

Cherry picking

You have a feature branch with two commits F1 and F2 one of these commits have some interesting changes we want to have in master, it is possible we can simply take that commit and put it in master.

 #git cherry-pick your_hash
 git cherry-pick 7b8ae2c

Picking files from another branch

If you are not interested in a commit then you can simply pic a file you need, and you can do that with a cherry pick

#switch to your master branch
#git restore --source=branch_name file_name
git restore --source=bugfix -- email.py

Collaboration

Github is used for collaboration.

Cloning a repository

#git will creat a folder with the repo name
git clone cloneUrl
 
#clone and create your preffered folder name
git clone url folder_name
git log --oneline --all --graph
# 282a917 (HEAD -> main, origin/main, origin/HEAD) Initial commit
	# origin/master: when cloning git names the source ripository origin. Origin/master tells us where the master is at on that repository.(where is the master in our remote directory(technically it is called a remote branch))
	# origin/head: tells us where is the head pointer in our origin repository.

Listing the remote repositories

A remote repository is a repository that is not on our machine. In our case it is the link git uses when talking to that repository.

git remote
 
# for more details.
git remote -v
#origin  https://github.com/danielerat/Mars.git (fetch)
 
#origin  https://github.com/danielerat/Mars.git (push)

Download or fetch changes from remote

#fetch#pull You want to download changes to your remote repository? well you can do that with the fetch command

# git fetch the_remote branch_name
#git will asume that you want to fetch the main
git fetch
 
#git will fetch all changes / commits of your origin branch
git fetch origin
 
#git will download only changes from that  specific branch
git fetch origin dev

When you fetch a repository, what happens is that it simply brings the commits but your head still points to the main. you are gonna have to manually merge.

We have pulled the changes and we want to know if we are being of how many commits

git branch --vv
 
#output
# main 282a917 [origin/main: behind 1] Initial commit

We have fetched our data, we know what we are behind for sure and we want to merge to be up to date with the origin.

#git merge remote_branch_name
git merge origin/main
 
#verify that we are not behind.
git branch -vv

Pull command = Fetch + Merge

pull=fetch + merge To bring the changes from remote to local , most of the time we wan to do fetch followed by a merge. and we have a command for that pull

#will create a 3Ways merge
git pull
 
# will Create a linear history.
git pull --rebase

Pushing

We are in our local repo and it is ahead of the origin/main we want to push our change to the remote repo.

# Send Commits to the origin (remote)
# move the remote pointer to the new origin
#move the origin/master to the pushed part
 
#git push remote_repo branch_name
 
# Git will asume that you want to push to the remote repo and the current branch
git push
 
#push to the origin remote branch
git push origin
 
#push the main branch to the origin.
git push origin main
 

Pushing our Tag

By default pushing does not push your tags, you should push them individually.

# git push origin tag_name
git push origin v3.0

Deleting our tags from origin

#git push origin --delete tag_name
git push origin --delete v1.0

Pushing our branches

Now you want to work with branches and push them to github. well easy, you create them and push them (how do yo push them ? )

If you run git push while in your new branch, then you will get some error. saying that the branch you are trying to push is not linked to a branch in the origin.

# Get the branches and their remote tracking
git branch -vv
# dev  89e7945 Changes to the developmet branch
# * main 89e7945 [origin/main] Changes to the developmet branch
# Check all the remote trancking branches
git branch -r

If you want to push a branch for the first time you have to set the upstream branch (remote branch) with the -u flag.

#git push -u remote_name branch_name
git push -u origin dev

You are done with your branch and you would simply want to delete it from remote

#git push -d remote_name branch_name
git push -d origin Development

Delete a tracking branch that are not on remote

sometimes you have a remote tracking branch tracking changes of a given branch in the remote . you can remove automatically these branches using the prune command.

#listing all the remote branches.
git branch -r
 
# Delete the remote branch on github.
git push -d origin feature/change-password
 
# You have removed the branch from github, now you wanna remove it from your local repo, then remove the tracking origin branch
git remote prune origin
 

Pull requests.

Quite often we would want our team members to help us reviewing our codes with a pull requests. with a pull request we essentially open a discussion with the team before merging to the main branch.

# Create a new branch add features and push it to github.
git switch -C feature/login
 
# make changes and stage the file
echo "Some changes on the feature/login branch" > text.txt
# Add the change and commit
git commit  -am "New file on the nea branch"
 
#Push the branch.
git push -u origin feature/login
 

The Remote Command

We Use the git remote command to manage our remote repositories.

# Show the remote repositories
git remote
 
# List move verbos info about the repo
git remote -v
#origin  https://github.com/danielerat/Mars.git (fetch)
#origin  https://github.com/danielerat/Mars.git (push)

Adding a new remote

To add a new remote it is as easy as using the add command

# git remote add name url
git remote add upstream https://github.com/danielerat/Mars.git
 
# lising our remote repo
git remote
 
#origin
#upstream

Rename a remote repository

To rename a remote repo we sue, git remote rename command

# git remote rename name_old_remote  name_new_remote
git remote rename upstream base

Removing a remote

#git remote rm remote_name
git remote rm upstream

Synch changes from upstream to local

You would want to get updates of a particular repo you forked. what are the steps ?

# Scenario
# step1 : You fork a project
# step2 : you clone it to your computer from your fork
# step3 : You get lazy, and the base gets updated(where you forked your codes)
# step4 : You want the lates change cause you are crazy
 
# Ste1: Create a remote branch (aka base branch)
git remote add upstream
 
# step2: Fetch the new changes from the remote branch
git fetch upstream
 
#step3: merge to your main branch
git switch main
git merge base/master
 
#step4: Push to your forked repo the latest changes
git push

Ignore Tracked Files

#gitignore If you don’t want to track a file you have to add them to your git ignore

Sometimes you create your git ignore after you have tracked some changes in a particular file , if you add that file to .gitignore later on, it won't still be tracked you need to remove the file to the cache

#git rm --cached filename
git rm --cached .env
 
git rm --cached -r media/

Guide to remove tracked files

When you’ve already tracked files that you later add to your .gitignore file, Git might not automatically stop tracking those files. This is because Git’s tracking of files is based on their history. If a file has already been committed and is part of the history, adding it to .gitignore won’t immediately remove it from the repository.

Remove Cached Files

First, you’ll want to remove the files from the index and cache. You can do this using the following command:

git rm --cached <filename>

Commit Changes

After removing the files from the cache, commit the changes to the repository:

git commit -m "Stop tracking <filename>"

Update .gitignore

Ensure that the files you want to ignore are correctly listed in your .gitignore file. If not, add them to the file.

Commit Again:

Commit the updated .gitignore file:

git add .gitignore
git commit -m "Update .gitignore"

Finding a bad commit using git bisect

Divide history in half and get to test and see where there is a problem in our codes

git bisect start
git bisect bad
# Marks the current commit as a bad commit
git bisect good ca49180 # Marks the given commit as a good commit
git bisect reset # Terminates the bisect session

Finding contributors

#contribution#contibutor#authors

# see all logs and people who made the logs
git shortlog
 
git shortlog -n -s # Show names supress logs
 
git shortlog -n -s -e # show names logs and email

git ls-tree HEAD

============

List all files on the current directory

Git Tracking Directories


In the directoty you want to track simply add a

.gitkeep  and your directory will start being tracked

ADVANCED GIT


Point to the latest commit,

git show HEAD

-Ancestry: Parent (^)


Reference the direct parent aka commit right after the current one

we use the symbo (^)

git show HEAD^ : will show the previous commit right after the head

or git show master

or git show HEAD~

or git show HEAD~1

Multiple Parents


you simply use multiple ^^…

git show HEAD^^…

git show HEAD~2

Show directories and file in a tree-ish


Just like an ls command

git ls-tree HEAD

git ls-tree HEAD assets/

git ls-tree HEAD

040000 tree a20f5c1eb5270ad88529db701d6ba790ad19f50e    notneeded

100644 blob a8f3da1151c71091c0521ae4c489cce3eed5ac94    second_file.txt

100644 blob 8a56ec4382c359ce58dc65543c9cefc402bbbf0b    thirt.txt

Where blob:bigLongBinaryFile

Tree: Directory

FILTER THE LOG


limiting Commits:

git log -3#first 3 Commits

—since and —until,—after,—before


git log —since=2019-02-29

git log —until=‘3 days ago’

git log —after=2.weeks —before=3.days

Filter by author


git log —author=‘danielerat’

Look for a commit message


git log —grep=“Initial”

look for commit within a specific range


git log b447gh12..HEAD

!!!!!!!!!

Git logs of a particular file


git log first.html

*You will only get changes that afect that file

FORMAT THE COMMIT LOG (git log -p)


You can brownse through different commits and see changes applied to them

git log -p

git log —stat


Brings the statistics of the logs

something like this

commit e3806740d77048ac8381cff5adaab8ff1f8a9583

Author: danielerat davidodo2015@gmail.com

Date:   Sat Jun 11 09:06:10 2022 +0200

Modifying content of the third file

thirt.txt | 3 +—

1 file changed, 1 insertion(+), 2 deletions(-)

Specifying the format of logs


git log —format=YourFormat

Formats are: oneline,short,medium(default),full,fuller,email,raw

or You can use

Show format of one line commits


git log —oneline

Using Graphs


Graps are useful when dealing with branches

git log —graph

or even better use

git log —graph —all —oneline —decorate

BRANCHES OVERVIEW

  • 💡 Branches are cheap, easy to create
  • 💡 easy to delete
  • 💡 try new ideas
  • 💡 isolate features or sections of work
  • 💡 fast context switch master_branch

Listing BRANCHES

To list all branches simply use

git branch # used to list all the branches
#output:
#    * master

By default all git projects are on the main Branch

Creating new branch

#git branch name_of_branch
git branch bugfix # Creates a new branch called bugfix
 
git checkout bugfix # Switches to the bugfix branch
git switch bugfix # Same as the above
git switch -C bugfix # Creates and switches
git checkout -b branch_name #same as above

Renaming a branch

#git branch -m old_name new_name
git branch -m gold golden_buzzer

Comparing the branches

#Comparing branches
git log master..bugfix # Lists the commits in the bugfix branch not in master
git diff master..bugfix # Shows the summary of changes

Detached head

#pointer

Sometimes you want to move back in time and see the commits on a specific branch, for that you can use the checkout command,

git checkout f312b
 
#you can not view all the commits unless you use the --all flag
git lot --oneline --all

Check Where the head Points to

When you create a new branch by default git is pointing to that new branch

!!! If you type : ls -la .git/refs/heads/

You will see the list of all branches

!!!!! As Soon as you are done creating a new branch they will be pointing to the same

commit as the master,

git log —oneline

df3d3aa (HEAD -> master, new_feature) Adding another line in the third file *random line

Stashing

The git stash command takes your uncommitted changes (both staged and unstaged ), saves them away for later use, and then reverts them from your working copy

#Stashing
git stash push -m “New tax rules” # Creates a new stash
git stash list # Lists all the stashes
git stash show stash@{1} # Shows the given stash
git stash show 1 # shortcut for stash@{1}
git stash apply 1 # Applies the given stash to the working dir
git stash drop 1 # Deletes the given stash
git stash clear # Deletes all the stashes

Viewing the merged branch

#Viewing the merged branches
git branch --merged # Shows the merged branches
git branch --no-merged # Shows the unmerged branches

Rebasing

git rebase master # Changes the base of the current branch

Cherry picking

git cherry-pick dad47ed # Applies the given commit on the current branch

Collaboration

Cloning a repository

git clone url

Syncing with remotes

git fetch origin master # Fetches master from origin
git fetch origin # Fetches all objects from origin
git fetch # Shortcut for “git fetch origin”
git pull # Fetch + merge
git push origin master # Pushes master to origin
git push # Shortcut for “git push origin master”

Sharing tags

git push origin v1.0 # Pushes tag v1.0 to origin
git push origin —delete v1.0

Sharing branches

git branch -r # Shows remote tracking branches
git branch -vv # Shows local & remote tracking branches
git push -u origin bugfix # Pushes bugfix to origin
git push -d origin bugfix # Removes bugfix from origin

Managing remotes

git remote # Shows remote repos
git remote add upstream url # Adds a new remote called upstream
git remote rm upstream # Remotes upstream

Tip

Get Commits for a particular file

#Output all commits made up on this file
git log --oneline filename
 
#output all commits satatistic made on a file(+lines -lines and more.)
git log --oneline --sat filename
 
# See the actual changes of a given file per commit
git log --oneline --patch filename

Restore Deleted File

#remove#delete You delete a file then add and commit and you would first want to see the commits made on that file ? well use the — flag

# git log --oneline -- filename
git log --oneline -- toc.txt

Now to restore the file you simply have to checkout the previous commit where the file existed and simply restore that specific file

git checkout a642e12 toc.txt

The Git Reset Command

The git reset command is a crucial tool that allows you to manipulate commits, branches, and the staging area.

What does it do?

How Git Reset Works Behind the Scenes

When you run git reset, it adjusts the “HEAD” pointer and potentially other pointers to modify the state of your repository.

Modes of git reset

The git reset command has three primary modes, each with distinct effects:

  1. Soft Reset: This mode resets the HEAD pointer to a specific commit without modifying your working directory or staging area. It’s often used when you want to rewrite commit history before pushing changes to a remote repository.
  2. Mixed Reset (Default): This mode resets the HEAD pointer and updates the staging area to match the specified commit. It leaves your working directory untouched, allowing you to review and modify your changes before committing them again.
  3. Hard Reset: This mode resets the HEAD pointer, the staging area, and your working directory to match the specified commit. It discards all uncommitted changes, so use this mode cautiously.

How to Use Git Reset

The basic syntax of the git reset command is:

git reset <mode> <commit>

where

  • <mode>: Specifies the reset mode (--soft, --mixed, or --hard).
  • <commit>: Specifies the target commit to which you want to reset.

soft reset

git reset --soft HEAD~1

This resets the HEAD pointer to the previous commit, preserving changes in the staging area and working directory.

Mixed Reset (Default):

git reset HEAD~2

This resets the HEAD pointer and the staging area to two commits back, leaving changes in your working directory.

Hard Reset:

git reset --hard abc123

This resets the HEAD pointer, staging area, and working directory to the commit with hash "abc123."

When to Use Git Reset

  1. Undoing Commits: You can use git reset to remove or modify commits. Soft reset is useful for rewriting commit messages, while mixed or hard reset can be used to remove commits from history.
  2. Unstaging Changes: When you’ve staged changes but want to unstage them, use git reset with the mixed mode.
  3. Starting Over: In cases where your working directory is in an undesirable state, a hard reset can revert everything to a specific commit.

Advantages of Using Git Reset

  1. Granular Control: Git reset provides precise control over which changes you want to reset and how.
  2. Safe Rewriting: Soft and mixed resets allow you to revise your commit history before sharing changes with others.
  3. Flexible Workflow: Git reset fits various workflows, from cleaning up commits to preparing feature branches for pull requests.