Git Command Prompt Templates
AI prompt templates for Git operations. Understand and execute complex version control tasks.
Overview
Git's power comes with complexity, hundreds of commands with subtle options that can save or destroy your work. These prompts help you handle Git's intricacies, from everyday operations to recovering from mistakes. The key is describing your current state and desired outcome clearly, so you get commands that actually solve your problem.
Best Practices
Describe your current repository state (branch, uncommitted changes, remote status)
Explain what you're trying to achieve in terms of the end result, not just the command you think you need
Mention if you're working with a team or shared repository, some operations rewrite history
Specify if you need to preserve any work-in-progress changes
Include relevant context like CI/CD workflows or branch protection rules
Prompt Templates
1. Git Problem Solver
Help me with this Git situation: **Current state:** - Branch: [CURRENT BRANCH] - Uncommitted changes: [YES/NO - DESCRIBE IF YES] - Recent commits: [RELEVANT RECENT HISTORY] - Remote status: [AHEAD/BEHIND/DIVERGED] **What I'm trying to do:** [DESCRIBE YOUR GOAL] **What I tried (if anything):** [COMMANDS YOU ALREADY ATTEMPTED] **Constraints:** - [e.g. Can't force push to main] - [e.g. Need to preserve uncommitted work] - [e.g. Working with a team] Provide the commands to achieve this, explaining what each does and any risks involved.
Current state: On feature-branch, 5 commits ahead of main, no uncommitted changes Goal: I need to squash my 5 commits into 1 before merging, but one commit in the middle has a merge conflict with main that I already resolved Constraints: PR is open, others might have seen the commits
## Solution: Interactive Rebase with Squash Since you have an open PR that others may have seen, I'll give you two options: ### Option 1: Squash on merge (Safest) If your Git platform supports it, just merge with "Squash and merge" button. No history rewriting needed. ### Option 2: Interactive rebase (Rewrites history) ```bash # First, make sure you have latest main git fetch origin main # Interactive rebase to squash git rebase -i origin/main ``` In the editor that opens: ``` pick abc1234 First commit message squash def5678 Second commit squash ghi9012 Third commit (the one with resolved conflict) squash jkl3456 Fourth commit squash mno7890 Fifth commit ``` Change `pick` to `squash` (or `s`) for all commits except the first. ```bash # After editing commit message, force push git push --force-with-lease origin feature-branch ``` **What `--force-with-lease` does:** Safer than `--force`, it fails if someone else pushed to your branch since you last fetched, preventing you from overwriting their work. **About your resolved merge conflict:** The rebase will replay your commits on top of current main. You might see the conflict again. If so, resolve it the same way, then: ```bash git add <conflicted-files> git rebase --continue ``` ## Risks ⚠️ **History rewriting:** Anyone who pulled your branch will have conflicts. Warn your team before force-pushing. ⚠️ **PR comments:** GitHub/GitLab comments linked to specific commits may become orphaned.
When you're stuck in a Git situation and need to understand both what commands to run and why
- •Always mention if you're working with others, history rewriting commands affect collaborators
- •`--force-with-lease` is almost always safer than `--force`
2. Git Undo Operations
Help me undo a Git operation: **What I did:** [DESCRIBE THE ACTION YOU WANT TO UNDO] **When:** - [JUST NOW / X COMMITS AGO / YESTERDAY] **Current state:** - Committed: [YES/NO] - Pushed: [YES/NO] - Others have pulled: [YES/NO/UNKNOWN] **What I want to recover:** [WHAT STATE YOU WANT TO GET BACK TO] **Important:** [ANY FILES OR CHANGES THAT MUST NOT BE LOST]
What I did: Accidentally committed a.env file with secrets 3 commits ago When: 3 commits ago Current state: Committed and pushed to feature branch, not merged to main Others pulled: Probably not, it's my feature branch Recover: Remove the.env file from history entirely, keep the other changes in those commits
## Removing Sensitive File from Git History ⚠️ **Critical:** Even after removal, the secrets are compromised. Rotate all credentials in that.env file immediately. ### Step 1: Prevent future commits ```bash # Add to.gitignore first echo '.env' >>.gitignore git add.gitignore ``` ### Step 2: Remove from history using filter-repo (recommended) ```bash # Install if needed: pip install git-filter-repo # This rewrites history to remove the file entirely git filter-repo --path.env --invert-paths ``` **Or using BFG Repo-Cleaner (alternative):** ```bash # Download bfg.jar from https://rtyley.github.io/bfg-repo-cleaner/ java -jar bfg.jar --delete-files.env git reflog expire --expire=now --all && git gc --prune=now --aggressive ``` ### Step 3: Force push the cleaned history ```bash # Your remote refs are now out of date git push origin feature-branch --force ``` ### Step 4: Notify anyone who pulled If anyone else has this branch, they need to: ```bash git fetch origin git reset --hard origin/feature-branch ``` ## What happened to the file - **Local working directory:** Still there (untracked now due to.gitignore) - **Git history:** Completely removed from all commits - **Remote:** After force push, removed there too - **Git reflog:** Still visible locally for ~90 days, but not pushed ## Verify removal ```bash # Search history for the filename git log --all --full-history --.env # Should return nothing # Search for content git log -p --all -S 'YOUR_SECRET_VALUE' -- # Should return nothing ```
When you need to undo commits, recover lost work, or remove sensitive data from history
- •The undo approach depends entirely on whether changes are pushed and whether others have pulled
- •For sensitive data, assume it's compromised once pushed, rotate credentials regardless of how quickly you remove it
3. Git Workflow Setup
Help me set up a Git workflow for my team: **Team size:** [NUMBER OF DEVELOPERS] **Project type:** [WEB APP / LIBRARY / MONOREPO / etc.] **Release cadence:** [CONTINUOUS / WEEKLY / VERSIONED RELEASES] **Current pain points:** - [PROBLEM 1 - e.g. merge conflicts] - [PROBLEM 2 - e.g. unclear what's in production] **CI/CD:** [DESCRIBE YOUR PIPELINE IF ANY] **Hosting:** [GITHUB / GITLAB / BITBUCKET / etc.] **Requirements:** - [REQUIREMENT 1 - e.g. code review required] - [REQUIREMENT 2 - e.g. automated testing] Provide: 1. Branch strategy 2. Merge/rebase policy 3. Commit message conventions 4. PR process 5. Recommended branch protection rules
Team: 6 developers Project: SaaS web app Release: Continuous deployment to staging, weekly production releases Pain points: Long-lived branches causing big merge conflicts, unclear what's deployed CI/CD: GitHub Actions Requirements: Code review, tests must pass, need to hotfix production quickly
## Recommended: GitHub Flow + Release Branches ### Branch Strategy ``` main (protected) │ ├── feature/user-auth (short-lived, from main) ├── feature/payment-refactor (short-lived, from main) │ └── release/v2.1 (created weekly for production) └── hotfix/critical-bug (from release, merged back) ``` **Key principle:** Keep branches short-lived (<1 week). Merge to main frequently. ### Branch Purposes | Branch | Purpose | Lifetime | |--------|---------|----------| | `main` | Staging-ready code, always deployable | Permanent | | `feature/*` | New work | 1-5 days | | `release/vX.Y` | Production release candidates | Until next release | | `hotfix/*` | Emergency production fixes | Hours | ### Daily Workflow ```bash # Start new feature git checkout main git pull origin main git checkout -b feature/add-dashboard # Work, commit frequently git add -p # Stage hunks interactively git commit -m "feat(dashboard): add revenue chart component" # Stay up to date (daily) git fetch origin main git rebase origin/main # Push and create PR git push -u origin feature/add-dashboard ``` ### Commit Message Convention (Conventional Commits) ``` <type>(<scope>): <description> [optional body] [optional footer] ``` **Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` **Examples:** - `feat(auth): add OAuth2 Google login` - `fix(payments): handle declined cards gracefully` - `chore(deps): update lodash to 4.17.21` ### PR Process 1. Create PR when ready for review (or draft PR earlier for visibility) 2. Require 1 approval from code owner 3. All CI checks must pass 4. Author merges with "Squash and merge" (clean history) 5. Delete branch after merge ### Branch Protection Rules (GitHub) ```yaml # main branch require_pull_request: required_approving_review_count: 1 dismiss_stale_reviews: true require_status_checks: strict: true # Branch must be up-to-date contexts: - "test" - "lint" - "build" restrict_push: true # No direct pushes # release/* branches require_pull_request: required_approving_review_count: 2 # Extra scrutiny ``` ### Hotfix Process ```bash # Branch from the release in production git checkout release/v2.1 git checkout -b hotfix/fix-payment-crash # Fix, test, PR to release branch # After merge to release, also merge to main git checkout main git merge release/v2.1 ``` ### Addressing Your Pain Points **Long-lived branches → Merge conflicts:** - Mandate: No branch lives >5 days - Break big features into smaller PRs - Rebase onto main daily **Unclear what's deployed:** - Tag every production deployment: `git tag -a v2.1.3 -m "Production 2024-01-15"` - GitHub releases page shows history - Consider: Deploy `main` to staging automatically, `release/*` to production
When setting up a new project, improving team Git practices, or resolving workflow pain points
- •The best workflow is the simplest one that meets your needs, don't over-engineer
- •Short-lived branches are the single most effective way to reduce merge conflicts
4. Git Command Explainer
Explain this Git command: ```bash [PASTE COMMAND] ``` **Context:** [WHERE YOU SAW IT OR WHY YOU'RE ASKING] Explain: 1. What each part of the command does 2. When you would use this 3. Any risks or side effects 4. Common variations 5. Safer alternatives if applicable
Command: git reset --hard HEAD~3 Context: Someone suggested this to undo my last few commits but I want to understand it first
## Command Breakdown ```bash git reset --hard HEAD~3 ``` | Part | Meaning | |------|---------| | `git reset` | Move the current branch pointer to a different commit | | `--hard` | Also reset the staging area AND working directory to match | | `HEAD~3` | The commit 3 steps before the current HEAD | ## What This Does 1. Moves your branch pointer back 3 commits 2. **Deletes** all changes in those 3 commits from your working directory 3. Clears the staging area **Your 3 most recent commits will appear to vanish** (they're still in reflog temporarily). ## Visual ``` Before: A -- B -- C -- D -- E (HEAD, main) ↑ you are here After: A -- B -- C (HEAD, main) ↑ now here, D and E are "gone" ``` ## When to Use ✅ **Appropriate:** - You made commits locally that you want to completely discard - You haven't pushed these commits - You don't want to keep any of the changes ❌ **Dangerous if:** - You've already pushed (would require force push) - Others have pulled your commits (their repos will diverge) - You want to keep the changes but undo the commits ## Safer Alternatives **Keep changes, just undo commits:** ```bash git reset --soft HEAD~3 # Changes stay staged git reset HEAD~3 # Changes stay in working directory (unstaged) ``` **Create new commit that undoes changes (safe for pushed commits):** ```bash git revert HEAD~2..HEAD # Creates 3 new commits that undo the changes ``` **If you're unsure, stash first:** ```bash git stash # Save current work git reset --hard HEAD~3 # Do the reset git stash pop # Get work back if needed ``` ## Recovery If you run this and regret it: ```bash git reflog # Find the commit hash before reset git reset --hard abc123 # Go back to that commit ``` Reflog keeps commits for ~90 days, so recovery is usually possible.
When you encounter an unfamiliar Git command and want to understand it before running it
- •Never run a Git command you don't understand, especially ones with --hard or --force
- •When in doubt, make a backup branch first: `git branch backup-just-in-case`
Common Mistakes to Avoid
Not mentioning whether commits have been pushed, the undo strategy is completely different
Running suggested commands without understanding them, especially dangerous with reset --hard or force push
Forgetting to mention uncommitted changes that could be lost
Frequently Asked Questions
Git's power comes with complexity, hundreds of commands with subtle options that can save or destroy your work. These prompts help you handle Git's intricacies, from everyday operations to recovering from mistakes. The key is describing your current state and desired outcome clearly, so you get commands that actually solve your problem.
Related Templates
Code Review Prompt Templates
AI prompt templates for thorough code reviews. Get comprehensive feedback on code quality, security, and best practices.
Debugging Prompt Templates
AI prompt templates for debugging code. Identify issues, understand errors, and find solutions faster.
Code Documentation Prompt Templates
AI prompt templates for writing code documentation. Create clear comments, READMEs, and API docs.
Have your own prompt to optimize?