Skip to content

Latest commit

 

History

History
4164 lines (1596 loc) · 56.9 KB

README.md

File metadata and controls

4164 lines (1596 loc) · 56.9 KB

Git Sheet Sheet

Git Sheet Sheet with the most needed stuff...



Postman



Import Repo to Postman






Install

# Method #1
sudo apt-get install git



# Method #2
sudo apt install libz-dev libssl-dev libcurl4-gnutls-dev libexpat1-dev gettext cmake gcc -y

# get latest version and replace in link below
# https://github.com/git/git/tags
wget -c https://github.com/git/git/archive/refs/tags/v2.44.0.tar.gz -O - | sudo tar -xz -C /usr/src

cd /usr/src/git-*
sudo make prefix=/usr/local all
sudo make prefix=/usr/local install

git --version



Uninstall

sudo apt-get purge git
sudo apt-get autoremove
sudo apt-get install git










Terminal Editor



Nano

git config core.editor "nano"










Workflows

  • The next section does contain example of what commands to use in different all day scenarios
Click to expand..

Ticket > MR

  1. Set Ticket to In progress in Jira
  • Move into current sprint

  1. Create new feature and feature-dev branch base from develop branch
git checkout develop
git pull
mkbranch
  1. If you have a local environment like minikube then update to the latest state that your deployments or services which you are using are at the latest state

  2. If needed update dependencies

npm ci
  1. Solve your ticket and push commit on feature-dev branch
  • Make sure als tests are working
  • Did you remove all.only?
  • Did you create everything related to the ticket? E.g. migrations scripts?

  1. Squash merge feature-dev branch -> feature branch
git checkout your-feature-branch
git merge --squash your-feature-dev-branch
# If there are breaking changes then to breaking change commit instead of normal commit!
git commit -m "fix(ABC-232): Edit custom block"
git push

If there are breaking changes set commit message footer:

git commit -m 'fix(ABC-232): Edit custom block' -m 'BREAKING CHANGE: Route xyz has been
renamed to abc'

# If you accedently already committed without breaking change then you can do:
# git add . && git commit --amend -m 'refactor(ABC-2139): Update MongoDB from 5 to 7' -m 'BREAKING CHANGE:
Update MongoDB from 5 to 7'
Make sure that only 1 Commit exists on your feature branch. If you forget to add changes then use:
```shell
git add . && git commit --amend --reuse-message HEAD && git push -f
```
	
	If you accedently have multiple comments on your feature branch you can reset the commits:
	```shell
	# Use git log to check how many of the recent commits need to be squashed. Alternatively, you can also see this in the merge request (MR).
	
	# Switch to the target branch
	git checkout your_branch
	
	# Soft reset the last e.g. 4 commits locally
	# Alternatively, you can do it one-by-one with git reset --soft HEAD^, which is a safer option.
	git reset --soft HEAD~4
	
	# Ensure the affected commits no longer appear in the history:
	git log
	
	# Ensure the files from the previous commits are still present
	git status
	
	git add . && git commit --amend --reuse-message HEAD && git push -f
	```
	
	There are exceptions. For example, if you're working on a ticket with sub-tasks, you can create multiple commits related to different ticket IDs:
	- Branching Strategy | Feature branches
	- Warning: If your MR is rejected due to an issue in the first commit, you'll need to stage the files again and recreate the commits.
	```shell
	There are exceptions. For example, if you're working on a ticket with sub-tasks, you can create multiple commits related to different ticket IDs:
	- Branching Strategy | Feature branches
	- Warning: If your MR is rejected due to an issue in the first commit, you'll need to stage the files again and recreate the commits.
	
	# If you've already committed, you can amend it afterward:
	git add . && git commit --amend -m 'refactor(CCS-2139): Update MongoDB from 5 to 7' -m 'BREAKING CHANGE: Update MongoDB from 5 to 7'
	
	Important
	
	git add . && git commit --amend --reuse-message HEAD && git push -f
	
	# Use git log to check how many of the recent commits need to be squashed. Alternatively, you can also see this in the MR.
	
	# Switch to the target branch
	git checkout your_branch
	
	# Soft reset the last e.g. 4 commits locally
	# Alternatively, you can do it one-by-one with git reset --soft HEAD^, which is a safer option.
	git reset --soft HEAD~4
	
	# Ensure the affected commits no longer appear in the history:
	git log
	
	# Ensure the files from the previous commits are still present
	git status
	
	# Stage the previously committed files. You’ll need to decide which files to stage for your 1st commit and which for the 2nd:
	git add README.md
	
	# Ensure the desired files are staged:
	git status
	
	# Force push to overwrite the commit history on GitLab with the local changes
	git push -f
	
	# If you have a 2nd commit, repeat the same process.
	```

  1. Rebase develop -> feature branch
cd ais-ccm-repo

git checkout develop
git pull
git checkout fix/ABC-232/edit-custom-block/main
git rebase develop

# ----- Resolving potential merge conflicts ----
# If there are merge conflicts and you solve them, use:

# If there are merge conflicts with package-lock.json:
# rm -f package-lock.json
# npm i

# git add .
# git rebase --continue

# Necessary if untracked files remain when switching branches.
git clean -f -d -x -i -e node_modules

# Make sure again that the unit tests and integration tests pass locally.

Run this command every time! If there are changes to NPM packages, such as an update to a higher version, we can install the current version with this command:

npm ci
  1. Push feature branch
git push --set-upstream origin fix/ABC-232/edit-custom-block/main

# git push --force --set-upstream origin fix/ABC-232/edit-custom-block/main
# --force is only needed if the branch was already pushed before the rebase.
# During a rebase, the commit history is always overwritten,
# so the next push will always require the --force flag.
  1. Wait until gitlab pipeline is finished

  2. Deploy to test cluster and if everything is working set ticket to FINISHED.

  3. Create MR in gitlab feature branch -> develop branch

  4. If needed update Postman collection





Create new branch and use current code status without git add/stash

  • You can just create a new switch and then checkout on it. The current code from your old branch will be copied in the new you had created and where you checkout.
git branch my-test-branch
git checkout my-test-branch





Merge



Revert changes from git pull with merge conflicts

  • Imagine you did a git pull and had 2 merge conflicts. You solved one of them but it was not correct and you want to revert your changes then you do:
git merge --abort







Squash merge branch into current branch without merge conflicts

git checkout sourceBranch
git merge --squash targetBranch
git commit -m "Test"
git push



Squash merge branch into current branch with merge conflicts

git checkout sourceBranch
git merge --squash targetBranch

# Merge Conflicts with your IDE

git commit -m "Test"
git push



Revert merge if no commit was made by deleting the branch locally

git checkout otherBranch
git branch -D targetBranch # will delete the branch local
git checkout targetBranch





Rebase



Squash merge branch into current branch without merge conflicts

git fetch -u origin develop:develop
git rebase develop

# Resolve Merge Conflicts
# If there are merge conflicts and you solve them use
# git add .
# git rebase --continue

git push -f





Pull



Current branch is local outdated and there are changes remote

# hint: You have divergent branches and need to specify how to reconcile them.
# hint: You can do so by running one of the following commands sometime before
# hint: your next pull:
# hint: 
# hint:   git config pull.rebase false  # merge (the default strategy)
# hint:   git config pull.rebase true   # rebase
# hint:   git config pull.ff only       # fast-forward only
# hint: 
# hint: You can replace "git config" with "git config --global" to set a default
# hint: preference for all repositories. You can also pass --rebase, --no-rebase,
# hint: or --ff-only on the command line to override the configured default per
# hint: invocation.
# fatal: Need to specify how to reconcile divergent branches.

git config pull.rebase false
git pull





Branches

develop, feature and feature-dev branch

# Pull from latest main branch in this case develop and then create feature branch
git checkout develop
git pull
git branch fix/TICKET-232/edit-custom-block/main

# Create feature-dev branch, checkout to it and then work on your ticket
git checkout fix/TICKET-232/edit-custom-block/main
git branch fix/TICKET-232/edit-custom-block/kho
git checkout fix/CCS-232/edit-custom-block/kho

# Merge feature-dev branch into feature branch
git checkout fix/TICKET-232/edit-custom-block/main
git merge --squash fix/TICKET-232/edit-custom-block/kho
git commit -m "fix(TICKET-232): Edit template"

# Rebase develop branch on feature branch
git fetch -u origin develop:develop
git rebase develop

# Push feature branch
git push --force --set-upstream origin fix/TICKET-232/edit-custom-block/main

# Create MR/PR










Git

Init repo where no .git folder exist

git init





Git LFS



Upload/Commit bigger files than 100mb (https://git-lfs.github.com/)

# Download (https://github.com/git-lfs/git-lfs/releases/latest) and install the Git command line extension. Once downloaded and installed, set up Git LFS for your user account by running:
git lfs install

#In each Git repository where you want to use Git LFS, select the file types you'd like Git LFS to manage (or directly edit your .gitattributes). You can configure additional file extensions at anytime.
git lfs track "*.psd"

# Now make sure .gitattributes is tracked:
git add .gitattributes

# Note that defining the file types Git LFS should track will not, by itself, convert any pre-existing files to Git LFS, such as files on other branches or in your prior commit history. To do that, use the git lfs migrate[1] command, which has a range of options designed to suit various potential use cases.

# There is no step three. Just commit and push to GitHub as you normally would; for instance, if your current branch is named main:
git add file.psd
git commit -m "Add design file"
git push origin main



Uninstall from repo

git lfs uninstall






Git

Init repo where no .git folder exist

git init

Command Line Cheat Sheet






Most asked questions



How to checkout on another branch after you do local changes on your current branch?

  • You may get a error that you have to commit or stash your current changes before you can do a checkout. Here are your solutions:
    • Delete old branch where we want to checkout
    • Create commit on the current branch
    • Stash






Definition of “downstream” and “upstream”

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

Forking










change timeout for session password

# if terminal closed it must be typed again
git config --global credential.helper "cache --timeout=3600"
# 0 should be unlimited

disable password verify by using .git-credentials at %HOME%

git config --global credential.helper store






config

Set the name that will be attached to your commits and tags.

git config --global user.name "yourname.."



Set the e-mail address that will be attached to your commits and tags.

git config --global user.email "sample@mail.com"



Enable some colorization of Git output.

git config --global color.ui auto






SSH

  • It is recommended to create multiple ssh keys and and not use 1 for everything
## Default your key will keys will be saved to ~/.ssh/
## Your custom name keys will be stored in current directoy where you executed the command. E.g. ~/samplePubKey.pub
# ssh-keygen -t ecdsa -b 521
ssh-keygen -t ecdsa -b 521 -f /home/tuserNameHere/.ssh/github/id_ecdsa



Next add your public key to your git settings (~/.ssh/id_ecdsa.pub):



Now when you clone your repo via command line you will get asked for passphrase to verify. This will be only done 1 time.



How to use Private Key global

# Method 1 - Edit ~/.ssh/config and enter:
host github.com
 HostName github.com
 IdentityFile /home/tuserNameHere/.ssh/github/id_ecdsa
 User git

How to store passphrase

  • Add your private key. If you have have multiple ssh keys and you e.g. create the new ssh key here /home/tuserNameHere/.ssh/github/id_ecdsa then you have to add it in order to use it on your machine
# Method #1
eval $(ssh-agent -s)
ssh-add /home/tuserNameHere/.ssh/github/id_ecdsa

# Method 2 - Use this command on your private key e.g.
ssh-add /home/tuserNameHere/.ssh/github/id_ecdsa

# Method 3 (Not sure if this will work)
ssh-add

# Method 4 - Add private key to keychain. You must 1 time verify it manually and then it will be saved
ssh-add -K /home/tuserNameHere/.ssh/github/id_ecdsa
reboot






clone

  • Download repo and create folder related to the repo name
git clone https://github.com/CyberT33N/Socket.io-Chat-APP-Example.git

Clone repo with specific branch

git clone -b my-branch git@github.com:user/myproject.git

Clone all repos

  • If you use SSH key for auth instead of the Access Token then you must add your private key to your machine that git clone command will work!
# ---- VARIABLE ----
ACCESS_TOKEN="xxxxxxxxxxxxxxxxxxxxxx"
USERNAME="xxxxxxxxxx"

API_LINK="https://api.github.com/user/repos"
GIT_LINK="git@github.com"

EXPORT_PATH="$HOME/Documents/git_projects"

# ---- cd to current directory ----
cd "$EXPORT_PATH"; pwd
printf "\nWe will display now the current directory used:"; echo "$EXPORT_PATH"
printf "\n\nWe will clone now all your repos!\n\nPlease wait.. This maybe take some time..\n"

# ---- clone all git repos - ACCESS TOKEN ----
# for line in $(curl "$API_LINK?access_token=$ACCESS_TOKEN"  | grep -o "$GIT_LINK:$USERNAME/[^ ,\"]\+");
# do printf "\nCurrent repo link: $line"; git clone $line; done

# ---- clone all git repos - SSH KEY ----
# Notice that we have a limit of 100 items per page. If you want to get more than 100 repos this script must be edited..
for line in $(curl "$API_LINK?access_token=$ACCESS_TOKEN&per_page=100"  | grep -o "$GIT_LINK:$USERNAME/[^ ,\"]\+");
do printf "\nCurrent repo link: $line" &&
  git clone $line &
done
wait


# ---- END AREA ----
printf "\nWe finished the .sh file :) - Created by Dennis Demand( github.com/CyberT33N )\n"






squash

# * df71a27 - (HEAD feature_x) Updated CSS for new elements (4 minutes ago)
# * ba9dd9a - Added new elements to page design (15 minutes ago)
# * f392171 - Added new feature X (1 day ago)
# * d7322aa - (origin/feature_x) Proof of concept for feature X (3 days ago)

git rebase -i HEAD~3

# text editor will open. Pick the commit you want to squash all others to.
pick f392171 Added new feature X
squash ba9dd9a Added new elements to page design
squash df71a27 Updated CSS for new elements

# * f392171 - Added new feature X (1 day ago)








Log



Show logs of last commits

git log

# beautify
git log --all --graph --decorate --oneline



Show all commit hashes/id

# This will be for all branches
git log --pretty=format:"%h"

# This will be for specific branch
git log main..feat/CCS-1114/new-data-structure/main --pretty=format:"%h"

## This will be for specific branch and show more details than only commit hash
git log main..feat/CCS-1114/new-data-structure/main --oneline








  • display state of project (current branch and more..)
  • display changes
git status






add

add all files in folder recursive

  • You should always add each file manually to prevent mistakes. Only use this command when you are 100% sure.
git add .

# add parent folder
git add ..






commit

Commit Message Conventions

feat (feature)
fix (bug fix)
docs (documentation)
style (formatting, missing semi colons, …)
refactor
test (when adding missing tests)
chore (maintain)



commit all changes from all files

git add .
git commit -m "TITLE" -m "DESCRIPTION"



commit specific file

git add app.js
git commit -m "TITLE" -m "DESCRIPTION"



empty commit

git commit -a --allow-empty --allow-empty-message -m ''



overwrite/delete last commit (amend)

git add .
git commit --amend -m "an updated commit message"
git push -f


# Skip commit message dialog by using message from last commit
git add . && git commit --amend --reuse-message HEAD && git push -f






  • origin is an alias on your system for a particular remote repository. It's not actually a property of that repository.
  • Remotes are simply an alias that store the URL of repositories. You can see what URL belongs to each remote by using
git remote -v

As example if you have the same repo on github and gitlab you can switch between your remote repos and origin would be just the name. So instead it could be aswell gitlab oder github






submodule



Remove submodule

# Remove the submodule entry from .git/config
git submodule deinit -f path/to/submodule

# Remove the submodule directory from the superproject's .git/modules directory
rm -rf .git/modules/path/to/submodule

# Remove the entry in .gitmodules and remove the submodule directory located at path/to/submodule
git rm -f path/to/submodule






difference between fetch and pull



Force pull by overwriting local files

git fetch --all

# if you are on the master branch
git reset --hard origin/master

# if other branch
# git reset --hard origin/<branch_name>



Fetch from specific remote repo

git fetch -u origin localbranch:remotebranch

# What is origin?
# https://github.com/CyberT33N/git-cheat-sheet#what-is-origin-httpsstackoverflowcomquestions9529497what-is-origin-in-git

#






pull

  • Download latest version of your repo
git pull



force pull by deleting last local changes

  • Download latest version of your repo
git reset --hard HEAD
git pull






  • Update your repo based on your commits
git push



fatal: You are not currently on a branch. To push the history leading to the current (detached HEAD)

git push origin HEAD:branchname --force



Push to specific remote repo

git push REMOTE_REPO_NAME BRANCH

Push to all remote repos

git remote | xargs -L1 git push --all







Branch



get current Branch

git rev-parse --abbrev-ref HEAD
# git pull origin $(git rev-parse --abbrev-ref HEAD)



Fixing the “GH001: Large files detected. You may want to try Git Large File Storage.”

  • It turned out that GitHub only allows for 100 MB file. The problem is that I can’t simply remove the file because it is tracked inside the previous commits so I have to remove this file completely from my repo. The command that allow you to do it is:
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch fixtures/11_user_answer.json'



Show all branches local and remote

git branch -av



Get default branch

git remote show <remote_name> | awk '/HEAD branch/ {print $NF}'

#REMOTE_DEFAULT_BRANCH=$( git remote show $REMOTE_REPO_NAME | awk '/HEAD branch/ {print $NF}' )
#printf "\nDefault Remote Branch: $REMOTE_DEFAULT_BRANCH \n"



Check all branches

git branch

Check current branch

git branch --show-current



Create branch

git branch branch_name



delete branch

// delete branch locally
git branch -d localBranchName

// delete branch remotely
git push origin --delete remoteBranchName



rename branch

git branch -m "old-branch-name-here" "new-branch-name-here"







Checkout



switch branch

git checkout branch_name



delete local files and switch back to state of remote branch

  • When you locally delete a branch and then checkout again on it you will download the latest files from your remote branch.
git branch -D yourbranch
git checkout yourbranch



Go back to specific commit and reset files

# First clone your project
git clone git://github.com/facebook/facebook-ios-sdk.git

Then checkout by commi SHA. You can find the SHA in your github/gitlab commit.
git checkout xxxxxSHA-HERExxxxx



checkout tag

  • If you want to view the versions of files a tag is pointing to, you can do a git checkout of that tag, although this puts your repository in “detached HEAD” state, which has some ill side effects:
$ git checkout v2.0.0
Note: switching to 'v2.0.0'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 99ada87... Merge pull request #89 from schacon/appendix-final

$ git checkout v2.0-beta-0.1
Previous HEAD position was 99ada87... Merge pull request #89 from schacon/appendix-final
HEAD is now at df3f601... Add atlas.json and cover image










In “detached HEAD” state, if you make changes and then create a commit, the tag will stay the same, but your new commit won’t belong to any branch and will be unreachable, except by the exact commit hash. Thus, if you need to make changes — say you’re fixing a bug on an older version, for instance — you will generally want to create a branch:

$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'







Remote



Push Github repo to Gitalab

git clone your_github_repo

# add remote repo
git remote add gitlab http://gitlab.urlhere/username/projectname.git

## Push repo to gitlab
git push gitlab



Check all current remote links of your project

git remote -v



How to use Github and GitLab on same machine

Pushing to Multiple Git Repos

All in one script example

mkdir ~/Projects
cd ~/Projects
git clone git@github.com:CyberT33N/dev-environment.git
git clone git@github.com:CyberT33N/errormanager.git
git clone git@github.com:CyberT33N/puppeteerservices.git
git clone git@github.com:CyberT33N/errormanager.git

	
# ---- DEV ENVIRONMENT ----
cd ~/Projects/dev-environment

# method 1
git remote add github git@github.com:CyberT33N/dev-environment.git
git remote add bb git@bitbucket.org:CyberT33N/dev-environment.git
git remote add gitlab git@gitlab.com:CyberT33N/dev-environment.git
# dev-environment docker
# git remote add gitlabInternal git@gitlab.local.com:CyberT33N/dev-environment.git
# minikube
git remote add gitlabInternal ssh://git@gitlab.local.com:32022/CyberT33N/dev-environment.git

# Method #2 - Maybe not needed when you sue method #1
# git remote set-url --add --push origin git@github.com:CyberT33N/dev-environment.git
# git remote set-url --add --push origin git@bitbucket.org:CyberT33N/dev-environment.git
# git remote set-url --add --push origin git@gitlab.com:CyberT33N/dev-environment.git
# git remote set-url --add --push gitlabInternal git@gitlab.local.com:CyberT33N/dev-environment.git

If a project has to have multiple git repos (e.g. Bitbucket and Github) then it's better that they remain in sync.

Usually this would involve pushing each branch to each repo in turn, but actually Git allows pushing to multiple repos in one go.

If in doubt about what git is doing when you run these commands, just edit .git/config (git-config(1)_) and see what it's put there.

Remotes

Suppose your git remotes are set up like this::

git remote add github git@github.com:muccg/my-project.git
git remote add bb git@bitbucket.org:ccgmurdoch/my-project.git
git remote add gitlabInternal git@gitlab.local.com:websites/my-project.git

The origin remote probably points to one of these URLs.

Remote Push URLs

To set up the push URLs do this::

git remote set-url --add --push origin git@github.com:muccg/my-project.git
git remote set-url --add --push origin git@bitbucket.org:ccgmurdoch/my-project.git
git remote set-url --add --push gitlabInternal git@gitlab.local.com:websites/my-project.git

It will change the remote.origin.pushurl config entry. Now pushes will send to both of these destinations, rather than the fetch URL.

Check it out by running::

git remote show origin

Then run::

git push github && git push gitlab

Add this to your ~/.gitconfig::

[alias]
    pushall = "!f(){ for i in `git remote`; do git push $i; done; };f"

[alias]
    pushallforce = "!f(){ for i in `git remote`; do git push -f $i; done; };f"

Remove all remote repos

for remote_name in $(git remote); do git remote remove "${remote_name}"; done

Per-branch

A branch can push and pull from separate remotes. This might be useful in rare circumstances such as maintaining a fork with customizations to the upstream repo. If your branch follows github by default::

git branch --set-upstream-to=github next_release

(That command changed branch.next_release.remote.)

Then git allows branches to have multiple branch.<name>.pushRemote entries. You must edit the .git/config file to set them.

Pull Multiple

You can't pull from multiple remotes at once, but you can fetch from all of them::

git fetch --all

Note that fetching won't update your current branch (that's why git-pull exists), so you have to merge -- fast-forward or otherwise.

For example, this will octopus merge the branches if the remotes got out of sync::

git merge github/next_release bb/next_release



Method #2

host github.com
 HostName github.com
 IdentityFile ~/.ssh/id_ecdsa
 User git
 
 # GitLab.com
Host gitlab.com
  Preferredauthentications publickey
  IdentityFile ~/.ssh/id_ecdsa

# Private GitLab instance
Host gitlab.company.com
  Preferredauthentications publickey
  IdentityFile ~/.ssh/id_ecdsa

Add new remote repo

# cd into your project and then run:
git remote add REPO_NAME git@gitlab.com:USERNAME/PROJECTNAME.git






clean



Clean all untracked files that will be ignored by .gitignore

git clean -f -d -x -i -e node_modules






reset

  • --soft will be used by default when you use git reset. Use --soft if you want to keep your changes
  • Use --hard if you don't care about keeping the changes you made



reset last head commit

git checkout <branch-to-modify-head>
git reset --soft HEAD^
git reset --hard HEAD^
git push -f  # force push the last commit to your repo. The deleted commit will be also deleted from your repo



replace last head commit with another commit

git checkout <branch-to-modify-head>
git reset --hard <commit-hash-id-to-put-as-head>
git push -f



Remove specific amount of head commits but keep local changes

# git log um zu checken wie viele der letzten Commits vereint werden sollen. Sonst kann man es auch im MR sehen

# Gehe zum gewünschten Branch
git checkout dein_branch

# Dynamisch die letzten z.b. 4 Commits lokal löschen
# Alternativ kannst du es auch einzeln machen mit git reset --soft HEAD^ was die sichere Variante ist..
git reset --soft HEAD~4

# Sicherstellen, dass die betroffenen Commits oben nicht mehr in der History auftauchen:
git log

# Sicherstellen, dass die Dateien die vorher committed waren da sind
git status

# Die vorher committeten Dateien stagen, zb:
git add .

# sicherstellen, dass die gewollten Dateien gestaged sind:
git status

mkbranch

# force pushen, um die commit history im gitlab mit der lokalen zu überschreiben
git push -f



Reset last merge

# cd into your project and then run:
rm -rf .git/MERGE*



Cancel current merge process

git reset --hard HEAD
git clean -d -f 






  • The git revert command can be considered an 'undo' type command, however, it is not a traditional undo operation. Instead of removing the commit from the project history, it figures out how to invert the changes introduced by the commit and appends a new commit with the resulting inverse content. This prevents Git from losing history, which is important for the integrity of your revision history and for reliable collaboration.

revert specific commit

# use git log to get commit id
git revert id_here

abort revert operation

git revert --abort






rebase

  • does same thing like merge



rebase master branch into feature branch

git checkout feature
git commit -m "any cool changes"

git checkout master
git push

git checkout feaure
git rebase master

git push



  • merge will create a merge commit on the branch where you are merging
  • rebase instead will keep the history of all commits and you can see linear all commits and do not have a merge commit

interactive rebasing

create interactive rebasing

git checkout feature
git rebase -i master

# -i will show all commits and display how your your branch would look like after the rebasing






Remove/Delete



Remove folder and then create commit

git add -A
git commit -m 'deleting directory'
git push origin master






merge

Merge Request

  • You can request merge request via Dashboard of Gitlab. In GitHub it is called pull request but means the same.



Merge Conflict

  • After resolve merge conflict use git commit



Ignore merge conflicts

# cd into your project and then run:
rm -rf .git/MERGE*



merge master branch into feature branch

git checkout feature
git merge master

# or in 1 line
git checkout feature git merge master

# or in short
git merge feature master






  • Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.
git stash



Guide



show all stashes

git stash show



list your stashed changes

git stash list



create new branch from stash

1. git stash
2. git stash list
3. git stash branch my_feature_branch stash@{0}





  • git stash pop throws away the (topmost, by default) stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse (or you can then git stash drop it).



apply most recent stash

git stash apply



apply older stash

git stash apply stash@{n}



apply stash but Throws away the (topmost, by default) stash after applying it. (https://git-scm.com/docs/git-stash#Documentation/git-stash.txt-pop--index-q--quietltstashgt)

git stash pop



go back to latest local state after you did pop/apply

git reset --hard HEAD^





Remove a single stash entry from the list of stash entries.

git stash drop






  • Like most VCSs, Git has the ability to tag specific points in a repository’s history as being important. Typically, people use this functionality to mark release points (v1.0, v2.0 and so on). In this section, you’ll learn how to list existing tags, how to create and delete tags, and what the different types of tags are.



Guides



Listing Your Tags

git tag



search for specific tag name

git tag -l "v1.8.5*"



create Annotated Tag

  • Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too.
# The -m specifies a tagging message, which is stored with the tag. If you don’t specify a message for an annotated tag, Git launches your editor so you can type it in.
git tag -a v1.4 -m "my version 1.4"
git tag
# v1.4



create Lightweight Tag

  • Another way to tag commits is with a lightweight tag. This is basically the commit checksum stored in a file — no other information is kept. To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name:
git tag v1.4-lw
git tag
# v 1.4-lw



delete tag

  • To delete a tag on your local repository, you can use git tag -d . For example, we could remove our lightweight tag above as follows:
git tag -d v1.4-lw
# Deleted tag 'v1.4-lw' (was e7d5add)






  • This only works when you did not use git add! If you use git add then you must revert them before,

restore specific file

git restore sample.html






  • Given one or more existing commits, apply the change each one introduces, recording a new commit for each. This requires your working tree to be clean (no modifications from the HEAD commit).

When it is not obvious how to apply a change, the following happens:


1. The current branch and HEAD pointer stay at the last commit successfully made.


2. The CHERRY_PICK_HEAD ref is set to point at the commit that introduced the change that is difficult to apply.


3. Paths in which the change applied cleanly are updated both in the index file and in your working tree.


4. For conflicting paths, the index file records up to three versions, as described in the "TRUE MERGE" section of git-merge[1]. The working tree files will include a description of the conflict bracketed by the usual conflict markers <<<<<<< and >>>>>>>.


5. No other modifications are made.



Syntax:

git cherry-pick [--edit] [-n] [-m parent-number] [-s] [-x] [--ff]
		  [-S[<keyid>]] <commit>…​
git cherry-pick (--continue | --skip | --abort | --quit)








Delete Files

delete specific file from disk and repo

git rm -f your_file.txt
git push -f

delete folder recursive from disk and repo

git rm -rf --cached .idea









.gitkeep



Keep empty folder but still ignore all files inside

test-db-dumps/test_333/*
!test-db-dumps/test_333/.gitkeep
  • Create .gitkeep file at test-db-dumps/test_333/.gitkeep





.gitignore

  • Ignore files and folders for push
node_modules
test/*
  • You can use relative paths. e.g. your project is abc/hey/test/test.json you can just use hey/test



Create .gitignore file and include node_modules folder

touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status



Remove files that are already commited but the folder is listed in .gitignore

git rm -rf 'lib/main/test/test-db-dumps/test_333'











Helper Scripts

Check if branch exists remote

REMOTE_NAME="origin"

if git ls-remote --heads $REMOTE_NAME $branch | grep -q $branch; then
  echo "Branch $branch exists. Proceeding with git pull."
  git pull $REMOTE_NAME $branch
else
  echo "Branch $branch does not exist on remote. So we do not pull.."
fi

Check if head commit from branch a exists in branch b

if [ "$ENABLE_CUSTOM_PROJECT_PATH" = "true" ]; then
(
    cd $CUSTOM_PROJECT_PATH

    # Pull the latest changes for both branches
    echo "Pulling latest changes for $BRANCH1"
    git pull origin $BRANCH1
    if [ $? -ne 0 ]; then
        echo "Failed to pull $BRANCH1"
        exit 1
    fi

    echo "Pulling latest changes for $BRANCH2"
    git pull origin $BRANCH2
    if [ $? -ne 0 ]; then
        echo "Failed to pull $BRANCH2"
        exit 1
    fi

    # Get the HEAD commit hash of the first branch
    HEAD_COMMIT_BRANCH1=$(git rev-parse origin/$BRANCH1)

    # Check if the HEAD commit of the first branch is present in the second branch
    if git branch -r --contains $HEAD_COMMIT_BRANCH1 | grep -q "origin/$BRANCH2"; then
        echo "The HEAD commit of $BRANCH1 exists in $BRANCH2."
    else
        echo "Error: The HEAD commit of $BRANCH1 does not exist in $BRANCH2. This means that $BRANCH2 is not up-to-date with $BRANCH1. (Check open MR or create MR: $BRANCH1 -> $BRANCH2)"
        exit 1
    fi
)
fi







Gitlab

Import repos from Github



Mirror

Auto Sync via Gitlab UI

Open your GitLab repo and then go to Settings > Repository > Mirroring repositories (https://gitlab.com/USERNAME/PROJECT-NAME/-/settings/repository)

IMPORTANT - Please notice that only public repo mirror is currently free. For mirror of privat repos you must buy premium GitLab.



Mirror Github 2 GitLab

: 'This script will clone all your Github repos and then mirror them to GitLab.
This is usefully when you want to keep your repos sync and dont have GitLab Premium.
You should use this script on your server as cron job.

Currently your GitLab account already must contain all the repos you want to mirror.
You can easily achieve this by using: https://gitlab.com/import/github/status

This script will only work when your master branch (normally called main/master) is not protected by GitLab.
You can manually unprotect your master branch at your repo at:
- Settings > Repository > Protected Branch (https://gitlab.com/USERNAME/REPONAME/-/settings/repository)

Alternative when you host GitLab on your own server you can go to admin settings
and change the default settings for protected branch to not do this manually for every repo.

This script is currently limited to 100 repos cause of the Github API page limit.
'



# ---- VARIABLE ----
ACCESS_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxx"
USERNAME="xxxxxx"

API_LINK="https://api.github.com/user/repos"
GIT_LINK="git@github.com"


EXPORT_PATH="$HOME/Documents/git_projects"

# I guess the github limit is 100 item per page. So if you got more than 100 repos this script is not working
PAGE_LIMIT=100

REMOTE_REPO_NAME="gitlab"
REMOTE_REPO_HOST="git@gitlab.com"
REMOTE_USERNAME="xxxxxxx"








CD(){ cd "$1"; printf "\nCD() - We will display now the current directory used:"; pwd; } # CD(){


fakeCommit(){ printf "\n---- fakeCommit() ----\n"
  # create temp file and add files
  touch .placeholder_mirror
  git add .

  # get default branch name
  REMOTE_DEFAULT_BRANCH=$( git remote show $REMOTE_REPO_NAME | awk '/HEAD branch/ {print $NF}' )
  printf "Default Remote Branch name: $REMOTE_DEFAULT_BRANCH\n"

  # dirty workaround for empty push - create stash, push it and then delete it
  git stash save
  git push -f $REMOTE_REPO_NAME "stash@{0}:$REMOTE_DEFAULT_BRANCH"
  git stash pop

  # remove temp file from repo and disc
  git rm -f .placeholder_mirror
} # fakeCommit(){







getRepoName(){ printf "\n---- getRepoName() ----\n"
  # match repo name - git@github.com:USERNAME/REPONAME.git
  [[ $line =~ ([._a-zA-Z0-9-]+).git$ ]]
  printf "Matched project name: ${BASH_REMATCH[0]}\n"

  # replace .git from project name
  REPONAME=$(echo ${BASH_REMATCH[0]} | sed 's/.git//g')
  #printf "\n Matched project name without .git: $REPONAME";
} # getRepoName(){





repoNotExist(){ printf "\n---- repoNotExist() - Repo name: $REPONAME----\n"; git clone $line; } # repoNotExist(){

repoExist(){ printf "\n---- repoExist() - Repo name: $REPONAME----\n"
  # tempMirror folder already exist because of script crashes etc.. we delete it now
  rm -rf $REPONAME/tempMirror

  # Clone just the repository's .git folder (excluding files as they are already in `existing-dir`) into an empty temporary directory
  git clone --no-checkout $line $REPONAME/tempMirror  # might want --no-hardlinks for cloning local repo

  # check if .git folder exist. If true delete it.
  [ -d $REPONAME/.git ] && rm -rf $REPONAME/.git

  # Move the .git folder to the directory with the files.
  # This makes `existing-dir` a git repo.
  mv $REPONAME/tempMirror/.git $REPONAME

  # Delete the temporary directory
  rm -rf $REPONAME/tempMirror
  cd $REPONAME

  # git thinks all files are deleted, this reverts the state of the repo to HEAD.
  # WARNING: any local changes to the files will be lost.
  git reset --hard HEAD
} # repoExist(){










addRemoteRepo(){ printf "\n---- addRemoteRepo() ----\n"
  # cd into the repo we cloned
  CD $REPONAME

  # add gitlab remote repo
  git remote add $REMOTE_REPO_NAME $REMOTE_REPO_HOST:$REMOTE_USERNAME/$REPONAME.git
} # addRemoteRepo(){



main(){ printf "\n---- main() ----\nCurrent repo link: $line"

  # cd back to the git project main folder and get next Repo Name
  CD $EXPORT_PATH
  getRepoName

  # if repo folder does not exist we clone repo and automatically create the folder
  # if repo folder exist we clone to temp dir and then replace the old repo
  [ -d $REPONAME ] && repoExist || repoNotExist

  # add gitlab remote repo as second remote link
  addRemoteRepo

  # create empty fake commit that will not be in history
  fakeCommit

  # mirror local repo by push to remote repo
  git push -f $REMOTE_REPO_NAME
} # main(){


# ---- get all repos by using the API ----
printf "\n\nWe will clone now all your repos!\n\nPlease wait.. This maybe take some time..\n"
for line in $(curl "$API_LINK?access_token=$ACCESS_TOKEN&per_page=$PAGE_LIMIT" | grep -o "$GIT_LINK:$USERNAME/[^ ,\"]\+")
  do main &
done; wait; printf "\nWe finished the .sh file :) - Created by Dennis Demand( github.com/CyberT33N )\n"






Error



fatal: in unpopulated submodule

git rm --cached foldernamehere -f



You have divergent branches and need to specify how to reconcile them

git pull --ff-only
	
## If you get error fatal: Not possible to fast-forward, aborting
git pull --rebase







Markdown



Tools



Github markdown API

  • Notice that github will sanitize markdown and remove a lot of stuff like the usage of inline style, style elements or script elements
  • The only available size formats you can use are px and %





Custom stlyes in markdown

readme.md

<div align="center">
    <img src="test.svg" width="400" height="400" alt="css-in-readme">
</div>

example.svg

<svg fill="none" viewBox="0 0 800 400" width="800" height="400" xmlns="http://www.w3.org/2000/svg">
	<foreignObject width="100%" height="100%">
		<div xmlns="http://www.w3.org/1999/xhtml">
			<style>
				@keyframes rotate {
					0% {
						transform: rotate(3deg);
					}
					100% {
						transform: rotate(-3deg);
					}
				}

				@keyframes gradientBackground {
					0% {
						background-position: 0% 50%;
					}
					50% {
						background-position: 100% 50%;
					}
					100% {
						background-position: 0% 50%;
					}
				}

				@keyframes fadeIn {
					0% {
						opacity: 0;
					}
					66% {
						opacity: 0;
					}
					100% {
						opacity: 1;
					}
				}

				.container {
					font-family:
						system-ui,
						-apple-system,
						'Segoe UI',
						Roboto,
						Helvetica,
						Arial,
						sans-serif,
						'Apple Color Emoji',
						'Segoe UI Emoji';
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					margin: 0;
					width: 100%;
					height: 400px;
					background: linear-gradient(-45deg, #fc5c7d, #6a82fb, #05dfd7);
					background-size: 600% 400%;
					animation: gradientBackground 10s ease infinite;
					border-radius: 10px;
					color: white;
					text-align: center;
				}

				h1 {
					font-size: 50px;
					line-height: 1.3;
					letter-spacing: 5px;
					text-transform: uppercase;
					text-shadow:
						0 1px 0 #efefef,
						0 2px 0 #efefef,
						0 3px 0 #efefef,
						0 4px 0 #efefef,
						0 12px 5px rgba(0, 0, 0, 0.1);
					animation: rotate ease-in-out 1s infinite alternate;
				}

				p {
					font-size: 20px;
					text-shadow: 0 1px 0 #efefef;
					animation: 5s ease 0s normal forwards 1 fadeIn;
				}
			</style>
			<div class="container">
				<h1>Made with HTML &amp; CSS<br />not an animated GIF</h1>
				<p>Click to see the source</p>
			</div>
		</div>
	</foreignObject>
</svg>





Change font size

  • You can use # or

    like you maybe know but you can also do this. The more sub you use the smaller it gets..

<sub><sup>combining the two tags</sup></sub>





Colabsing menu


Code:

# Header name
<details><summary>Click to expand..</summary>
Some stuff inside here..
</details>

Live:

Click to expand.. Some stuff inside here..






TOC (Table of Contents)

Code:

# Some data.. 
1. [Example](#example)
2. [Example2](#example2)
3. [Third Example](#third-example)
4. [Fourth Example](#fourth-examplehttpwwwfourthexamplecom)


## Example
## Example2
## Third Example


## [Fourth Example](http://www.fourthexample.com) 

Live:

Some data..

  1. Example
  2. Example2
  3. Third Example
  4. Fourth Example

Example

Example2

Third Example






Allowed HTML tags

h1 h2 h3 h4 h5 h6 h7 h8 br b i strong em a pre code img tt div ins del sup sub p ol ul table thead tbody tfoot blockquote dl dt dd kbd q samp var hr ruby rt rp li tr td th s strike summary details











Tables


Code:

|Redis Type|Javascript Type|
|---|---|
|string|String|
|list|Array of String|
|set|Array of String|
|hash|Object(keys have String values)|
|float|String|
|integer|number|

Live:

Redis Type Javascript Type
string String
list Array of String
set Array of String
hash Object(keys have String values)
float String
integer number











Images


Code:

![Test Image 4](https://github.com/tograh/testrepository/3DTest.png)

Live:

Test Image 4











Listing

Code:

- [Root Topic](#root-topic)
  - [1. Overview](#1-overview)
  - [2 Basic components](#2-basic-components)
    - [2.1. Message composer](#21-message-composer)
    - [2.2 Message senders](#22-message-senders)

Live:






FAQ

Git freezing on new line when try to git push

# First remove git
sudo apt-get purge git
sudo apt-get autoremove
sudo apt-get install git

## If you used a passphrase which was stored before you must save it again:
ssh-agent zsh # If you do not use ZSH then make ssh-agent bash
ssh-add