Git Knowledge Base

Aus MattWiki
Version vom 3. August 2024, 12:55 Uhr von Matt (Diskussion | Beiträge) (→‎Git Commands and How To's)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

Good introductions to Git:

Git Cheat Sheet

Git Cheat Sheet
Task Command
Initialize empty repository git init
Add file to staging area git add <file> or <pattern>
Remove file from staging area git rm --cached <file>
Commit files to repository git commit -m "<Message>"
View and manage remote repositories git remote
Clone remote repository git clone <URL>
Update remote repository from local git push
Fetch objects from remote repositories git fetch
Fetch objects from remote and merge git pull
Create branch git branch <name>
Change to branch git checkout <branch>
Merge branch to current branch git merge <branch>
Show commit history git log [--oneline] [--graph]
Unstage file git reset HEAD <file>
Discard file changes git checkout -- <file>
Alter last commit git commit --amend
Go back to previous commit git reset <commit>

git reset HEAD~

Git Basic Knowledge

Git works with:

  • Snapshots
  • Most operations happen locally

A file added to a repository can have the following states:

  1. Modified (but not staged)
  2. Staged (but not commited)
  3. Commited

git pull = git fetch + git merge

Notable Files
Location Filename Description
. .gitignore List of files and directories to be ignored
.git HEAD Contains reference to HEAD commit checksum of current branch
.git/refs/heads/ main HEAD commit checksum of branch
.git description Repository description


Git Commands and How To's

Staging / Unstaging Files

git add <file>|<pattern>              Add file or pattern to staging area
git reset HEAD <file>                 Remove file from staging area
git checkout -- <file>                Discard changes in working directory 
                                      (Caution: Cannot be undone)
git status
								  

Commit and Alter Commit

git commit -m "<Message>"             Commit staged files with message
git commit --amend                    Replace last commit (Replace message if not other changes are specified)
git commit --amend -m "<Message>"     Replace specifically last commit message 


Reset vs. Revert

https://www.datacamp.com/tutorial/git-reset-revert-tutorial

Reset Commit

How to reset the current branch to a previous commit, or to be more precise: How to reset the HEAD pointer to a previous commit?

git reset HEAD~                       The tilde character refers to the last commit before HEAD.
                                      Two tilde characters would refer to the second to last commit before HEAD.

HEAD can be replaced by checksum of commit

Resetting
command Is Default Changes what Resets Staging Area Reset Work Directory Secure
git reset --soft HEAD~ No Branch HEAD No No Yes
git reset --mixed HEAD~ Yes Branch HEAD Yes No Yes
git reset --hard HEAD~ No Branch HEAD Yes Yes No, resets work directory


Revert

git revert --no-commit <commit ID>

https://stackoverflow.com/questions/4114095/how-do-i-revert-a-git-repository-to-a-previous-commit --> Siehe Abschnitt git revert --no-commit

Reset vs Revert of Merge Commit

https://www.git-tower.com/learn/git/faq/undo-git-merge

Long story short:

If not pushed to remote, simply reset to the commit before the merge:

git reset --hard <commit-before-merge>

If pushed to remote repository use revert

git revert -m 1 --no-commit <commit ID>

The No-Commit option puts the previous file states in the working directory unstaged for review and later commiting.

History

git log                               Show commit history
git log --oneline                     Show only one line per commit in CLI instead in viewer
git log --oneline --graph             Additionally show graph view
git log -p                            
git log --stat
git log --pretty


Branching

git branch -a                         List all branches
git branch NewBranch                  Create "NewBranch"
git branch -d NewBranch               Delete "NewBranch"
git branch -m NewName                 Rename current branch to "NewName"
git checkout NewBranch                Switch to "NewBranch"
git checkout master                   Switch to master branch
git merge FromBranch                  Merge changes FromBranch to current branch
git mergetool                         


Stash / Change Branch Without Commit

When changing branches without adding files and committing them then they will not be added to their original branch. To prevent this one can create a Work-In-Progress State and stash everything there before changing the branch. Proceed as follows:

git add .                             Add all files
git stash                             Assign all changes to WIP-State to the current branch
git checkout <Branch2>                Change to second branch
...                                   Work on second branch
git checkout <Branch1>                Return to first branch
git stash apply                       Fetch files from WIP-State to the working directory


Remote-Repositories

git remote                            Show remote repositories
git remote -v                 		   Additionally show names and paths of remote repositories
git remote add <alias> <URL>          Add remote repository at URL as alias
git remote remove <alias>             Remove remote repository with given alias
git remote rm <alias>                 dto.

Clone, Fetch, Pull, Push

git clone <URL>                       Clone remote repository from <URL>
git fetch <alias>                     Fetch changes from alias repo without automatic merge
git pull <alias>                      Like fetch but with automatic merge
git push <alias>/<branch>             Push changes to <alias>/<branch>
git push --set-upstream origin main   Set upstream target alias (origin) and branch (main)
git push                              Requires push.default configuration (see below)

Grundbefehle

git bundle create file.git --all      Gesamtes serverseitiges Repository in eine Datei packen


Nützliche Programme

git gui                               Grafische Oberfläche für Commits
gitk                                  Grafische Oberfläche für History


Commits

Mit Texteditor

git commit                            Committext-Eingabe VIM-ähnlich:

Vorgehen in VIM

  • I drücken → Wechselt zu Insert Mode
  • Comit Text eingeben
  • Esc drücken
  • :wq eingeben (Speichern + Beenden)

Per Commandline

git commit -m 'change text'


Dateien ignorieren

Git-Ignore-Datei erstellen:

touch .gitignore

Beispielinhalt'

# Archiv-, Log- und Object-Dateien
*.a
*.o
*.log

# Emacs-Backupdateien (Alle, die mit ~ enden)
*~

# Verzeichnisse ignorieren
bin/
obj/



Installing Git

git -v                                Check version

Source: https://git-scm.com/download

Don't forget to configure user name and email adress like described below.

Configuring Git

Git Global Config

git config --global user.name                             Return user name
git config --global user.name "FirstName LastName"        Set FirstName LastName as user name
git config --global user.email                            Return user email
git config --global user.email "example@email.com"        Set example@email.com as user email
git config --global push.default matching                 Set push.default to matching which results in
                                                          git push always pushing to remote branch

with the same name


Git-Aware Bash-Prompt

Bash erweitern um Erkennung von Git-Archiven.

emacs ~/.bashrc

Am Ende einfügen:

# Git aware bash prompt
export GIT_PS1_SHOWDIRTYSTATE=true
export GIT_PS1_SHOWUNTRACKEDFILES=true
export GIT_PS1_SHOWSTASHSTATE=true
export PS1="${PS1::$((${#PS1}-3))}\$(__git_ps1 ' [\[\e[34;1m\]%s\[\e[0m\]]')\$ "


The Seven Rules of a Great Commit Message

Source: https://chris.beams.io/posts/git-commit/#seven-rules

  1. Separate subject from body with a blank line
  2. Limit the subject line to 50 characters
  3. Capitalize the subject line
  4. Do not end the subject line with a period
  5. Use the imperative mood in the subject line
  6. Wrap the body at 72 characters
  7. Use the body to explain what and why vs. how


Use the imperative mood in the subject line

Commit subject lines should be written in the imperative mood, i.e.:

  • Clean your room
  • Close the door
  • Take the trash out

Examples:

  • Refactor function X
  • Remove deprecated classes
  • Update getting started documentation

Goal is to have the commit subject line complete the following line in a meaningful sense:

  • If applied, this commit will <your subject line here>

Examples:

  • If applied, this commit will refactor function X
  • If applied, this commit will remove deprecated classes
  • If applied, this commit will update getting started documentation