References:

Allcommands Learn Git in Y minutes learn by eample download and install sqush 10 daily situation 45 scenario Navigate in Visual Studio Team Explorer git in javapoint / rebase git documentation How to Squash last n commits

What is git

A managable repository (database) of snapshots of working directory(ies).

Basic Git workflow

1- You modify files in working folder. 2- To add those changes to the staging area:

$ git add

3- To save the files in the staging area into local Git repository:

$ git commit -m "Added x() function to a.cs" 
4- To push the changes from local repository to remote repository:

git push

Glossary

Repositoryit stores files and directories plus the history of their changes. Branch is a version of the repository (A Git project can have more than one branch) . Indexis a staging area between the working directory and repository. HEAD referes to latest commit to the current branch .it is like current branch. Detached HEAD refers to a specific revision that is not associated with a branch name. MasterIt's a default branch of Git. (in the remote server) Originis the remote repository from a project was initially cloned. (original repository URL shotened) Remoteis a shared remote repository .it could be GitHub. ForkA fork is a rough copy of a repository. tracking branch is a local branch that sync itself into a remote branch Checkout is used to switch between branches in a repository. Cherry-Picking is to apply some commit from one branch into another branch Clonemakes a copy of the target repository or clone it as local copy Fetchjust "downloads" the changes from the remote to your local repository without merging it to the current local branch(git pull does) Merge combine another branch into current branch . Pull is used to receive data from remote server to your working directory. Pull Request announces all the team members that they need to review the code and merge it into the master branch. Pushis an act of transfer (overwrite)commits from your local repository to a remote repository. Rebaseis moving or combining a sequence of commits to a new base commit From a content perception, rebasing is a technique of changing the base of your branch from one commit to another Stashingif you don't want to make a commit of half-done work, The git stash command saves your work in stash are and enables you to switch branch without committing the current branch. Tagis used to mark a commit stage as important. We can tag a commit for future reference. Primarily, it is used to mark a projects initial point like v1.1. There are two types of tags. 1.Light-weighted tag 2.Annotated tag Upstream And Downstream The term upstream and downstream is a reference of the repository. Generally, upstream is where you cloned the repository from (the origin) and downstream is any project that integrates your work with other works. However, these terms are not restricted to Git repositories. RevertIt is an undo type command,bu not completely. is used to revert some commit. Resetstands for undoing changes. The git reset command is used to reset the changes. The git reset command has three core forms of invocation. These forms are as follows: 1.Soft 2.Hard 3.Mixed Ignoreused to specify intentionally untracked files that Git should ignore. It doesn't affect the Files that already tracked by Git. Diff It is used to show changes between commits, commit, and working tree, etc. Flow is a branching model for Git, developed by Vincent Driessen. It is very well organized to collaborate and scale the development team. Git flow is a collection of Git commands. It accomplishes many repository operations with just single commands. Squashis used to squash previous commits into one. Git squash is an excellent technique to group-specific changes before forwarding them to others. You can merge several commits into a single commit with the powerful interactive rebase command. Rmstands for remove. It is used to remove individual files or a collection of files. The key function of git rm is to remove tracked files from the Git index. Additionally, it can be used to remove files from both the working directory and staging index.

Commands:


# Showing help -----------------------------------------------------------------------
 $ git help -a    or   $ git help -g                  
  
# working copy(index/repo) and the latest commited,differnce
 $ git status     ( $ git status -s   # Short status)

# Searching for "variableName" in all files of java type
 $ git grep 'variableName' -- '*.java'    
 
# config  -----------------------------------------------------------------------

# git configuration info
 $ git config -l                                

# setting user name
 $ git config --global user.name "Fabio"       

# setups the email used in commits.   
 $ git config --global user.email "me@fab.com" 
 
# stores credentials in the cache to be remembered
 $ git config --global credential.helper cache 
 
# working directory  -----------------------------------------------------------------------

$ git init         # mark the current folder as a git repository
 rmdir /s .git     # undo git init in windows   
 
# 'Current directory' to/from 'staging'  -----------------------------------------------------------------------
 
$ git clone https:/github.com/libgit2/libgit2   # getting a Repository

# Staging files:


$ git add file1.js file2.js  # Stages multiple files
$ git add .                  # add all files to the staging area/index 
$ git add fil*               # add only certain files to the staging area  
$ git add -p                 # opens a prompt and asks if you want to stage changes

# Unstaging files (undoing git add):

$ git restore --staged file.js          # Copies the last version of file.js from repo to the working directory
$ git restore --source=HEAD~2 file.js   # Restoring an earlier version of a file
 
$ git diff                        # view the difference betwween comittted and before commited
$ git diff all_checks.py          # view changes on a specific file.  
$ git diff --staged               # git diff shows only unstaged changes by default.  
$ git diff --cached               # Same as the above
  
$ git rm filename                 # removes tracked files from the current working tree
$ git rm file1.js                 # Removes from working directory and staging area   
$ git rm --cached file1.js        # Removes from staging area only  

$ git mv file1.js file1.txt       # Renaming or moving files
$ git mv oldfile newfile          # Renames files.it stages the changes, then it expects a commit message.  

$ 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
$ git checkout filename           # Revert unstaged changes:

$ git reset HEAD filename         # revert staged changes:
$ git reset HEAD -p               # You can use the -p option flag to specify the changes you want to reset.
  
# ignore files:
  # Create a .gitignore file and commit it.

# Staging and repository  -----------------------------------------------------------------------

# Committing the staged files :


 $ git commit                                 # opens a text editor to write a message,then commit (stroes in repositiory)
 $ git commit -m "your commit message here"   # commit changes with a message 
 $ git commit -a -m"your commit message here" # commit changes (and skip the staging area) 
 $ git commit -am 'Message'                   # Removes from staging area only 
 $ git show _commit-id_                       # view a specific 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 

$ git rebase -i HEAD~n                        # merges the last n commits into a single commit( use `HEAD~3` for example).


 $ git log                                    # view all commits history 
 $ git log --oneline                           # --oneline will limit commit msg to a single line.
 $ git log --reverse                           # Lists the commits from the oldest to the newest
 $ git log --stat                              # Shows the listof modified files
 $ git log --patch                             # Shows the actual changes (patches)
 $ git log -3                                  # Shows the last 3 entries 
 $ git log hash1..hash2                        # Range of commits
 $ git log --pretty=format:”%an committed %H”  # Formatting the log output
 $ git log file.txt                            # Shows the commits that touched file.txt
 $ git log --stat file.txt                     # Shows statistics (the number of changes) for file.txt 
 $ git log --patch file.txt                    # Shows the patches (changes) applied to file.tx t  
 $ git log -p                                  # shows the commit's history including all files and their changes
 $ git log --graph --oneline                   # show the commit log as a graph. 
 $ git log --graph --oneline --all             # show the commit log as a graph of all branches

# Comparing commits

 $ git diff HEAD~2 HEAD                        # Shows the changes between two commits 
 $ git diff HEAD~2 HEAD file.txt               # Changes to file.txt only

# Checking out a commit 

$ git checkout dad47ed                        # Checks out the given commit 
 $ git checkout master                        # Checks out the master branch


 $ git bisect start                          # Finding a bad commit
 $ 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

 $ git shortlog                              # Finding contributors 

# Finding the author of lines
 $ git blame file.txt # Shows the author of each line in file.txt

# Tagging
 $ git tag v1.0                 # Tags the last commit as v1.0 
 $ git tag v1.0 5e7a828         # Tags an earlier commit 
 $ git tag                      # Lists all the tags
 $ git tag -d v1.0              # Deletes the given tag

# Amending the last commit -----------------------------------------------------------------------
  
#Undo a commit and redo (simple scenario, forget to change sth)
 $ git commit --amend             # allows to modify and add changes to the most recent commit
 $ git commit -m 'initial commit'
 edit file
 $ git commit -a --amend

 git revert HEAD           # rollback the last commit:.reverts the latest commit by using the head alias .
 git revert comit_id_here   # rollback an old commit using its commit id (opens the editor to add commit message)


 git rebase -i master        # Squashing all commitssince you branched, into a single commit

# Managing branches -----------------------------------------------------------------------


git branch branch_name            # creates a new branch(By default, you have one branch)Git won't switch to it automatically 
git checkout branch_name          # switch to a newly created branch.
git branch                        # list branches:shows all branches and highlight the current branch in green. 
git checkout -b branch_name       # create a branch and switch to it immediately,In a single command. 
git branch -d branch_name         # delete a branch. 
git merge branch_name             # Merges the branch you are currently in with the branch_name.  
git merge --abort                 # abort a conflicting merge.If you want to throw a merge away and start over 
$ 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 branch -d bugfix            # Deletes the bugfix branch 

# 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
   $ git diff [branchname]              # compare the branch with active branch
   $ git diff -name-status [branchname] # only compares file names of the branch and active branch
   $ git diff [branchname] --[filename] #comparision of  specific file in two branch

# Merging
    git merge bugfix          # Merges the bugfix branch into the current branch
    git merge --no-ff bugfix  # Creates a merge commit even if FF is possible
    git merge --squash bugfix # Performs a squash merge 
    git merge --abort         # Aborts the merge

# 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
    
#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

#Undoing commits
    git reset --soft HEAD^  # Removes the last commit, keeps changed staged 
    git reset --mixed HEAD^ # Unstages the changes as well 
    git reset --hard HEAD^  # Discards local changes
    
#Reverting commits 
    git revert 72856ea      # Reverts the given commit
    git revert HEAD~3..     # Reverts the last three commits
    git revert --no-commit HEAD~3..
    
#Recovering lost commits
    git reflog              # Shows the history of HEAD
    git reflog show bugfix  # Shows the history of bugfix pointer

#CHECKOUT
 git checkout file_name   # Discard uncommitted changes in a specific file 
 git checkout -- .          # Clear everything not in repo

 git rebase branch_name_here # transfer completed work from one branch to another using git rebase.
 git rebase -i master    # run rebase interactively.it opens the editor and present a set of commands you can use:
        # p, pick = use commit
        # r, reword = use commit, but edit the commit message
        # e, edit = use commit, but stop for amending
        # s, squash = use commit, but meld into previous commit
        # f, fixup = like "squash", but discard this commit's log message
        # x, exec = run command (the rest of the line) using shell
        # d, drop = remove commit

# local repository and Remote -----------------------------------------------------------------------

 $ git -vv # to find the remote branch that your local branch is tracking in git
 # to get difference between local folder and remote folder,first use fetch then use diff:
 $ git fetch
 $ git diff --state origin/master # for summary of differences
 $ git diff origin/master # for detailed differences
 
#Syncing with remotes

 $ git fetch origin master        # Fetches master from origin
 $ git fetch origin               # Fetches all objects from origin 
 $ git fetch                      # (=“git fetch origin”).downloads the changes from a remote repo but will not perform a merge on local branch as git pull.
 $ git pull                       # (Fetch + merge)retrieve the latest changes made to the remote repository
 $ git push -u origin branch_name # pushs a new branch to a remote repo.-u to create the branch upstream
 $ git push                       #(=“git push origin master”)update (and merges) repository from local repository
 $ git push origin master         # Pushes master to 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
 $ git add remote https://repo_here           # adds a remote repository to local repository 
 $ git remote -v                              # see all remote repositories(urls) for local repository
 $ git remote show origin                     # get more info about a remote repo.Just obtain origin name by running the git remote -v command.
 $ git branch -r                              # shows the name of all remote branches that Git is tracking for the current repository
 $ git log origin/main                        # check the current commits log of a remote repo.
 $ git merge origin/main                      # merge a remote repo with local repo(If the remote repository has changes).
 $ git remote update                          # get the contents of remote branches without automatically merging.
 $ git push --delete origin branch_name_here  # remove a remote branch.
 $ git push -f                                # force a push request: This is usually fine for pull request branches because nobody else should have cloned them.But this isn't something that you want to do with public repos.

GIT in visual studio

git have 2 user interface in visual studio: 1-Visual Studio Git :new 2-Visual Studio Team Explorer:can access to the Work Items hub. You can exercise Git features from either interface interchangeably. In the link below, there is a side-by-side comparison for cloning a repository.

"Visual Studio Git" and "Visual Studio Team Explorer" comparision