Files
Advanced-Git/README.md
JESVIN 29502bba8a added worktree.md (#9)
* added worktree.md

* fixed quatation issue

---------

Co-authored-by: Anonymous-025 <unknownjesvin>
2025-03-11 15:36:31 -05:00

17 KiB
Raw Blame History

Advanced Git Commands

Important

If you find a useful GIT command - be sure to sent a PR here as well :)

Table of Contents

Latest

📌 git push --force-with-lease

git push --force-with-lease ensures you dont accidentally overwrite someone elses work when force-pushing. It checks if the remote branch still matches what you last pulled. If someone else has pushed changes in the meantime, your push is rejected, preventing unintended data loss.

🔹 Problem

When users are within the same branch and they want to push to remote but not sure if there is a commit pushed from the other dev that might block you

🔹 Solution

use the ---force with lease flag while pushing to check it there is a push. If there is a push from the other person - your push to the same branch is cancelled.

Tutorial

Checkout Tutorial Here

📌 Git Worktree Tutorial

🔹 Problem

Switching branches is Time consuming ,your IDE will run mad trying to adapt the project settings and constant reconfiguration.

🔹 Solution

With worktree, you can avoid that constant reconfiguration

Tutorial

Git Submodules

How to Use Git Submodules by Setting Up a New Submodule Repository and Pushing to It This guide walks you through:

  • Creating a new Git submodule repository
  • Adding it as a submodule in another repository
  • Pushing files from the main repository to the submodule

Step 1: Create the Git Submodule Repository

We need to create a new repository that will act as the submodule.

1. Initialize the Submodule Repository

mkdir my-submodule
cd my-submodule
git init --bare

This sets up an empty bare repository, meaning it will only store Git data and be used as a remote.

2. Host it on GitHub (or any remote)

  • Go to GitHub (or GitLab/Bitbucket).
  • Create a new repository named my-submodule.
  • Copy the remote URL (e.g., git@github.com:your-user/my-submodule.git).

3. Push the Bare Repo to Remote

git remote add origin git@github.com:your-user/my-submodule.git
git push --set-upstream origin main

Step 2: Add the Submodule to Another Repo

Now, lets integrate this submodule into a main repository.

1. Initialize and Clone the Main Repository

mkdir main-repo
cd main-repo
git init

2. Add the Submodule

git submodule add git@github.com:your-user/my-submodule.git submodules/my-submodule

This clones the submodule into the submodules/my-submodule directory inside the main repo.

3. Commit and Push

git add .gitmodules submodules/my-submodule
git commit -m "Added submodule my-submodule"
git push origin main

Step 3: Add Files and Push to the Submodule

Now, lets add files to the submodule from the main repo.

1. Navigate into the Submodule

cd submodules/my-submodule

2. Add Files to the Submodule

echo "Hello from the submodule!" > file.txt
git add file.txt
git commit -m "Added file to submodule"

3. Push the Changes to the Submodule Repository

git push origin main

Step 4: Commit the Updated Submodule in the Main Repo

Once the submodule has new changes, the main repository needs to recognize it.

1. Move Back to Main Repo

cd ../..

2. Stage and Commit the Submodule Update

git add submodules/my-submodule
git commit -m "Updated submodule to latest commit"
git push origin main

Step 5: Cloning and Initializing Submodules

If you or someone else clones the main repo, you need to initialize the submodules:

git clone --recursive git@github.com:your-user/main-repo.git

or, if already cloned:

git submodule update --init --recursive

Summary

  • Created a Git submodule repository
  • Added it as a submodule to another repo
  • Pushed files from the main repo into the submodule
  • Updated the submodule reference in the main repo

Difference Between git submodule update --remote --merge and git submodule update --init --recursive

Both commands update submodules, but they work differently.

1 git submodule update --remote --merge

git submodule update --remote --merge

📌 What It Does:

  • Pulls the latest commit from the remote branch of the submodule.
  • Merges that commit into your local submodule.
  • Updates the submodule folder to match the latest remote version.

🛠 When to Use It

  • When you want to fetch the latest changes from the submodules remote repo.
  • Useful if the submodule is actively being updated and you want to sync with the latest version.

🚀 Example

  • Your submodule (whk-script-library) is behind the remote repository.
  • Running git submodule update --remote --merge fetches and merges the latest changes.
  • The submodule now tracks the latest remote commit.

2 git submodule update --init --recursive

git submodule update --init --recursive

📌 What It Does:

  • Ensures that all submodules are initialized (--init).
  • Updates submodules to the exact commit referenced in the main repository.
  • Recursively initializes nested submodules (--recursive).

🛠 When to Use It

  • When you just cloned the main repository and need to fetch and initialize submodules.
  • Ensures that all submodules match the commit stored in the main repo (even if they are outdated).
  • Best for setting up a project that includes submodules.

🚀 Example

  • You cloned whk-wms, but the whk-script-library submodule is empty.
  • Running git submodule update --init --recursive initializes and updates it to the expected commit.
  • The submodule now matches the commit tracked in the main repo, not necessarily the latest commit from the remote.

Delete Untracked Files and Folders

To delete untracked files and folders, use the following methods:

Git provides git clean to safely remove untracked files and directories.

1 Dry Run (Check What Will Be Deleted)

First, run this to see what will be deleted:

git clean -n -d

2 Delete Untracked Files and Folders

If everything looks correct, run:

git clean -f -d

What this does: -f → Forces deletion of untracked files. -d → Deletes untracked directories (like data-loader/).

Repository Management

  • git init --bare: Initialize a bare repository, typically used for remote repositories.
  • git clone --mirror <repository>: Clone a repository in mirror mode, including all refs and branches.

Branching and Merging

  • git branch -m <old-branch> <new-branch>: Rename a branch.
  • git branch -d <branch>: Delete a branch that has been merged.
  • git branch -D <branch>: Force delete a branch that hasnt been merged.
  • git checkout -b <new-branch>: Create and switch to a new branch.
  • git cherry-pick <commit>: Apply the changes from a specific commit onto the current branch.
  • git rebase <branch>: Reapply commits on top of another base tip.
  • git merge --squash <branch>: Merge a branch, combining all commits into one.
  • git merge --no-ff <branch>: Merge with a merge commit even if fast-forward is possible.
  • git stash branch <branch>: Create a new branch and apply the stashed changes.

History and Inspection

  • git log --graph --oneline --decorate --all: Visualize the commit history in a graphical format.
  • git log -p: Show patches (differences) introduced in each commit.
  • git show <commit>: Show various types of objects (e.g., commits, tags, trees).
  • git reflog: Show the history of changes to the repositorys refs.
  • git diff <commit1> <commit2>: Show changes between two commits.
  • git blame <file>: Show what revision and author last modified each line of a file.
  • git bisect start: Begin a binary search to find the commit that introduced a bug.
  • git bisect bad <commit>: Mark a commit as bad in the bisect process.
  • git bisect good <commit>: Mark a commit as good in the bisect process.

Stashing and Cleaning

  • git stash save "description": Save changes to the stash with a description.
  • git stash pop: Apply the last stashed changes and remove them from the stash.
  • git stash apply stash@{n}: Apply a specific stash.
  • git stash list: List all stashes.
  • git stash drop stash@{n}: Remove a specific stash.
  • git clean -fd: Remove untracked files and directories.
  • git clean -n: Show what would be removed by git clean.

Submodules

  • git submodule add <repository> <path>: Add a submodule.
  • git submodule init: Initialize the submodules.
  • git submodule update: Update the submodules to the latest commit.
  • git submodule foreach <command>: Run a command in each submodule.
  • git submodule sync: Synchronize the submodule URLs.

Advanced Configuration

  • git config --global alias.<alias-name> '<git-command>': Create a Git command alias.
  • git config --global core.editor "<editor>": Set the default text editor for Git.
  • git config --global user.name "<name>": Set the user name for Git commits.
  • git config --global user.email "<email>": Set the user email for Git commits.
  • git config --global --edit: Edit the global configuration file.

Rewriting History

  • git commit --amend: Modify the most recent commit.
  • git rebase -i <base>: Start an interactive rebase session.
  • git filter-branch --tree-filter <command> -- --all: Rewrite branches to modify the working tree.
  • git reset --soft <commit>: Move the HEAD to a commit, staging all changes.
  • git reset --hard <commit>: Move the HEAD to a commit, discarding all changes.
  • git revert <commit>: Create a new commit that undoes the changes from a previous commit.

Collaboration and Review

  • git remote add <name> <url>: Add a new remote repository.
  • git fetch <remote>: Download objects and refs from another repository.
  • git pull --rebase <remote> <branch>: Fetch the branch and rebase onto the current branch.
  • git push <remote> <branch>: Push changes to a remote repository.
  • git push --force-with-lease <remote> <branch>: Force push with a safety check to ensure youre not overwriting someone elses work.
  • git push --tags: Push all tags to the remote repository.
  • git request-pull <start> <url> <end>: Generate a request to pull changes into a repository.

🛠 View and Clean Up Local Git Branches

🐧 Bash

List Local Branches Without a Remote Connection. git branch -vv | grep -E '^\s*\S+\s+[^\[]+$'
Automatically Delete Local Branches Without Remote Tracking.

git branch -vv | grep -E '^\s*\S+\s+[^\[]+$' | awk '{print $1}' | xargs git branch -D

View Local Branches That Had Their Remote Deleted (Ex: PR Merged & Deleted in remote but still exist in local).**

git branch -vv | grep ': gone]'

Delete Stale Local Branches That Had Their Remote Deleted.

git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D

🖥 PowerShell

List Local Branches Without a Remote Connection.

git branch -vv | Select-String -NotMatch "origin/"

Automatically Delete Local Branches Without Remote Tracking

git branch -vv | Select-String -NotMatch "origin/" | ForEach-Object {
   $branch = ($_ -split "\s+")[1]
   git branch -D $branch
}

View Local Branches That Had Their Remote Deleted (Ex: PR Merged & Deleted in remote but still exist in local).**

git branch -vv | Select-String ": gone\]"

Delete Stale Local Branches That Had Their Remote Deleted.**

git fetch -p && git branch -vv | Select-String ': gone]' | ForEach-Object { $_.ToString().Trim().Split()[0] } | ForEach-Object { git branch -D $_ }

Miscellaneous

  • git archive --format=zip --output=<file.zip> <tree-ish>: Create an archive of files from a named tree.
  • git shortlog -sn: Summarize commit activity by author.
  • git gc: Cleanup unnecessary files and optimize the local repository.
  • git fsck: Verify the connectivity and validity of objects in the database.
  • git worktree add <path> <branch>: Create a new working tree linked to a branch.
  • git bundle create <file> <revision>: Create a bundle file from specified revisions.
  • git bundle verify <file>: Verify the integrity of a bundle file.
  • git bundle unbundle <file>: Extract a bundle into a repository.
  • git rm --cached -r <file/folder>: Removes Git tracking without deleting files from local machine which prevents Git from tracking future changes if its added to .gitignore.(Ex: most useful for deleting .env when you accidentally push it to remote)

Contributors & Credits

Note

Add yourself, your links you have used, or even your blogs if you have some or is an author

👨‍👩‍👧‍👦 Contributors

A list of individuals who have contributed to this project.

👨‍👩‍👧‍👦 View Contributors

🧑‍💻 Credits & Authors

Acknowledgment of the original authors.

🧑‍💻 View Credits & Authors

📖 References & Resources

A collection of blogs, articles, and materials used to learn more about Git.

📖 View References & Resources