
Git Rebase
- 1 installs
- 95 repo stars
- Updated June 28, 2026
- pedronauck/kodebase-go
Handles git rebase and merge-conflict resolution using a squash-first strategy with safety backups and force-with-lease pushes.
About
Runs a structured rebase workflow that backs up state, squashes to resolve conflicts once, validates the merge, and pushes safely. A developer uses it when rebasing feature branches onto main and resolving conflicts.
- Squash-first strategy resolves conflicts once
- Safety backup before rebase, force-with-lease push
Git Rebase by the numbers
- 1 all-time installs (skills.sh)
- Ranked #527 of 733 Git & Pull Requests skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/pedronauck/kodebase-go --skill git-rebaseAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 95 |
| Last updated | June 28, 2026 |
| Repository | pedronauck/kodebase-go ↗ |
What it does
Handles git rebase and merge-conflict resolution using a squash-first strategy with safety backups and force-with-lease pushes.
Files
Git Rebase with Intelligent Conflict Resolution
Quick Start
For most rebases with multiple commits, use the squash-first strategy to resolve conflicts only once:
# Step 1: Backup current state
bash scripts/pre-rebase-backup.sh
# Step 2: Squash commits (interactive rebase on current branch)
git rebase -i $(git merge-base HEAD origin/main)
# Step 3: Rebase onto target
git rebase origin/main
# Step 4: If conflicts, resolve them once (see workflow below)
# Then continue: git rebase --continue
# Step 5: Force push safely
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-leaseThis approach resolves conflicts once instead of per-commit, saving time and mental overhead.
Core Workflow: Conflict Analysis & Resolution
Copy this checklist and mark progress:
Rebase Workflow:
- [ ] Step 1: Create safety backup
- [ ] Step 2: Fetch latest from target branch
- [ ] Step 3: Analyze conflict scope
- [ ] Step 4: Choose resolution strategy
- [ ] Step 5: Apply conflict resolutions
- [ ] Step 6: Validate merged code
- [ ] Step 7: Run tests
- [ ] Step 8: Force push safelyStep 1: Create Safety Backup
ALWAYS do this first. If rebase goes wrong, you can recover:
# Use the bundled script
bash scripts/pre-rebase-backup.sh
# Or manually create timestamped backup branch
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
git branch backup-rebase-$TIMESTAMP
# Alternative: Create temporary ref to your current commit
git reflog # Note your current HEAD SHA for manual recoveryThis costs nothing and saves hours of work if something goes wrong.
Step 2: Fetch Latest Changes
Ensure you have the most recent remote state:
# Fetch without modifying local branches
git fetch origin
# View the divergence
git log --oneline origin/main..HEAD # Your commits
git log --oneline HEAD..origin/main # New commits on mainUnderstand how many commits you're rebasing and how much main has changed.
Step 3: Analyze Conflict Scope
Before starting the rebase, predict conflicts:
# See which files you changed
git diff --name-only origin/main...HEAD
# See which files main changed
git diff --name-only origin/main HEAD
# Likely conflict areas: files changed in bothKey insight: If you changed auth.ts and so did main, you WILL get conflicts in auth.ts.
Anticipating conflicts helps you understand how to resolve them.
Step 4: Choose Resolution Strategy
For detailed strategy comparison and decision matrix, see references/strategies.md.
Strategy A: Squash First (Recommended for 3+ commits)
When to use: Multiple feature commits with many conflicts expected
Why: Reduces conflicts to one resolution phase instead of per-commit
# Interactive rebase on current branch first
git rebase -i $(git merge-base HEAD origin/main)
# In editor, change all "pick" to "squash" (or 's') except first commit
# Save and exit - commits are squashed into one
# Edit commit message to describe the entire feature
# Now rebase the squashed commit
git rebase origin/main
# Resolve conflicts once, then git rebase --continueTradeoffs: Lose individual commit history, but simpler conflict resolution
Strategy B: Interactive Rebase with Conflict Awareness
When to use: 1-2 commits, clean history, or complex per-commit logic
git rebase -i origin/main
# In editor, you can:
# - Reorder commits to isolate conflict-prone ones
# - Drop commits that are already in main (git detects this)
# - Combine related commits before rebasing
# Save and exit - rebase proceeds, stopping at conflictsTradeoffs: More control, but more conflict-resolution iterations
Strategy C: Simple Linear Rebase (Fastest, Auto-Resolution)
When to use: Simple cases, no critical decisions, or in automated pipelines
# Rebase all commits at once
git rebase origin/main
# If no conflicts, done
# If conflicts, you resolve each oneWarning: Not recommended for complex scenarios. Use Strategies A or B instead.
Step 5: Apply Conflict Resolutions
When git rebase pauses with conflicts, use the analysis script:
# Analyze conflicts
bash scripts/analyze-conflicts.sh
# See which files conflict
git status
# For each conflicted file:
# - RECOMMENDED: Use merge tool for visual clarity
git mergetool --no-prompt
# - ALTERNATIVE: Manual edit in your editor
# Search for conflict markers: <<<<<<, ======, >>>>>>Conflict Marker Anatomy
<<<<<<< HEAD
// Your current feature code
function authenticate(token) {
validateToken(token);
return true;
}
=======
// Main branch code (incoming)
function authenticate(token) {
if (!token) throw new Error("No token");
validateToken(token);
setSession(token);
return true;
}
>>>>>>> origin/mainDecision framework (before deleting markers):
1. Can you keep both? YES → Merge them intelligently
function authenticate(token) {
if (!token) throw new Error("No token"); // Keep main's validation
validateToken(token);
setSession(token); // Keep main's session setup
return true; // Keep feature's return
}2. Conflicting logic? Understand WHY they differ, then decide
- Did main add critical security checks? → Keep main's version
- Did your feature add essential functionality? → Keep feature's version
- Are they trying to do different things? → Combine intentionally
3. Lost features? NEVER let a feature silently disappear
- If you added authentication logic, ensure it's in final version
- If main improved database access, ensure that's preserved
For detailed resolution patterns, see references/resolution-patterns.md.
Key Resolution Principles
✅ DO:
- Keep both versions' important functionality when possible
- Use the merge tool for visual representation
- Add comments explaining merged conflicts:
// Merged from both versions: main's validation + feature's session setup - Test each file after resolution
❌ DON'T:
- Mindlessly pick one version without understanding both
- Delete conflict markers without understanding the conflict
- Keep duplicate code - merge intelligently
- Skip testing before continuing
Step 6: Validate Merged Code
After resolving conflicts, validate the merged code:
# Use the validation script
bash scripts/validate-merge.sh
# Manual checks:
# 1. Check syntax
npm run lint # or eslint, pylint, etc.
# 2. Check types (if TypeScript)
npm run type-check # or tsc --noEmit
# 3. Spot-check key files
git diff HEAD origin/main -- <conflicted-file>
# If validation fails:
# 1. Fix the issue in the file
# 2. git add <file>
# 3. git rebase --continueImportant: Validation catches mistakes BEFORE you commit them.
Step 7: Run Tests
This is your safety net:
# Run full test suite
npm test
# Or specific tests for changed areas
npm test -- --testPathPattern=auth # If auth.ts was changed
# If tests fail:
# 1. Understand what broke
# 2. Fix in the files
# 3. git add <files>
# 4. git rebase --continueRule: Never force-push code that fails tests.
Step 8: Force Push Safely
Use --force-with-lease instead of --force. It protects against accidentally overwriting others' work:
# SAFE: Protects others' commits
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-lease
# UNSAFE: Can overwrite others' work
git push origin your-branch -f # Don't do this
# If force-with-lease fails:
# Someone else pushed to your branch
# Coordinate with them before forcingCommon Scenarios & Strategies
Scenario 1: Many Small Conflicts Across 5+ Commits
Use: Squash-first strategy
git rebase -i $(git merge-base HEAD origin/main)
# Mark all but first commit as 's' (squash)
# Save - commits squash into one
git rebase origin/main
# Resolve conflicts once
git rebase --continue
# Only one conflict-resolution phase!Why: Each commit might have conflicts. Squashing before rebasing means one pass.
Scenario 2: One Specific Commit Has Conflicts
Use: Target that commit with interactive rebase
git rebase -i origin/main
# In editor, move the problematic commit to the end
# Save - rebase proceeds, stopping at that commit
# When it stops, you know exactly which commit conflicts
git status # See what changed in this commit
# Resolve, then continue
git rebase --continueWhy: Isolating the commit helps you understand what it's trying to do.
Scenario 3: Conflicts Keep Repeating (Same File, Different Commits)
Use: Git rerere (reuse recorded resolution)
# Enable rerere globally (one-time setup)
git config --global rerere.enabled true
# Now when you hit the same conflict in a second commit,
# Git automatically applies the first commit's resolution
git rebase origin/main
# Git remembers your first conflict resolution
# and replays it automatically for similar conflictsWhy: When rebasing and hitting the same file repeatedly, rerere saves manual work.
Scenario 4: Rebase Conflicts Are Too Complex
Emergency escape plan:
# Abort the rebase - return to original state
git rebase --abort
# Fall back to merge (safer for complex scenarios)
git merge origin/main
# Or try a different approach:
# - Squash your entire feature branch first
# - Cherry-pick main's critical changes selectivelyImportant: It's okay to abort and rethink. Better than a broken rebase.
Bundled Scripts
This skill includes helper scripts in scripts/:
- `pre-rebase-backup.sh`: Creates a safety backup before rebasing
- `analyze-conflicts.sh`: Analyzes current conflicts and provides detailed information
- `validate-merge.sh`: Validates that merge/rebase is clean and ready for testing
Run scripts with bash scripts/<script-name>.sh.
Reference Files
For detailed information on specific topics:
- Strategies: references/strategies.md - Complete strategy comparison and decision matrix
- Resolution Patterns: references/resolution-patterns.md - Common conflict resolution patterns and heuristics
- Troubleshooting: references/troubleshooting.md - Solutions to common rebase problems
- Automation: references/automation.md - Automated conflict resolution for CI/CD
- Scripts & Tools: references/scripts-tools.md - Additional git commands and tool usage
Checklist: Before You Commit to Rebasing
- [ ] Understand why you're rebasing (cleaner history, syncing with main, etc.)
- [ ] Backup your current branch:
bash scripts/pre-rebase-backup.sh - [ ] Run tests on current branch - they should pass
- [ ] Fetch latest:
git fetch origin - [ ] Understand what you'll be rebasing (5 commits? 50?)
- [ ] Understand main's recent changes (1 commit? Major refactor?)
- [ ] Choose your strategy (see references/strategies.md)
- [ ] Have your merge tool ready (if using GUI)
- [ ] Block 30 mins - don't rush conflict resolution
- [ ] Have tests ready to run after rebase
When NOT to Rebase
- Shared branches (use merge instead:
git merge origin/main) - Critical production code without comprehensive tests
- When multiple people are pushing to the same branch
- If you don't understand the conflicts you're seeing
Default to merge if uncertain. Merge is safer for collaborative work.
Use rebase when: Solo feature branch, clean history matters, no shared dependencies.
Summary: The Rebase Philosophy
Rebasing is a tool for creating clean, linear commit history. Used well, it makes debugging and code review easier. Used poorly, it loses work.
The key principle: Understand every conflict before resolving it. Don't automate away the thinking.
With this Skill, you can rebase with confidence, understanding each decision and protecting your code throughout the process.
Advanced: Automated Conflict Resolution
When You KNOW the Resolution Strategy Upfront
For CI/CD pipelines or automated rebases:
# Accept ALL incoming changes (risky - verify first!)
git rebase -X theirs origin/main
# Accept ALL your changes (also risky!)
git rebase -X ours origin/main
# Three-way recursive merge (safest auto-strategy)
git rebase -Xrecursive origin/main⚠️ WARNING: Only use automated strategies when:
1. You understand the consequences 2. You have comprehensive tests 3. Changes are non-critical 4. You've verified the strategy is correct for this scenario
For production code: Use manual resolution from the core workflow in SKILL.md.
Resolution Patterns & Heuristics
Pattern 1: Main Added New Validation/Security
Indicator: Main's version has if checks or validations you don't have
Action: Keep main's validation, integrate with your feature
// WRONG: Removing main's validation
function authenticate(token) {
validateToken(token); // Lost: if (!token) check
return true;
}
// RIGHT: Keeping all validations
function authenticate(token) {
if (!token) throw new Error("No token"); // main's addition
validateToken(token); // your code
return true;
}Pattern 2: Your Feature Added Critical Functionality
Indicator: Main's version doesn't have your key feature additions
Action: Ensure your additions are preserved
// Before conflict
export class AuthService {
validate() {}
// Your addition
setUserContext(user) {}
}
// After resolving (keep your addition)
export class AuthService {
validate() {} // main's version
setUserContext(user) {} // your addition (don't lose this!)
}Pattern 3: Both Changed Same Line (Logic Conflict)
Indicator: Same line different in both versions
Action: Understand why, choose based on correctness
// YOU: Changed return value
return new User(profile);
// MAIN: Changed return statement entirely
return User.fromProfile(profile);
// DECISION: What's the actual implementation?
// Check User class for which method exists
// Pick the one that matches current APIPattern 4: Main Deleted Code You Still Need
Indicator: Code block exists in your branch, missing in main
Action: Keep your code - main might have deleted prematurely
// Main deleted some logging
// You kept it in your feature
// DECISION: If logging is useful, keep it
// If it was debug code, you can delete it too
// Usually: Keep your feature code + main's latestScripts & Tools Reference
bash: Analyze Current Conflicts
# See all conflicts at a glance
git diff --name-only --diff-filter=U
# Count conflicts
git diff --name-only --diff-filter=U | wc -l
# Show conflicts with context
git status | grep 'both modified'bash: Verify No Conflict Markers Remain
# Check for leftover conflict markers
git grep -l '<<<<<<'
# If any files show up, you missed editing them
git add <missing-file>
git rebase --continuebash: Compare Your vs Incoming Changes
# See only YOUR changes in this conflict
git show :1:<filename> # Base version
git show :2:<filename> # Your version
git show :3:<filename> # Their version
# Compare two versions:
git show :2:<filename> > yours.txt
git show :3:<filename> > theirs.txt
diff yours.txt theirs.txtUsing Bundled Scripts
This skill includes helper scripts in scripts/:
- `pre-rebase-backup.sh`: Creates a safety backup before rebasing
- `analyze-conflicts.sh`: Analyzes current conflicts and provides detailed information
- `validate-merge.sh`: Validates that merge/rebase is clean and ready for testing
See SKILL.md for usage instructions.
Conflict Resolution Strategies Reference
Strategy Decision Matrix
Choose your strategy based on your situation:
| Scenario | Strategy | Complexity | Risk | Time | Best For |
|---|---|---|---|---|---|
| 3+ commits, many changes | Squash First | Medium | Low | Fast | Feature branches, CI/CD |
| 1-2 commits, simple | Simple Rebase | Low | Low | Fast | Quick hotfixes |
| Clean history needed | Interactive | High | Medium | Slow | Production code |
| Same conflicts repeat | Rerere | Low | Very Low | Very Fast | Complex rebases |
| Unknown complexity | Merge instead | Very Low | Very Low | Fast | When in doubt |
---
Deep Dive: Each Strategy
1. Squash First (Recommended)
How it works:
# Squash all commits into one
git rebase -i origin/main # Keeps your branch's history intact
# Mark commits as 's' (squash) to combine them
# Then rebase once against mainWhen to use:
- 3+ commits to rebase
- Multiple files changed
- Conflicts expected
- Want clean commit history on main
Advantages:
- ✅ Resolve conflicts ONCE (not per-commit)
- ✅ Final code is one clean commit
- ✅ Faster for many commits
- ✅ Easy to understand final state
Disadvantages:
- ❌ Lose intermediate commit history
- ❌ Can't debug individual commits later
- ❌ Harder to bisect if bug is introduced
Example:
$ git rebase -i $(git merge-base HEAD origin/main)
# Editor shows:
pick a1b2c3d feat: add authentication
pick d4e5f6g fix: handle edge case
pick h7i8j9k chore: update dependencies
# Change to:
pick a1b2c3d feat: add authentication
s d4e5f6g fix: handle edge case
s h7i8j9k chore: update dependencies
# Save - commits squash into one
# Write new commit message describing entire feature
$ git rebase origin/main
# Resolve conflicts once
$ git rebase --continue
$ git push origin feature-branch --force-with-lease---
2. Interactive Rebase (Full Control)
How it works:
git rebase -i origin/main
# Reorder, edit, squash individual commits before rebasingWhen to use:
- Want to keep some commits, squash others
- Need to reorder commits strategically
- Want to reword commit messages
- History preservation is important
Advantages:
- ✅ Full control over commit order
- ✅ Can keep important intermediate commits
- ✅ Can edit commit messages
- ✅ Excellent for code review
Disadvantages:
- ❌ More conflict resolution iterations
- ❌ Takes more time
- ❌ More error-prone
Interactive rebase commands:
pick = use commit
reword = use commit, but edit message
squash = use commit but combine with previous
fixup = like squash, but discard log message
drop = remove commit
exec = run command between commitsExample:
$ git rebase -i origin/main
# Before:
pick commit1 - feat: part A
pick commit2 - feat: part B
pick commit3 - test: add tests
pick commit4 - chore: lint
# Edit to:
pick commit1 - feat: part A
squash commit2 - feat: part B # Combine with part A
squash commit3 - test: add tests # Include tests
drop commit4 - chore: lint # Remove lint-only commit
# Save and edit final message to describe everything---
3. Simple Linear Rebase (Fastest)
How it works:
git rebase origin/main
# Git replays all your commits directly, no intermediate editsWhen to use:
- 1-2 commits only
- Simple changes, minimal conflicts
- Don't care about reordering
- Want fastest possible rebase
Advantages:
- ✅ Fastest to execute
- ✅ Simplest conceptually
- ✅ Preserves commit history as-is
Disadvantages:
- ❌ Conflict per commit (can be slow)
- ❌ Can't reorder or edit commits
- ❌ Loses opportunity to clean up history
---
4. Git Rerere (Smart Replay)
How it works:
git config --global rerere.enabled true
# Git records your conflict resolutions
# Automatically replays them when same conflict appearsWhen to use:
- Rebasing many commits against target with repeated conflicts
- Same file changed in multiple of your commits
- Want to avoid re-resolving the same conflicts
Advantages:
- ✅ Automatic conflict replay
- ✅ Huge time savings for complex rebases
- ✅ Consistent resolutions
Disadvantages:
- ❌ Can hide mistakes if recorded wrong
- ❌ Requires careful first resolution
- ❌ Only works for identical conflict patterns
How to use:
# Enable (one-time)
git config --global rerere.enabled true
# Now when you rebase:
git rebase origin/main
# First conflict: You resolve it
# [Edit file, git add, git rebase --continue]
# Second identical conflict: Git automatically applies same resolution
# Just keep going: git rebase --continue
# Git has learned your conflict pattern and replays itTrack rerere database:
# See all recorded resolutions
ls -la .git/rr-cache/
# Review a specific resolution
cat .git/rr-cache/<conflict-hash>/preimage
cat .git/rr-cache/<conflict-hash>/postimage---
5. Merge Instead (Safest Alternative)
How it works:
git merge origin/main
# Combines two branches, creates merge commitWhen to use:
- Shared branches (never rebase shared branches!)
- Too complex to rebase
- Team collaboration on same branch
- Want to preserve branch history
Advantages:
- ✅ Preserves both histories
- ✅ Can't lose commits
- ✅ Safe for shared branches
- ✅ Clearer integration point
Disadvantages:
- ❌ Less clean history
- ❌ Creates merge commit
- ❌ Harder to bisect
- ❌ More verbose history
---
Automation Strategies (Pipeline Use)
Risky: Auto-Accept With -X
# Accept all INCOMING changes (main's version)
git rebase -X theirs origin/main
# Accept all YOUR changes (your version)
git rebase -X ours origin/main
# Three-way recursive merge (safest auto-strategy)
git rebase -X recursive origin/mainONLY use when:
1. You have comprehensive tests covering all changes 2. You understand the implications 3. You've verified the strategy on a test branch first 4. Changes are non-critical (not user-facing)
Recommendation: Avoid auto-resolution in production pipelines.
---
Conflict Complexity Indicators
Low Complexity (Safe to Auto-Resolve)
- ✅ Changes in different files
- ✅ Same file, different functions/methods
- ✅ Whitespace/formatting conflicts
- ✅ Import reordering
Medium Complexity (Manual Review Needed)
- ⚠️ Changes in same function but different branches
- ⚠️ Logic changes (if statements, loops)
- ⚠️ Return values or flow changes
- ⚠️ API changes
High Complexity (Very Careful)
- ❌ Same line changed differently
- ❌ Critical business logic
- ❌ Security/authentication code
- ❌ Database migrations
---
Decision Tree: Which Strategy?
START: Do I need to rebase?
|
+-> Is this a shared branch?
|-> YES: Use MERGE instead, don't rebase
|-> NO: Continue
|
+-> How many commits to rebase?
|-> 1-2 commits:
| +-> Use SIMPLE LINEAR REBASE
| +-> Quick, straightforward
|
|-> 3-10 commits:
| +-> Are conflicts expected?
| +-> YES: Use SQUASH FIRST
| +-> NO: Use INTERACTIVE REBASE
|
|-> 10+ commits:
+-> Almost always: Use SQUASH FIRST
+-> Too many conflict iterations otherwise
|
+-> Any other concerns?
|-> I've rebased this file before: Enable RERERE
|-> Feeling uncertain: Use MERGE instead
|-> Need clean history: Use INTERACTIVE
|-> Just want it done: Use SQUASH FIRST
END: Choose strategy and proceed---
Post-Resolution Validation
After resolving conflicts, always validate:
# 1. Check syntax (prevents runtime errors)
npm run lint
npm run type-check # If TypeScript
# 2. Check logic (review changes)
git diff HEAD origin/main -- <conflicted-file>
# 3. Run tests (catches integration issues)
npm test
# 4. Manual smoke test (try key features)
npm start
# Test the feature manually
# 5. Only then force push
git push origin branch --force-with-leaseRule: Never push code you haven't tested.
Troubleshooting Common Rebase Issues
Problem: "CONFLICT (content): Merge conflict in X"
What it means: File X has conflicting changes from both branches
Solution:
1. git status to see all conflicts 2. Edit each conflicted file (look for <<<<<<< markers) 3. git add <file> 4. git rebase --continue
Problem: "fatal: cannot lock ref 'refs/heads/...'"
What it means: Git can't write to branch (another command is running or permission issue)
Solution:
# Check if another git process is running
ps aux | grep git
# Kill it if safe: kill <PID>
# Or retry after a moment
# If persistent: check file permissions in .git/Problem: Rebase seems stuck (no prompt)
What it means: Your editor didn't open, or it's waiting for input
Solution:
# Check if you have an editor set
git config --global core.editor
# Set one if not configured
git config --global core.editor "nano" # or "vim", "code", etc.
# Resume rebase
git rebase --continueProblem: "Your branch has diverged"
What it means: After rebase, local and remote have different history
Solution:
# This is EXPECTED after rebase
# Force push safely to update remote
git push origin $(git rev-parse --abbrev-ref HEAD) --force-with-leaseProblem: Lost Commits After Force Push
Recovery:
# Your backup branch saves you
git reset --hard backup-rebase-<timestamp>
# Or use reflog to find the SHA
git reflog
git reset --hard <SHA>#!/bin/bash
# analyze-conflicts.sh
# Analyzes git rebase conflicts and provides detailed information
# Usage: bash analyze-conflicts.sh
set -e
echo "🔍 Git Rebase Conflict Analyzer"
echo "======================================"
echo ""
# Check if we're in a rebase
if [ ! -d ".git/rebase-merge" ] && [ ! -d ".git/rebase-apply" ]; then
echo "❌ No active rebase detected"
echo "Start a rebase first: git rebase origin/main"
exit 1
fi
echo "✓ Active rebase detected"
echo ""
# Get conflicting files
echo "📋 Conflicted Files:"
CONFLICTED_FILES=$(git diff --name-only --diff-filter=U)
CONFLICT_COUNT=$(echo "$CONFLICTED_FILES" | wc -l)
echo " Found $CONFLICT_COUNT file(s) with conflicts:"
echo "$CONFLICTED_FILES" | sed 's/^/ - /'
echo ""
# Analyze each conflict
echo "🔎 Conflict Analysis:"
echo ""
for file in $CONFLICTED_FILES; do
echo "📄 File: $file"
# Count conflict markers
MARKER_COUNT=$(($(grep -c "<<<<<<" "$file" || echo 0)))
echo " Conflict sections: $MARKER_COUNT"
# Show file size
FILE_SIZE=$(wc -c < "$file")
echo " File size: $FILE_SIZE bytes"
# Show line count
LINE_COUNT=$(wc -l < "$file")
echo " Total lines: $LINE_COUNT"
# Check for conflict markers
if grep -q "<<<<<<" "$file"; then
echo " Status: ⚠️ UNRESOLVED (has conflict markers)"
# Show first conflict
FIRST_CONFLICT=$(grep -n "<<<<<<" "$file" | head -1 | cut -d: -f1)
echo " First conflict at line: $FIRST_CONFLICT"
# Show context around first conflict (3 lines before and after markers)
echo " Context:"
sed -n "$((FIRST_CONFLICT-3)),$((FIRST_CONFLICT+10))p" "$file" | \
sed 's/^/ /'
else
echo " Status: ✓ RESOLVED (no conflict markers)"
fi
echo ""
done
# Summary
echo "📊 Summary:"
UNRESOLVED=$(for f in $CONFLICTED_FILES; do
grep -l "<<<<<<" "$f" 2>/dev/null || true
done | wc -l)
RESOLVED=$((CONFLICT_COUNT - UNRESOLVED))
echo " ✓ Resolved: $RESOLVED"
echo " ⚠️ Unresolved: $UNRESOLVED"
echo ""
# Get rebase progress
if [ -f ".git/rebase-merge/msgnum" ]; then
CURRENT=$(cat .git/rebase-merge/msgnum)
TOTAL=$(cat .git/rebase-merge/end)
echo "📈 Rebase Progress: $CURRENT / $TOTAL commits"
echo ""
fi
# Suggestions
echo "💡 Next Steps:"
if [ "$UNRESOLVED" -gt 0 ]; then
echo " 1. Edit conflicted files and resolve all markers"
echo " 2. Run: bash scripts/validate-merge.sh"
echo " 3. Run: npm run lint && npm test"
echo " 4. Run: git add ."
echo " 5. Run: git rebase --continue"
else
echo " 1. All conflicts appear resolved!"
echo " 2. Run: bash scripts/validate-merge.sh"
echo " 3. Run: npm run lint && npm test"
echo " 4. Run: git add ."
echo " 5. Run: git rebase --continue"
fi
echo ""
echo "✅ Analysis complete"
#!/bin/bash
# pre-rebase-backup.sh
# Creates a safe backup before starting a rebase
# Usage: bash pre-rebase-backup.sh [branch-name]
echo "🔐 Pre-Rebase Safety Backup"
echo "======================================"
echo ""
# Get current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$CURRENT_BRANCH" = "HEAD" ]; then
echo "❌ You're in detached HEAD state"
echo "Checkout a branch first: git checkout your-branch"
exit 1
fi
# Check if clean
if [ -n "$(git status --porcelain)" ]; then
echo "⚠️ Warning: You have uncommitted changes"
echo "Commit or stash them first:"
echo " git add . && git commit -m 'work in progress'"
echo " or"
echo " git stash"
exit 1
fi
echo "Current branch: $CURRENT_BRANCH"
echo ""
# Create timestamped backup
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_BRANCH="backup-rebase-${CURRENT_BRANCH}-${TIMESTAMP}"
echo "Creating backup branch..."
git branch "$BACKUP_BRANCH"
# Get current commit
CURRENT_SHA=$(git rev-parse HEAD)
echo ""
echo "✅ Backup created successfully!"
echo ""
echo "📋 Backup Details:"
echo " Branch name: $BACKUP_BRANCH"
echo " Commit SHA: $CURRENT_SHA"
echo ""
# Save backup info to file for easy recovery
BACKUP_INFO_FILE=".rebase-backup-info"
cat > "$BACKUP_INFO_FILE" << EOF
# Rebase Backup Information
# Created: $(date)
BACKUP_BRANCH=$BACKUP_BRANCH
CURRENT_BRANCH=$CURRENT_BRANCH
COMMIT_SHA=$CURRENT_SHA
TIMESTAMP=$TIMESTAMP
# To recover from this backup:
# git reset --hard backup-rebase-${CURRENT_BRANCH}-${TIMESTAMP}
EOF
echo "💾 Backup info saved to: $BACKUP_INFO_FILE"
echo ""
# Show git reflog for additional recovery options
echo "📚 Backup Recovery Instructions:"
echo ""
echo "If something goes wrong, you can recover using:"
echo ""
echo " Option 1 (Recommended): Use the backup branch"
echo " git reset --hard $BACKUP_BRANCH"
echo ""
echo " Option 2: Use git reflog"
echo " git reflog # Find your commit SHA"
echo " git reset --hard <SHA>"
echo ""
# List all backup branches
echo "🗂️ All Backup Branches:"
git branch | grep "backup-rebase" | tail -5 | sed 's/^/ - /'
echo ""
echo "✅ You're ready to rebase safely!"
echo ""
echo "Next steps:"
echo " 1. git fetch origin"
echo " 2. git rebase origin/main"
echo " 3. Resolve any conflicts"
echo " 4. git rebase --continue"
echo " 5. git push origin $CURRENT_BRANCH --force-with-lease"
#!/bin/bash
# validate-merge.sh
# Validates that merge/rebase is clean and ready for testing
# Usage: bash validate-merge.sh
set -e
echo "🔍 Merge/Rebase Validation"
echo "======================================"
echo ""
EXIT_CODE=0
# 1. Check for remaining conflict markers
echo "1️⃣ Checking for conflict markers..."
if git grep -l '<<<<<<\|======\|>>>>>>' 2>/dev/null | wc -l | grep -q '^0$'; then
echo " ✓ No conflict markers found"
else
echo " ❌ FOUND conflict markers:"
git grep -l '<<<<<<\|======\|>>>>>>' 2>/dev/null || true
echo ""
echo " ⚠️ Please resolve these files before continuing"
EXIT_CODE=1
fi
echo ""
# 2. Check for unresolved git conflicts
echo "2️⃣ Checking git status..."
if [ -z "$(git diff --name-only --diff-filter=U)" ]; then
echo " ✓ No unresolved conflicts in git status"
else
echo " ❌ Git still shows unresolved conflicts:"
git diff --name-only --diff-filter=U | sed 's/^/ - /'
EXIT_CODE=1
fi
echo ""
# 3. Check if working directory is clean
echo "3️⃣ Checking working directory..."
if git status --porcelain | grep -q '^ M\| ??'; then
echo " ⚠️ Unstaged changes found:"
git status --short | sed 's/^/ /'
echo ""
echo " Tip: Run 'git add .' to stage all changes"
else
echo " ✓ Working directory clean"
fi
echo ""
# 4. Check for duplicate code (merged sections)
echo "4️⃣ Checking for duplicate code patterns..."
COMMON_DUPES=$(git diff HEAD | grep -c '^+.*{$' || echo 0)
if [ "$COMMON_DUPES" -lt 10 ]; then
echo " ✓ No obvious code duplication detected"
else
echo " ⚠️ Possible code duplication (many new code blocks):"
echo " Manual review recommended"
fi
echo ""
# 5. Check for common merge markers in comments
echo "5️⃣ Checking for merge message artifacts..."
if git diff HEAD | grep -i "merged\|conflict\|cherry-pick\|rebase"; then
echo " ⚠️ Found merge-related comments in changes"
echo " Review to ensure they're intentional"
else
echo " ✓ No merge artifacts in comments"
fi
echo ""
# 6. Show changed files
echo "6️⃣ Changed Files Summary:"
CHANGED=$(git diff --name-only)
CHANGED_COUNT=$(echo "$CHANGED" | grep -c . || echo 0)
echo " $CHANGED_COUNT files changed:"
echo "$CHANGED" | sed 's/^/ - /'
echo ""
# 7. Show stats
echo "7️⃣ Diff Statistics:"
git diff --stat | sed 's/^/ /'
echo ""
# Final status
echo "======================================"
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Validation PASSED - Ready for testing!"
echo ""
echo "Next steps:"
echo " 1. Run tests: npm test"
echo " 2. Run linter: npm run lint"
echo " 3. Manual smoke test if needed"
echo " 4. Then: git rebase --continue"
else
echo "❌ Validation FAILED - Fix issues before proceeding"
echo ""
echo "Issues found:"
echo " - Conflict markers remain (resolve in files)"
echo " - Git shows unresolved conflicts"
echo " - Other validation errors above"
echo ""
echo "Fix and run: bash validate-merge.sh"
fi
exit $EXIT_CODE