Git Notes

Git commands which I tend to look up from time to time

Add a commit to previous commit

When you need to add a little edit to your previous commit

git commit --amend

# If you don't want to edit commit message

git commit --amend --no-edit

Change git history using rebase

# Using rebase HEAD~5 for upto 5 commits

git rebase -i HEAD~5

Git push force with lease

When you change the git history like edited the commit message or squashed some commits, then git will reject your push attempt because there is a conflict between these two. To push it you need to use a flag --force-with-lease

git push -u origin main --force-with-lease

# If above fails then use --force (not recommended)

git push -u origin main --force

Git subtree

Git subtree can be a better alternative to submodules. Its basically a method to use a different git repo inside an already active repository.

Reference article

These are steps to use the subtree in your project

  • Step 1 Add a different git repo (Which you want to use inside you repository) as remote
# add remote

git remote add -f remote_name git_remote_url
  • Step 2 Create a subtree and define the folder path, where it should fetch those files.

    Note if you are giving any folder path, the folder shouldn’t be present at that time otherwise git will error out saying folder already exists.

# add subtree --squash to squash all the remote commits into one. otherwise it'll pollute your main repository history

git subtree add --prefix subtree_directory remote_name remote_branch --squash
  • For updating the subtree files to the latest commit from the remote.
# update the subtree to a later commit

git subtree pull --prefix subtree_directory remote_name remote_branch --squash
  • If you want to push any commits to the subtree git repository
# Pushing the commit to subtree repo

git subtree push --prefix subtree_directory remote_name remote_branch