- Git version 2.32 latest as of 25th July 2021
- Git binary installs GUI and command line interface, Git Bash
- The command line interface can use Linux commands and can also run from Windows command prompt
- Installation from https://git-scm.com
- Install “Beyond Compare” for diffing and merging.
- Install “NotePad++” for text editing.
- Set up configurations as mentioned below in configurations table
- Create aliases mentioned in Git Aliases below (git history
- Distributed Version Control System: It is a distributed system and every clone has complete information with the history (Perforce, CVS, SVN were centralized systems) so we don’t risk losing all the data if the server goes down, unlike centralized or local version control systems.
- Many workflows can be created by collaborating with the users. E.g. Integration-Manager Workflow, Centralized Workflow, Dictator and Lieutenants Workflow, etc.
- One can work offline without interruptions and upload changes to the server when online.
- It is fast because most operations are performed locally
- Allows creating branches without copying the entire source making it extremely fast to work in collaboration.
- Snapshot-based and not delta-based version control: This allows creation of a variety of tools
- Integrity: All files are stored after SHA-1 encryption.
- Data safe: It is possible to lose data if not committed, but not so much if committed and particularly not if pushed.
- Three states: Git has staging area (index) not present in other versioning systems (along with a working directory and the compressed repository to which commits are done). This staging area is located inside the compressed repository only. The three states of a file are committed (shown by clean working directory in
git status
), modified or staged. - Downside: Although Git is good for source code versioning, it is not the best for large files, non-text files, like video, audio, executables, library binaries, etc. which are edited regularly.
- Git: Version control system
- GitHub: Most popular repository hosting service. Even source code of Git is available on GitHub. Hosting public and private repositories is free. But hosting private repo with special features is paid.
- GitLab: A popular alternative to GitHub and used a lot in a lot of companies including Huawei
- Author: One who makes a patch for any source change
- Commit: A snapshot of files in a branch of a repository after some changes are applied by a user
- Commit ID: The SHA1 checksum generated when a piece of source is committed.
- Committer: One who applies a source patch to a repository. In most scenarios author and committer are same.
- Repository: A Git repository is the .git folder inside a project. It tracks the modification history of files in a project.
- Remote repository: Version of your local repo which is held somewhere else over the internet (or on your PC itself). Often named as ‘origin’
- Local repository: The folder with .git name is the local repo. This is different from working tree.
- Working directory: Synonyms: Working tree, Workspace. The actual folder which contains the files that you edit. This folder also contains the .git folder i.e. the local repository.
- Staging area: A virtual area where the changes to be committed are held. Also, called as index
- Tracked files: Files that were in the last snapshot as well as newly staged files. In short, the files that Git knows about are tracked files.
- Untracked files: All files that are not tracked are untracked files. E.g. a newly added file which is not staged.
- Tags: Tags are used to mark milestones in project development and are usually used for versioning of software. They are of two types: annotated and lightweight tags. The former one is recommended for tagging.
- Lightweight tags: These are just pointers to a commit object
- Annotated tags: These are stored as full objects in Git database. They contain tagger’s name, email, date, tag message, and are checksummed. It is recommended to use these over lightweight tags
- Commit checksum: Unique commit identifier
- Commit object, blobs, and tree: Each commit is stored as a commit object containing information about the committer, author etc. and each file’s snapshot in the commit is kept as a checksum known as a blob. A tree exists for each subdirectory and contains the information on which file belongs to which blob. The commit object holds pointer to this tree and also pointer to previous commit objects
- HEAD: Generally points to the current branch object which internally points to the last commit of the current branch. If it doesn’t point to the last commit then it is termed as detached HEAD state. This happens when one checks out a commit (or a tag) instead of the branch.
- Branches: A branch in general terms is just a timeline of commits. A repository can have many branches. E.g. ‘master’. A branch object actually contains a checksum of commit snapshot it points to. The branch pointer points to the latest commit object in that branch. Since a branch is only a label, deletion of a branch will not lead to deletion of any commit object.
- Topic branches: Branches created temporarily for specific tasks which get deleted later after the small task is closed
- Remote references: References to state of remote branches, remote tags and so on maintained in the local repo. They are updated when the local repo is connected with the remote repo. They are of the form /
- Remote-tracking branch: They are part of local repo and have the form of / and track the remote branches of a remote server in a local repo.
- Tracking branches: are branches that track a remote branch via a remote-tracking branch. The remote branch being tracked is known as the upstream branch. Short hand for upstream branch is @{u} or @{upstream} i.e. same as / e.g. ‘origin/master’
- Merge types: fast-forward merge, automatic merge and manual merge.
- Fast-forward merge: This type of merge happens when the master branch (or other parent branch to which we merge) has no commit since the branch-to-be-merged was created, this type of merge occurs.
- Automatic and manual merge: When master branch has diverged, i.e. has more commits, since the creation of the child branch these two merge types come into picture.
- Stashing: If you are in the middle of a change in a working directory and you decide to make changes to another branch or change context in the same branch, use stashing to stash your temporary work. This can also stash the code in staging area. (A better way to handle this situation is to create a different workspace for each development branch)
- Rebasing: this technique is used instead of merging to apply new changes sometimes as it helps in generating a cleaner history. The end result of both commands can be the same. In rebasing, all the commits are applied again in the same order. However, in merging there is one-single final commit. Rebasing leads to a linear history and merge leads to a non-linear history.
- Pull request: Request to pull changes/patches (in your repo) from your branch to another branch. The command is ‘git request-pull’ and not ‘git pull’.
- Tag: Tags are used to version the source code. There are of 2 types: Lightweight and Annotated (Release has release notes in addition to tag information). GitHub can only create lightweight tags.
- Markdown: GitHub and GitLab use markdown to create rich text. It can be used for various purposes like Readme.md, pull request, issue, conversation, etc. comments. File name extension is ‘.md’
- Location of gitconfig file for storing username and email, and other configurations for Git activities throughout the system for all users [Path = C:\Program Files\Git]
[Path]\etc\gitconfig
C:\Program Files\Git\etc\gitconfig
- Location of .gitconfig file for storing username and email, and other configurations for the user logged in. For company systems, use this configuration. [$HOME = ~/ = C:\Users$USER.]
~/.gitconfig
C:\Users\$USER\.gitconfig
- Location of git config for the particular repo
.git\config
.gitignore file keeps a record of those files which should not be tracked by Git in the working directory. Useful for binaries, libraries, etc. generated during builds which should not be committed to the repo. Please note that it is possible to have multiple .gitignore files for a project. Glob patterns can be defined to create rules. These are simplified regular expressions that shells use. A list of .gitignore files for various requirements is listed below at https://github.com/github/gitignore
Configurations |
Description |
---|---|
git config –-system user.name “Ritesh Udhani” git config –-global user.name “Ritesh Udhani” git config –-local user.name “Ritesh Udhani” |
Sets username used for all commits. Updates the config file #1, #2 and #3 above, respectively. Prefer to set global option as after this is set, it will be picked up for all commits from your Windows account. |
git config –-system user.email “***@huawei.com” git config –-global user.email “***@huawei.com” git config –-local user.email “****@huawei.com” |
To set email address for all commits. Updates the file #1, #2 and #3 above, respectively. Prefer to set global option as after this is set, it will be picked up for all commits from your Windows account. |
git config --global pull.rebase "false" |
From Git version 2.27, the pull.rebase configuration needs to be set by the user. This value should be kept as false for default git behavior, i.e., fast forward if possible else create a merge commit. The true option allows rebasing when pulling. This config is already set for Huawei systems. Hence, no action is required. |
git config --list --show-origin |
To see from which configuration file any configuration is picked. Listed in the order system, global and local, with increasing priority, i.e. for e.g., local setting trumps global |
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin" git config --global core.editor emacs |
To set up your favorite text editor for git files. Notepad++ recommended for windows (check for location of NotePad++ exe before setting). For emacs fans option provided as well. Sample scenario: When you have to provide commit message with git commit command |
git config -–global diff.tool bc git config --global difftool.p4merge.path " C:\Program Files\Beyond Compare 4\BComp.exe" git config –-global difftool.prompt false |
To configure Beyond Compare as the default diff tool. Use this configuration with command git difftool. This is recommended over other difftools. The prompt configuration allows one to directly open the tool without any confirmation prompt. To identify all difftools supported you your system. Run “git difftool --tool-help” |
git config -–global diff.tool p4merge git config --global difftool.p4merge.path "C:\Program Files\Perforce\p4merge.exe" git config –-global difftool.prompt false |
Allows to enable p4merge as the default diff tool. Use this if beyond compare license is not available and for no export-control situation. The prompt configuration allows one to directly open the tool without any confirmation prompt. |
git config -–global merge.tool bc git config --global mergetool.p4merge.path " C:\Program Files\Beyond Compare 4\BComp.exe" git config –-global mergetool.prompt false |
Allows to enable Beyond Compare as the default merge tool. The prompt configuration allows one to directly open the tool without any confirmation prompt. |
git config -–global merge.tool p4merge git config --global mergetool.p4merge.path "C:\Program Files\Perforce\p4merge.exe" git config –-global mergetool.prompt false |
Allows to enable p4merge as the default merge tool. Use this if beyond compare license is not available and for no export control situation. The prompt configuration allows one to directly open the tool without any confirmation prompt. |
git config --global init.defaultBranch <defaultBranchName> E.g., git config --global init.defaultBranch main |
(Optional setting): ‘master’ is the default name for the initial branch. If you want to change it, this command can be used. In this example, the initial name is set to ‘main’ |
git config <keyname> E.g., git config user.name |
Allows you to know what git thinks is the value of a particular key in configurations set |
Help |
Description |
---|---|
git help <command> git <command> --help |
To get help on a command through a full-blown man page |
git <command> -h |
A short description when you just need to remember the options |
Git basic commands |
Description |
---|---|
Creating/getting a Git repository (repo) | |
git init |
To add version control to an existing folder |
git clone <project path> |
To clone a local repository from a remote repository. The .git folder is the repository and the files are a part of working directory (working tree). |
git init <new folder name> |
To create a new folder for your project and initialize a git repo in it. |
Recording changes in a git repo, staging area and working directory | |
git add <filename> |
It means “add precisely this content to the next commit”. This command is used to start tracking an untracked file, staging a tracked file and resolve merge conflicts |
git add * git add -u |
To add all the changed files to the staging area when we do not know what all files got changed |
git restore –-staged <filename> git reset HEAD <filename> |
To unstage a file in the staging area (index). Avoid reset commands as much as possible. The ‘restore’ command works without fetching any information from the local repository, whereas ‘checkout’ fetches the information for restoring from the local repository If the change is deletion of a file which needs to be reverted, this command (restore --staged) needs to be followed up with git restore . In this case, git restore works as the information of change is still available with git |
git restore <filename> git checkout -- <filename> |
To discard modifications done in a file in working directory. Very risky commands. Be very careful when using them, else you may lose your changes. The ‘restore’ command works without fetching any information from the local repository, whereas ‘checkout’ fetches the information for restoring from the local repository If the change is deletion of a file, restore does not work. In that case, checkout command has to be used. Because it fetches the file from repo instead of relying on reversal of change. |
git commit –m “commit message” |
Commit changes to the local repo from the staging area and provide commit message inline |
git commit |
The commit message is to be entered through the default text editor for git. The commit message is very important to choose and should be 1 liner and in worst cases two lines and should be a good identifier of the change being committed from the words used. The commit ID is a unique identifier of the commit snapshot and is an SHA1 checksum. |
git commit –a –m “commit message” |
To commit directly from working tree to the repository by skipping the staging area. Use very carefully as it can be risky. |
git rm <filename> is equivalent to rm <filename> git rm <filename> |
To remove a tracked file from Git. . The first one does so by removing file from the staging area and also deletes the file from the working tree. The next commit will remove the file from the repository. The second method removes file only from the working directory first and then updates the staging area with this information |
git checkout filename |
To restore a file deleted from the working directory using ‘rm’ or ‘git rm’. |
git mv <filename1> <filename2> or mv <filename1> <filename2> git add <filename2> git rm <filename1> |
To rename a file in git. Either of the two ways can be used |
Check differences |
Description |
---|---|
git status |
To check what is going on in the local repo at file level. To check the status of each file whether it is modified, staged or up to date. It can also show if the file in the tracking branch is up to date with the remote-tracking branch. |
git status -s |
To check what is going on in the local repo at file level. Used for a simplified output as compared to git status. ‘??’ means untracked files, ‘A’ means new files added to staging area, ‘M’ modified files. Here are two columns to the output — the left-hand column indicates the status of the staging area and the right-hand column indicates the status of the working tree. |
git diff |
To check what is going on in the local repo by showing the details of changes in each file. To know the exact changes made in working directory but not staged. Compares staging area with working tree changes. |
git diff –-staged git diff --cached |
To check what is going on in the local repo by showing the details of changes in each file. To know the exact changes one is about to commit from the staging area of each file |
git diff <commit id 1> <commit id 2> |
To compare differences between two commit ids |
git diff <commit id 1> <commit id 2> <filename> |
This allows us to compare two commit ids for a particular filename |
git difftool |
Use a difftool instead of git diff command to show the differences. To know the exact changes made in working directory but not staged with difftool. Compares staging area with working tree changes. This shows one file diff at a time for Beyond Compare. Please note that this doesn’t work for docx files but gitdiff does. |
git difftool --dir-diff |
Use a difftool instead of git diff command to show the differences. Use this command to open all files differing between two versions through directory comparison, instead of opening one after the other. Read ‘git difftool’ for the other behavior. |
git difftool –-cached git difftool --staged |
Use a difftool instead of git diff command to show the differences. Also, to know the exact changes one is about to commit from the staging area of each file with difftool |
git difftool --dir-diff –-cached git difftool --dir-diff --staged |
Use a difftool instead of git diff command to show the differences. Also, to know the exact changes one is about to commit from the staging area of each file with difftool Use this command to open all files differing between two versions through directory comparison, instead of opening one after the other. Read ‘git difftool’ for the other behavior |
git difftool <commit id 1> <commit id 2> |
To use a different tool for comparison like vimdiff, emerge, p4merge etc. This allows us to compare two commit ids |
git difftool <commit id 1> <commit id 2> <filename> |
This allows us to compare two commit ids for a particular filename |
Tracking files |
Description |
---|---|
git ls-files |
To find out all the files being tracked by git |
git ls-files --other |
To list all the untracked files in a directory |
Viewing commit history |
Description |
---|---|
Viewing commit metadata (author info, committer info, date, commit id, message) and not actual data like (patch info, files info, graph) | |
git log or git log -–pretty=medium |
To see the history of commits in reverse chronological order of the current branch. This lists commit id, author name, email, date of commit and commit messages |
git log <branch name> |
To get commit history of a particular branch |
git log --all |
To see commit history of all the branches |
git log –-pretty=oneline or git log --oneline |
Shows commit information (not file information) in one line. Shows a better readable formatting when many commits are present. This lists commit id and commit messages |
git log –-pretty=short |
Shows commit information (not file information) in short. Same as git log, but no commit or author date. This lists commit id, author name, email, and commit messages |
git log –-pretty=full |
Shows committer and author information both in commit information (not file details). This lists commit id, author name, email, committer name and email, and commit messages |
git log –-pretty=fuller |
Committer and author information and the corresponding dates in commit information (not file details). This lists commit id, author name, email, committer name and email, date of author and commit, and commit messages |
git log –-pretty=format:”%h %ar” |
To get the commit id, author, committer information, date, commit message in a specific format. Shows commit information (not file information). The format specifiers are specified here. %H ,Commit hash ,%h ,Abbreviated commit hash ,%T ,Tree hash ,%t ,Abbreviated tree hash ,%P ,Parent hashes ,%p ,Abbreviated parent hashes ,%an ,Author name ,%ae ,Author email ,%ad ,Author date (format respects the --date=option) ,%ar ,Author date, relative ,%cn ,Committer name ,%ce ,Committer email ,%cd ,Committer date ,%cr ,Committer date, relative ,%s ,Subject” |
git log --relative-date |
The time relative to now when the commit was made instead of the absolute date (shows commit information and not file information) |
git log --abbrev-commit |
Shows the log information but with abbreviated commit checksum |
Viewing commit metadata (author info, committer info, date, commit id, message) and also the actual data like (patch info, files info, graph) | |
git log --stat |
In addition to commit information it displays file information like filename, no of insertions and deletions |
git log --shortstat |
In addition to commit information it displays file information with stats summary line for file changes |
git log –-name-only |
In addition to commit information it displays file names where changes happened |
git log –-name-status |
In addition to commit information it displays file information with filename and the action done on that file, like additions, modification or deletion. |
git log --graph |
To view branches and merges information in logs |
git log –p |
In addition to commit metadata, it displays file modification information to show the patch details of the commits. However, the patch information does not show content of a newly added file |
Viewing commit metadata (author info, committer info, date, commit id, message) and also the actual data like (patch info, files info, graph) through filters. | |
git log –p -2 |
Filter out commits. In addition to commit information, it displays file modification information to show the patch details of the last two commits. |
git log –p -1 <commitid> |
Filter out commits. In addition to commit information, it displays modification information to show patch details of a specific patch with commit id |
git log –-author=”<part of author name>” |
Filter out commits. To see commits by a specific author. You can speficy multiple authors. |
git log –-committer=”<part of committer name>” |
Filter out commits. To see commits by a specific committer. You can specify multiple committers. |
git log -–since=”2 weeks”(“2 years, 2 minutes, 2 hours or specify a specific date "2008-01-15" etc.) |
Filter out commits. By time boundation. –-since = --after. |
git log -–until=”2 weeks” (“2 years, 2 minutes, 2 hours or specify a specific date "2008-01-15" etc.) |
Filter out commits. By time boundation. - -until = --before |
git log -–pretty=format:”%s” --grep “message” |
Filter out commits. Greps message in commit messages and filters the commits |
git log -–pretty=format:”%s” -–grep “message1” –grep “message2” --all-match |
The all math option ANDs the two greps and only shows results which has all grep patterns in them |
git log -- <filename/directory name> |
Filter out commits. Show only those commits which are related to a specific file or directory |
git log --no-merges |
Filter out commits. Show only those commits which are not merge commits |
git log –-S <keyword to search in code> |
Filters out commits. Shows only those commits with the keyword in code |
git log --no-merges <tracking branch>..<remote tracking branch> |
Filters out commits. Show only those commits in the remote tracking branch that are not present in the tracking branch. Useful after git fetch command to know what all has changed in the remote tracking branch |
git show |
Useful to see the last patch applied. Often when ‘git log –p -1’ doesn’t show the last patch information generated after a merge. This command can be used. |
git show <commitid> |
To show the details of a commit id. |
git log –-oneline -–graph --all |
This is equivalent of a non-existing command git history. |
git log <branch name> |
To get commit history of a particular branch |
git log --all |
To see commit history of all the branches |
git branch -v |
To see the last commit on each branch |
Editing and viewing the commit history (not visible by git log) |
Description |
---|---|
git log --decorate |
To see the current branch, i.e. to which branch the HEAD is pointing. Also, the current position in the branch is also shown (Not so useful as by default also HEAD is shown in latest git versions) |
git reset <commit id> --soft |
Moves the HEAD pointer to a particular commit id. The diff between the original HEAD position and the current position is saved in the staging area. Git log after this command will show timeline of commits done before this commit id and not the ones after. Used to delete some commits |
git reset <commit id> --mixed |
Moves the HEAD pointer to a particular commit id. The diff between the original HEAD position and the current position is saved in the working directory and staging area is blank. Git log after this command will show timeline of commits done before this commit id and not the ones after. Used to delete some commits |
git reset <commit id> --hard |
Moves the HEAD pointer to a particular commit id. The diff between the original HEAD position and the current position is not saved. Git log after this command will show timeline of commits done before this commit id and not the ones after. Used to delete some commits |
git reflog |
Stores all commit ids and actions taken in this repos in the entire history. So, this is a comprehensive history. Even deleted branches etc. can be tracked by this. |
Git Aliases |
Description |
---|---|
git config –-global alias.history “log –-oneline -–graph --all” |
Use git aliases to shorten a long command. In this example we create history alias for the log command to shorten it. Usage ‘git history’ |
mr = !sh -c 'git fetch $1 merge-requests/$2/head:mr-$1-$2 && git checkout mr-$1-$2' - | Required mostly for reviewers only. Allows to check a merge request using its ID instead of its branch as each merge request can be viewed using head ref (refs/merge-requests/:iid/head). Available from GitLab version 13.4. Usage ‘git mr origin <mergerequestnumber =5>’. This fetches the merge request into a local mr-origin-5 branch and check it out. Allows you to use beyond compare to review the source. |
Tagging |
Description |
---|---|
git commit --amend |
To amend previous commit by additionally committing staging area contents to the previous commit. It can also help to modify the commit message. Here, the previous commit is deleted and replaced by a new commit. Hence, once needs to be very careful in using this. |
Git Aliases |
Description |
---|---|
git tag |
Lists all the tags for a repository. |
git tag -l "v1.8.5*" |
To match all tags with 1.8.5 in their names at the beginning. For wildcard entries –l option is necessary. |
git tag <pipe> grep “pattern*” |
List only those tags which have a pattern |
git tag –a <tagname> -m “<commit message>” |
Creates an annotated tag <tagname> (e.g. v1.0) for the HEAD position with commit message and it also records taggers information |
git tag <tagname> |
Creates a tag of ‘tagname’ for the HEAD position. This is a lightweight tag. It is better to use annotated tags. |
git tag <tagname> <commit id> |
To tag a particular commit id using a lightweight tag |
git tag -a <tagname> <commit id> |
Create an annotated tagname for a specific commit id. |
git tag –f <existing tagname> <commit id> |
Updating an existing tag to a new commit id on local repo. |
git show <tagname> |
To show detailed information about a particular annotation tag e.g. the tagger, tagger email, time of tag, tag message, commit information etc. For lightweight tag, it only shows the commit information. |
git push <remote repo> <tagname> |
Since tags are not pushed by default. They need to be pushed explicitly. Remote repo example is ‘origin’. This method pushes only one tag at a time. |
git push -–force <remote repo> <tagname> |
To update an existing tag on git hub |
git push <remote repo> --tags |
Pushes all the tags (annotated and lightweight) to the remote server |
git push <remote> --follow-tags |
Pushes only the annotated tags to the remote server |
git tag -d <tagname> |
Delete a tag on a local repo |
git push <remote repo> -d <tagname> or git push <remote repo> :<tagname> or git push <remote repo>: refs/tags/<tagname> |
Delete a tag on remote repo. Since tags are not pushed by default, they need to be deleted explicitly too |
git checkout <tagname> |
If you want to view the source code at a particular tag. It is not a good approach if you want to modify it too as the HEAD is in detached state |
git checkout -b <new branchname> <tagname> |
Create a new branch if you want to edit the files at a particular tagname |
Save Intermediate stage |
Description |
---|---|
git stash |
To stash the current state of a branch so that it can be used later again from the same state. Avoid stashes and have multiple branches instad for development |
git stash list |
To list all the stashes |
git stash pop |
To pop the stash in the stack. It pops the latest entry to resume work from where it was last left |
git stash pop stash@{<stash number>} |
To pop a particular stash |
Commands for branching |
Description |
---|---|
git branch |
Shows all the branches in a local repo and also shows ur current branch marked with * |
git branch -a |
Shows all the local and remote branches |
git branch <new branch name> |
To create a new local branch. The new branch created points to the same commit object where the current branch points to when the new branch was created. The current branch, however, is not switched |
git checkout –b <new branch name> or git switch -c <new-branch> |
To create a new local branch. The new branch created points to the same commit object where the HEAD points to in the current branch when the new branch was created. The current branch is switched to the newly created branch |
git checkout <branch name> or git switch <branch name> |
To switch from an existing branch to the different branch (which already exists, it can create a tracking branch too, look at the other usage). Moves to the top commit of the branch. Also modifies the working directory accordingly. Always commit your changes in the current branch before you invoke git checkout of a new branch. If you are in the middle of something then stash your changes before switching. Branch switching won’t work if you have uncommitted changes |
git switch - |
To switch to previous branch |
git checkout –b <new local branch name> <remote repo>/<existing remote branch> Is the same as git checkout --track <remote repo>/<existing remote branch> same as git checkout <existing remote branch name>, e.g. git checkout testbranch |
To create a new tracking branch from a remote tracking branch and switch to it. The remote tracking branch could be updated on git fetch call. . The last one works when the branch specified has a unique name across all remote tracking branches and tracking branch is already not present |
git branch -vv |
To find out the local branches that are tracking branches or not, their status if they are up to date with remote-tracking branches, ahead or behind but it does not compare with the actual remote branches. No connection with the server is created to get this status. For getting an up to date status run ‘git fetch’ before. E.g. git fetch –all; |
git branch –d <branch name> |
To delete a local branch. Works only when all changes are merged to another branch else it will fail |
git branch –D <branch name> |
To forcefully delete a local branch even if its contents aren’t merged yet. |
git push origin --delete <remote-branch-name> |
To delete a remote branch |
git branch --move <bad-branch-name> <corrected-branch-name> git push --set-upstream origin <corrected-branch-name> git push origin --delete <bad-branch-name> |
Steps to rename a branch at local and remote repo. Do not change name of the master or the like branches. Also, avoid changing branch names as much as possible as your collaborators, CI system, etc. can get impacted |
git branch -–merged /--no-merged |
This is to find from the reference of the current branch. This finds all the other branches that are |
git branch –-merged/--no-merged <ref branch name> |
To see merged/no-merged branches for the branch ‘ref branch name’ |
git checkout <commit id> |
To checkout a specific commit id. Leaves the HEAD in detached state. So, don’t make changes here. If changes are necessary, create a branch instead. |
git merge <branch to be merged to the current branch> |
Merges the content of the branch to be merged to the current branch. If “fast-forward” phrase is observed during merge then it implies the two branches weren’t divergent and one was part of another’s history. If the branches were divergent, and there were no merge conflicts it would automatically merge. When merge conflicts are reported, run ‘git status’ to identify the conflicting files. Resolve conflicts in each file. The files with conflicts will contain symbols like “<<<” “>>>” and “===” delete these and resolve the conflict by editing this section and then do ‘git add’ to stage the resolved conflicts. Do git commit to commit the changes. You can edit the comment if you think it will help others to know what you did to resolve the changes. |
git mergetool |
This is used to run a visual merging tool when a merge conflict is detected. This helps to do manual merge. The merge conflict files are automatically detected by the tool after a conflict is reported. You can run this after git status step from the previous block |
git checkout experiment git rebase master git checkout master git merge experiment |
Steps for rebasing a new development on branch ‘experiment’ onto ‘master’ branch which has diverged. This is an alternative to merge method. |
Working with remotes | |
git remote |
To see the name of remote servers configured. If a repo is cloned then we should see name of atleast one remote repo. The default name of the repo server is ‘origin’ from which you cloned. |
git remote -v |
To see the url of the remote servers for both fetch and push |
git remote show <remote repo name> |
To show complete information about a particular remote repo including its branch information. Shows the remote URL, push and pull urls. Shows the remote branches that are tracked or untracked. Shows the local branches configured for push and pull requests |
git remote add <shortname> <url> |
To add a remote server. Shortname is usually ‘origin’. But it can be changed too. Shortname is only the localrepo’s name for the remote repo. The actual remote repo is a complete url. For multiple user workflows, even multiple remote repos can be added here. However, it is not required if your workflow does not require it. To know about the branches in the remote repo, run git fetch to update the local repo with the latest info on these branches. After this, you can checkout these branches to inspect them or merge their content to one of your tracking branches |
git remote rename <currentname> <newname> |
To rename a remote repository in the local repo records. The server of remote repo has no changes. E.g. ‘Origin’ remote can be changed to ‘Server’ |
git clone –o <name for remote repo> |
While cloning if we want a specific name of the remote repo, other than the default ‘origin’, it can be done like this |
git remote remove <remote repo name> git remote rm <remote repo name> |
To remove a remote repo. E.g. remote repot name is ‘origin’. This is required when a particular remote repo is deleted, when a contributor is not more going to contribute, etc. Removal of a remote repo will not remove the tracking branches associated with them |
git push <remote repo> --delete <remote branch name> or git push <remote repo> :<remote branch name> |
To delete a remote branch from a remote repo. To be done only if branch contents are merged to another. |
git fetch <remote repo name> |
Merges data from the remote repository to the local repository. No change is made to the working directory. They have to be merged manually. Only the remote-tracking branch is updated in the local repository and not the tracking branch. For multi-branch scenario, all remote-tracking branches are updated. |
git fetch -p |
This is helpful to prune those remote tracking branches for which the remote repo is deleted. Simple git fetch will not prune these branches. |
git fetch --all |
To fetch from all the remote repos instead of just one |
git pull |
If you are on a tracking branch and issue this command then git will automatically fetch changes for the current repo and synchronize remote tracking branches with upstream and merge changes in the tracking branch. It is same as git fetch and git merge . This to be done only when all the changes are committed to the local branch. For multi-branch scenario, the command can be configured to update all branches as well. |
git pull <remote repo name> |
git pull for a particular repo |
git pull --all |
To update all local branches in a multi-branch multi repo scenario |
git checkout --ours -- path/to/file.txt git checkout --theirs -- path/to/file.txt |
For binary files when merge fails after fetch, one needs to decide which file one wants to keep from the two i.e. master or origin/master. These commands help to resolve that |
git push --all |
To push all branches changes at once. |
git push <remote> refs/heads/<local branch name>:refs/heads/ or git push <remote> <local branch name>:<remote branch name> |
It means push my local branch to remote repo under a different branch name |
git remote set-url origin <new url name> |
If the remote repository is updated, its remote references in the local repo also need to be updated. This is the method to update the url |
GitLab issue management |
Description |
---|---|
git commit –m “Comment.., Closes #<issue number>” git commit –m “Comment.., Fixes #<issue number>” e.g git commit –m “Comment.., Closes #4” |
To close an issue on GitHub/GitLab with a commit id for easier tracking of Issues with their respective solutions. For issues already closed, a commit id can be associated by providing comment as in the example “Associating #3 with the issue” |
- Anything that is committed to the repo can always be recovered. Even if it was a commit that was deleted later. Anything lost that was not committed will be lost forever.
- If a file is modified, staged and modified again, the commit will be done only for the changes which have been staged and not the latest ones in the working directory
- Use Topic branches for development always.
- Rebase commits only for your local repo (if you like). Don’t do it for remote repos.
- Before push do a git fetch and merge always (or git pull)
- Delete .git folder from a project if it occupies a lot of space when creating copies of the project and when version control is not needed
- Always prefer to use git restore over git reset
- Don’t push your work unless you are happy with it
- Documentation at https://git-scm.com/doc
- Reference for this document Progit book on Git https://git-scm.com/book/en/v2
In case of errors due to formatting, please refer to the attached word file