Git Knowledge Base: Unterschied zwischen den Versionen

Aus MattWiki
K (Matt verschob die Seite Git Grundlagen nach Git Knowledge Base, ohne dabei eine Weiterleitung anzulegen)
Keine Bearbeitungszusammenfassung
Zeile 1: Zeile 1:
Gutes Video-Einleitung (und Quelle für untenstehendes):
Good introductions to Git:
 
* Learn Git in 20 Minutes → https://www.youtube.com/watch?v=Y9XZQO1n_7c
* Let’s Git - Versionsverwaltung und OpenSource → https://open.hpi.de/courses/git2020
* Pro Git book by Scott Chacon and Ben Straub: https://www.git-scm.com/book/en/v2
 
== Git Cheat Sheet ==
 
{| class="wikitable"
|+ Git Cheat Sheet
|-
! Task !! Command
|-
| Initialize empty repository || <code>git init</code>
|-
| Add file to staging area || <code>git add <file>|<pattern></code>
|-
| Remove file from staging area || <code>git rm --cached <file></code>
|-
| Commit files to repository || <code>git commit -m "<Message>"</code>
|-
| View and manage remote repositories || <code>git remote</code>
|-
| Clone remote repository || <code>git clone <URL></code>
|-
| Update remote repository from local || <code>git push</code>
|-
| Fetch objects from remote repositories || <code>git fetch</code>
|-
| Fetch objects from remote and merge || <code>git pull</code>
|-
|  || <code></code>
|-
|  || <code></code>
|-
|  || <code></code>
|-
| Create branch || <code>git branch <name></code>
|-
| Change to branch || <code>git checkout <branch></code>
|-
| Merge branch to current branch || <code>git merge <branch></code>
|-
| Show commit history || <code>git log [--oneline] [--graph]</code>
|-
| Unstage file || <code>git reset HEAD <file></code>
|-
| Discard file changes || <code>git checkout -- <file></code>
|-
| Alter last commit || <code>git commit --amend</code>
|-
| Go back to previous commit || <code>git reset <commit></code>
<code>git reset HEAD~</code>
|-
|  || <code></code>
|-
|  || <code></code>
|}
 
== Git Basic Knowledge ==
 
Git works with:
 
* Snapshots
* Most operations happen locally
 
A file added to a repository can have the following states:
 
# Modified (but not staged)
# Staged (but not commited)
# Commited
 
<code>git pull</code> = <code>git fetch</code> + <code>git merge</code>
 
{| class="wikitable"
|+ Notable Files
|-
! Location !! Filename !! Description
|-
| <code>.</code> || <code>.gitignore</code> || List of files and directories to be ignored
|-
| <code>.git</code> || <code>HEAD</code> || Contains reference to HEAD commit checksum of current branch
|-
| <code>.git/refs/heads/</code> || <code>main</code> || HEAD commit checksum of branch
|-
| <code>.git</code> || <code>description</code> || 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 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
{| class="wikitable"
|+ Resetting
|-
! command !! Is Default !! Changes what !! Resets Staging Area !! Reset Work Directory !! Secure
|-
| <code>git reset --soft HEAD~</code> || No || Branch HEAD || No || No || Yes
|-
| <code>git reset --mixed HEAD~</code> || Yes || Branch HEAD || Yes || No || Yes
|-
| <code>git reset --hard HEAD~</code> || No || Branch HEAD || Yes || Yes || No, resets work directory
|}
 
=== 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)


Learn Git in 20 Minutes &rarr; https://www.youtube.com/watch?v=Y9XZQO1n_7c


== Grundbefehle ==
== Grundbefehle ==
git init          Initiieren
  git bundle create file.git --all     Gesamtes serverseitiges Repository in eine Datei packen
nano .git/description    # Projektbeschreibung einfügen
git status        Status des Repository
git add <file>    Staging einer Datei
git add .        Staging aller Dateien (exkl. Ignore-Liste)
git add *.html    Staging aller *.html-Dateien
git log          Commit Historie anzeigen
  git bundle create file.git --all     Gesamtes serverseitiges Repository in eine Datei packen


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


== Nützliche Programme ==
== Nützliche Programme ==
  git gui           Grafische Oberfläche für Commits
  git gui                               Grafische Oberfläche für Commits
  gitk             Grafische Oberfläche für History
  gitk                                 Grafische Oberfläche für History




== Commits ==
== Commits ==
=== Mit Texteditor ===
=== Mit Texteditor ===
  git commit       Committext-Eingabe VIM-ähnlich:
  git commit                           Committext-Eingabe VIM-ähnlich:


'''''Vorgehen in VIM'''''
'''''Vorgehen in VIM'''''
Zeile 57: Zeile 218:




== Entwicklungszweige ==
=== Allgemein===
git branch -a              Alle zweige auflisten
git branch NewBranch        Neuen Zweig "NewBranch" erstellen
git branch -d NewBranch    Zweig "NewBranch" löschen
git branch -m NewName      Aktuellen Zweig in "NewName" umbenennen
git checkout NewBranch      Zum Zweig "NewBranch" wechseln
git checkout master        Zum Master-Zweig zurückkehren (heißt meistens so)
git merge SourceBranch      Änderungen in SourceBranch in aktuellen Branch mergen
git mergetool              Mergewerkzeug


=== Zweig wechseln ohne Commit ===
Wenn man den Zweig wechselt, ohne vorher zu adden/committen werden neue Dateien nicht dem ursprügnlichen Zweig zugeordnet. Um dies zu vermeiden, kann man einen WIP-Stack in einem Zweig anlegen, bevor man den Zweig wechselt:


git add .                  Zuerst alle Dateien adden
== Installing Git ==
git stash                  Änderungen in WIP-Status dem Zweig zuordnen
git checkout <Branch2>      Wechseln
...                        Bearbeiten
git checkout <Branch1>      Zurückwechseln
git stash apply            Datein aus WIP-Status wieder zurückholen


== Remote-Repositories ==
  git -v                                Check version
=== Allgemein ===
   
  git remote                    Namen des Remote-Repositories anzeigen
'''Source:''' https://git-scm.com/download
  git remote -v                Namen und Pfade des Remote-Repositories anzeigen
 
git remote add <name> <remotepath>  Remote-Repository unter dem Namen bekannt machen
Don't forget to configure user name and email adress like described below.
git remote remove <name>      Rremote-Repository entfernen


=== Holen ===
== Configuring Git ==
git clone https://host/*.git  Klonen des *.git-Repositories vom Host
git fetch <reponame> <branch> Änderungen seit letztem clone/fetch in den aktuellen Zweig holen, ohne automatisch zu mergen
git pull <reponame> <branch>  Änderungen ins aktuelle Repository fetchen und automatisch mergen


=== Senden ===
=== Git Global Config ===
  git commit -a -m 'text'      Zuerst committen
  git config --global user.name                            Return user name
  git push <reponame> <branch> Änderungen an Zweig in Remote-Repository übertragen/committen
git config --global user.name "FirstName LastName"        Set FirstName LastName as user name
  git config --global push.default matching
  git config --global user.email                            Return user email
                              Setzt push.default auf matching, was dazu führt, dass
  git config --global user.email "example@email.com"        Set example@email.com as user email
                              git push immer an den Remote Branch mit dem gleichen Namen hochlädt
  git config --global push.default matching                 Set push.default to matching which results in
git push                      Setzt push.default voraus - siehe oben
                                                          git push always pushing to remote branch
git push --set-upstream origin master
  with the same name




== Git-Aware Bash-Prompt ==
=== Git-Aware Bash-Prompt ===
Bash erweitern um Erkennung von Git-Archiven.
Bash erweitern um Erkennung von Git-Archiven.


Zeile 112: Zeile 252:
  export GIT_PS1_SHOWSTASHSTATE=true
  export GIT_PS1_SHOWSTASHSTATE=true
  export PS1="${PS1::$((${#PS1}-3))}\$(__git_ps1 ' [\[\e[34;1m\]%s\[\e[0m\]]')\$ "
  export PS1="${PS1::$((${#PS1}-3))}\$(__git_ps1 ' [\[\e[34;1m\]%s\[\e[0m\]]')\$ "


== The Seven Rules of a Great Commit Message ==
== The Seven Rules of a Great Commit Message ==

Version vom 16. Oktober 2023, 19:40 Uhr

Good introductions to Git:

Git Cheat Sheet

Git Cheat Sheet
Task Command
Initialize empty repository git init
Add file to staging area <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 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

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