Git has become the main version control system for our code. This means we need a good understanding of Git to maintain/contribute/develop any software nowaday.
git configInitial Config
Is this first time you use Git? Then you should start setting up your email and name, which will be used in all your projects.
git config --global user.name "Your Name" git config --global user.email firstname.lastname@example.org
We must ask ourselves if we are importing an existing project or creating a new one.
git clone [url]
git init git add . git commit -m 'First commit' git remote add origin https://github.com/user/project git push origin master
The staging area or
git add has a primary function, is to promote pending changes in the working directory. After you're happy with changes or staged snapshot, you commit them to the project history.
git add [file] # Add a single file or directory git add . # All files and directory git add -p # Interactive mode
Get all information about repo's current state.
By default git will show you any uncommitted changes since the last commit.
Restore files from current index unstagging them to last committed state.
git reset [file] [*.txt] [/dir] git reset -p # Interactive mode
Or simply checkout the file.
git checkout -- file.txt
git commitOk, all look works
Once we saved a snapshot of the current project state with
git add, the
git commit command is then used to register current state to the repository commit history.
git commit -m 'First commit'
Or you can add changes to last commit:
git commit --ammend
git mergeBranching and merge
merge will combine multiple commits into one unified history. In the most frequent use cases, merging is used to combine two branches. We should follow merge-commit pattern to keep an initial and end point in the history.
git checkout -b newfeature git add . git commit -m 'Added new feature' git checkout master git merge newfeature -m 'Merged newfeature into master' git push master
git pullBe up-to-date!
Merge remote upstream changes into your local repository with
git pull. This command is a combination of two other commands,
git fetch followed by
git merge. In the first stage git will retrieve latest changes where HEAD is pointed at. Once the content is downloaded, git pull will enter a merge workflow.
Sometimes we have an upstream that rebased/rewound a branch we're depending on. This can be a big problem causing messy conflicts for us if we're downstream. We can solve it rebasing:
git pull --rebase
git resetOuch! I did a mistake
When we want to restore entire branch to last commit we should:
git reset --hard HEAD~1
You can undo n commits using
HEAD~n. Be careful! Deletes local changes