Wednesday, September 18, 2024

Common Git Commands

 

# initialize local Git repository

git init

# create the main branch

git checkout -b main

# add local file (eg README.md) to staging

git add README.md

# commit the staging changes with comments (eg first commit)

git commit -m "first commit"

# add a remote repository (Git HTTPS or SSH URL: git@git.abc.com:company-name/Temp_Test_Repo.git)

git remote add origin git@git.abc.com:company-name/Temp_Test_Repo.git

# push the staging changes to the (remote) repository

git push origin main


# create the new branch (eg FY23-01) from main

git checkout -b FY23-01 main

# push the latest changes from the branch (eg FY23-01)

git push origin FY23-01


# revert local commits - for SHA, only need first 5 or 6 characters to differentiate

git revert <new commit SHA>

# undo the above revert

git revert <commit SHA of the previous revert>

# or, make a copy of the original commit

git cherry-pick <original commit SHA>

# check untracked files

git diff

# check local git status for uncommitted files etc

git status

# check git history

git log

# check git history by range

git log --online <start commit SHA>..<end commit SHA>

# cherry-pick multiple commits
git cherry-pick <start commit SHA>..<end commit SHA>


# delete a new local branch (eg FY23-01) in case of recreating
git branch -D FY23-01

# delete a remote branch
git push origin --delete FY23-01


# merge branch FY23-01 back to main

# switch to the target branch (eg main)

git switch main # or git checkout main

# merge from the source branch (eg FY23-01) without fast-forward

git merge --no-ff FY23-01

# push the merged changes back to the target branch (eg main) of the (remote) repository

git push origin main


# rebase from main to the branch created before some updates in main - merged from another branch - later

git switch main

git pull origin main

git switch out-of-date-branch

git rebase main


# temporary record the current state of local directory and the index for going to a clean work directory - matching to HEAD
git stash or git stash push
git stash list
# invert stash push and remove a stash state and put it on top of the current working tree state
git stash pop

# Cherry-pick
# update with the latest source and export the logs
git switch <source branch>
git fetch
git pull
git log --pretty=oneline > c:/Temp/main_log.txt
# review and modify the logs and remove the unnecessary ones

# go to the target branch and update to the latest
git switch <target branch>
git fetch
git pull

git cherry-pick <original commit SHA from source logs>
# if conflicts found, manually review and fix - by keeping the correct and removing the old/incorrect
git add <updated files>
# if not picked (same as or up-to-date with HEAD/target), git cherry-pick --skip 
# if picked, git cherry-pick --continue, update comments and save
git push

No comments:

Post a Comment