MCP HubMCP Hub
Вернуться к навыкам

resolve-git-conflicts

pjt222
Обновлено Yesterday
1 просмотров
17
2
17
Посмотреть на GitHub
Дизайнaiapidesign

О программе

Этот навык Claude помогает разработчикам разрешать конфликты при слиянии, перебазировании и выборочном применении коммитов в Git, определяя источники конфликтов, читая маркеры и выбирая стратегии разрешения. Он предоставляет безопасные методы восстановления для продолжения или отмены операций при возникновении конфликтов из-за команд, таких как merge, pull или stash pop. Используйте его для систематического управления и восстановления после неудачных операций в Git.

Быстрая установка

Claude Code

Рекомендуется
Основной
npx skills add pjt222/agent-almanac -a claude-code
Команда плагинаАльтернативный
/plugin add https://github.com/pjt222/agent-almanac
Git клонированиеАльтернативный
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/resolve-git-conflicts

Скопируйте и вставьте эту команду в Claude Code для установки этого навыка

Документация

Resolve Git Conflicts

Identify, resolve, and recover from merge and rebase conflicts.

When to Use

  • A git merge or git rebase reports conflicts
  • A git cherry-pick cannot apply cleanly
  • A git pull results in conflicting changes
  • A git stash pop conflicts with current working tree

Inputs

  • Required: Repository with active conflicts
  • Optional: Preferred resolution strategy (ours, theirs, manual)
  • Optional: Context about which changes should take priority

Procedure

Step 1: Identify the Conflict Source

Determine what operation caused the conflict:

# Check current status
git status

# Look for indicators:
# "You have unmerged paths" — merge conflict
# "rebase in progress" — rebase conflict
# "cherry-pick in progress" — cherry-pick conflict

The status output tells you which files have conflicts and what operation is in progress.

Got: git status shows files listed under "Unmerged paths" and indicates the active operation.

If fail: If git status shows a clean tree but you expected conflicts, the operation may have already been completed or aborted. Check git log for recent activity.

Step 2: Read Conflict Markers

Open each conflicting file and locate the conflict markers:

<<<<<<< HEAD
// Your current branch's version
const result = calculateWeightedMean(data, weights);
=======
// Incoming branch's version
const result = computeWeightedAverage(data, weights);
>>>>>>> feature/rename-functions
  • <<<<<<< HEAD to =======: Your current branch (or the branch you're rebasing onto)
  • ======= to >>>>>>>: The incoming changes (the branch being merged or the commit being applied)

Got: Each conflicting file contains one or more blocks with <<<<<<<, =======, and >>>>>>> markers.

If fail: If no markers are found but files show as conflicting, the conflict may be a binary file or a deleted-vs-modified conflict. Check git diff --name-only --diff-filter=U for the full list.

Step 3: Choose a Resolution Strategy

Manual merge (most common): Edit the file to combine both changes logically, then remove all conflict markers.

Accept ours (keep current branch's version):

# For a single file
git checkout --ours path/to/file.R
git add path/to/file.R

# For all conflicts
git checkout --ours .
git add -A

Accept theirs (keep incoming branch's version):

# For a single file
git checkout --theirs path/to/file.R
git add path/to/file.R

# For all conflicts
git checkout --theirs .
git add -A

Got: After resolution, the file contains the correct merged content with no remaining conflict markers.

If fail: If you chose the wrong side, re-read the conflicting version from the merge base. During a merge, git checkout -m path/to/file re-creates the conflict markers so you can try again.

Step 4: Mark Files as Resolved

After editing each conflicting file:

# Stage the resolved file
git add path/to/resolved-file.R

# Check remaining conflicts
git status

Repeat for every file listed under "Unmerged paths".

Got: All files move from "Unmerged paths" to "Changes to be committed". No conflict markers remain in any file.

If fail: If git add fails or markers remain, re-open the file and ensure all <<<<<<<, =======, and >>>>>>> lines are removed.

Step 5: Continue the Operation

Once all conflicts are resolved:

For merge:

git commit
# Git auto-populates the merge commit message

For rebase:

git rebase --continue
# May encounter more conflicts on subsequent commits — repeat steps 2-4

For cherry-pick:

git cherry-pick --continue

For stash pop:

# Stash pop conflicts don't need a continue — just commit or reset
git add .
git commit -m "Apply stashed changes with conflict resolution"

Got: The operation completes. git status shows a clean working tree (or moves to the next commit during rebase).

If fail: If the continue command fails, check git status for remaining unresolved files. All conflicts must be resolved before continuing.

Step 6: Abort if Needed

If resolution is too complex or you chose the wrong approach, abort safely:

# Abort merge
git merge --abort

# Abort rebase
git rebase --abort

# Abort cherry-pick
git cherry-pick --abort

Got: Repository returns to the state before the operation started. No data loss.

If fail: If abort fails (rare), check git reflog to find the commit before the operation and git reset --hard <commit> to restore it. Use with caution — this discards uncommitted changes.

Step 7: Verify Resolution

After the operation completes:

# Verify clean working tree
git status

# Check that the merge/rebase result is correct
git log --oneline -5
git diff HEAD~1

# Run tests to confirm nothing is broken
# (language-specific: devtools::test(), npm test, cargo test, etc.)

Got: Clean working tree, correct merge history, tests pass.

If fail: If tests fail after resolution, the merge may have introduced logical errors even though syntax conflicts are resolved. Review the diff carefully and fix.

Validation

  • No conflict markers (<<<<<<<, =======, >>>>>>>) remain in any file
  • git status shows a clean working tree
  • The merge/rebase history is correct in git log
  • Tests pass after conflict resolution
  • No unintended changes were introduced

Pitfalls

  • Blindly accepting one side: --ours or --theirs discards the other side entirely. Only use when you are certain one version is completely correct.
  • Leaving conflict markers in code: Always search the entire file for remaining markers after editing. A partial resolution breaks the code.
  • Amending during rebase: During an interactive rebase, do not --amend unless the rebase step specifically calls for it. Use git rebase --continue instead.
  • Losing work on abort: git rebase --abort and git merge --abort discard all resolution work. Only abort if you want to start over.
  • Not testing after resolution: A syntactically clean merge can still be logically wrong. Always run tests.
  • Force-pushing after rebase: After rebasing a shared branch, coordinate with collaborators before force-pushing, as it rewrites history.

Related Skills

  • commit-changes - committing after conflict resolution
  • manage-git-branches - branch workflows that lead to conflicts
  • configure-git-repository - repository setup and merge strategies

GitHub репозиторий

pjt222/agent-almanac
Путь: i18n/caveman-lite/skills/resolve-git-conflicts
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

Похожие навыки

executing-plans

Дизайн

Используйте навык executing-plans, когда у вас есть полный план реализации для выполнения контролируемыми партиями с контрольными точками проверки. Он загружает и критически анализирует план, затем выполняет задачи небольшими партиями (по умолчанию 3 задачи), сообщая о прогрессе между каждой партией для проверки архитектором. Это обеспечивает систематическую реализацию со встроенными контрольными точками проверки качества.

Просмотреть навык

requesting-code-review

Дизайн

Этот навык запускает суб-агента для ревью кода, который анализирует изменения в коде на соответствие требованиям перед дальнейшими действиями. Его следует использовать после завершения задач, реализации крупных функций или перед слиянием с основной веткой. Ревью помогает выявить проблемы на ранней стадии, сравнивая текущую реализацию с исходным планом.

Просмотреть навык

connect-mcp-server

Дизайн

Этот навык предоставляет разработчикам подробное руководство по подключению серверов MCP к Claude Code с использованием транспортов HTTP, stdio или SSE. Он охватывает установку, конфигурацию, аутентификацию и безопасность для интеграции внешних сервисов, таких как GitHub, Notion и пользовательские API. Используйте его при настройке интеграций MCP, конфигурации внешних инструментов или работе с Model Context Protocol от Claude.

Просмотреть навык

web-cli-teleport

Дизайн

Этот навык помогает разработчикам выбирать между веб-интерфейсом Claude Code и CLI на основе анализа задачи, а также обеспечивает бесшовное перемещение сессий между этими средами. Он оптимизирует рабочий процесс, управляя состоянием и контекстом сессии при переключении между веб-интерфейсом, CLI или мобильным приложением. Используйте его для сложных проектов, требующих различных инструментов на разных этапах работы.

Просмотреть навык