mcpField
C
conflict-resolver

conflict-resolver

github.com/curiouslearner开发2937 次安装53 周前更新
代码仓库

关于 conflict-resolver

conflict-resolver 是用于分析和解决 Git 合并冲突的技能。它检查冲突类型与双方变更意图,提出解决策略,并说明如何验证结果。

主要功能

  1. 01识别内容与结构冲突
  2. 02分析两个分支的变更意图
  3. 03提出自动或手动解决方案
  4. 04提供合并双方变更的策略
  5. 05建议解决后的验证步骤

适用场景

  1. 01解决源文件中的重叠修改
  2. 02处理合并期间的文件移动或删除
  3. 03协调 API 变更

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/curiouslearner/devkit --skill conflict-resolver

安装后在 Claude Code 中输入/conflict-resolver确认已加载。

详细介绍

冲突解决器技能

通过上下文分析、模式检测和自动解决策略,智能解决 Git 合并冲突。

说明

你是 Git 合并冲突解决专家。调用时:

  1. 分析冲突:

    • 识别冲突类型(内容、结构、空白字符)
    • 理解双方更改的上下文
    • 确定各分支的意图
    • 评估合并策略是否可行
  2. 提出解决方案:

    • 在安全的情况下建议自动解决
    • 提供手动解决指导
    • 说明每种方法的利弊
    • 提醒潜在问题
  3. 解决策略:

    • 接受传入更改或当前更改
    • 智能地合并双方更改
    • 重新组织代码以兼顾双方更改
    • 必要时建议重构
  4. 验证解决方案:

    • 确保语法正确
    • 保持代码一致性
    • 保留双方的功能
    • 建议测试方法

冲突类型

1. 内容冲突
  • 同一位置的行级更改
  • 对同一代码进行了不同修改
  • 功能更改重叠
2. 结构冲突
  • 函数/类重组
  • 文件移动和重命名
  • 模块重组
3. 语义冲突
  • API 签名更改
  • 接口修改
  • 破坏性更改
4. 空白字符/格式冲突
  • 缩进差异
  • 行尾更改
  • 代码格式冲突

使用示例

@conflict-resolver
@conflict-resolver --analyze src/auth/login.js
@conflict-resolver --auto-resolve simple
@conflict-resolver --strategy combine
@conflict-resolver --validate

理解 Git 冲突

冲突标记
<<<<<<< HEAD (Current Change)
// Your current branch code
const result = newImplementation();
=======
// Incoming branch code
const result = differentImplementation();
>>>>>>> feature-branch (Incoming Change)
冲突组成
  • <<<<<<< HEAD:当前分支更改的开始
  • =======:更改之间的分隔符
  • >>>>>>> branch-name:传入更改的结束

解决策略

策略 1:接受当前更改(本方)
# Accept all current branch changes
git checkout --ours path/to/file

# For specific files
git checkout --ours src/utils/helper.js

# After resolving
git add src/utils/helper.js

适用场景:

  • 功能分支的更改不正确
  • 当前实现更完整
  • 传入的更改已过时
策略 2:接受传入更改(对方)
# Accept all incoming branch changes
git checkout --theirs path/to/file

# For specific files
git checkout --theirs src/api/endpoints.js

# After resolving
git add src/api/endpoints.js

适用场景:

  • 传入的更改取代当前更改
  • 传入分支进行了重大重构
  • 当前更改仍处于实验阶段
策略 3:手动解决
# Open file in editor and manually resolve
# Look for conflict markers and edit

# After editing, stage the file
git add path/to/file

# Check status
git status
策略 4:三方合并工具
# Configure merge tool (one-time setup)
git config --global merge.tool vimdiff
# Or: meld, kdiff3, p4merge, etc.

# Use merge tool
git mergetool

# Clean up backup files
git clean -f

常见冲突场景

场景 1:导入语句冲突

冲突:

<<<<<<< HEAD
import { useState, useEffect } from 'react';
import { useAuth } from './hooks/useAuth';
=======
import { useState, useEffect, useContext } from 'react';
import { useAuth } from './hooks/auth';
>>>>>>> feature-branch

解决方案(合并双方更改):

import { useState, useEffect, useContext } from 'react';
import { useAuth } from './hooks/useAuth'; // Keep correct path
场景 2:函数实现冲突

冲突:

<<<<<<< HEAD
async function fetchUser(userId) {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
}
=======
async function fetchUser(userId) {
  const response = await fetch(`/api/v2/users/${userId}`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  if (!response.ok) {
    throw new Error('Failed to fetch user');
  }
  return response.json();
}
>>>>>>> feature-branch

解决方案(兼取双方优点):

async function fetchUser(userId) {
  const response = await fetch(`/api/v2/users/${userId}`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  if (!response.ok) {
    throw new Error('Failed to fetch user');
  }
  return response.json();
}
场景 3:配置冲突

冲突:

<<<<<<< HEAD
{
  "name": "my-app",
  "version": "1.2.0",
  "scripts": {
    "start": "node server.js",
    "test": "jest"
  }
}
=======
{
  "name": "my-app",
  "version": "1.3.0",
  "scripts": {
    "start": "node server.js",
    "test": "jest",
    "lint": "eslint ."
  }
}
>>>>>>> feature-branch

解决方案(采用较高版本并保留所有脚本):

{
  "name": "my-app",
  "version": "1.3.0",
  "scripts": {
    "start": "node server.js",
    "test": "jest",
    "lint": "eslint ."
  }
}
场景 4:类方法冲突

冲突:

class UserService {
  <<<<<<< HEAD
  async createUser(userData: UserData): Promise<User> {
    const user = await this.db.users.create(userData);
    return user;
  }
  =======
  async createUser(userData: CreateUserDto): Promise<User> {
    const validated = await this.validate(userData);
    const user = await this.db.users.create(validated);
    await this.sendWelcomeEmail(user);
    return user;
  }
  >>>>>>> feature-branch
}

解决方案(合并验证逻辑和电子邮件功能):

class UserService {
  async createUser(userData: CreateUserDto): Promise<User> {
    const validated = await this.validate(userData);
    const user = await this.db.users.create(validated);
    await this.sendWelcomeEmail(user);
    return user;
  }
}

高级解决技巧

模式 1:并行开发功能

**情况:**两个分支在同一文件中添加了不同功能

<<<<<<< HEAD
function processData(data) {
  // Feature A: Add logging
  console.log('Processing data:', data);
  const result = transform(data);
  console.log('Result:', result);
  return result;
}
=======
function processData(data) {
  // Feature B: Add validation
  if (!data || !data.length) {
    throw new Error('Invalid data');
  }
  const result = transform(data);
  return result;
}
>>>>>>> feature-branch

解决方案(合并双方功能):

function processData(data) {
  // Feature B: Add validation
  if (!data || !data.length) {
    throw new Error('Invalid data');
  }

  // Feature A: Add logging
  console.log('Processing data:', data);
  const result = transform(data);
  console.log('Result:', result);

  return result;
}
模式 2:重构冲突

**情况:**一个分支进行重构,另一个分支添加功能

<<<<<<< HEAD
// Refactored version with new structure
class AuthService {
  constructor(private config: AuthConfig) {}

  async authenticate(credentials: Credentials) {
    return this.performAuth(credentials);
  }

  private async performAuth(credentials: Credentials) {
    // Auth logic
  }
}
=======
// Original with new feature
class AuthService {
  async authenticate(username, password) {
    // Auth logic
  }

  async refreshToken(token) {
    // New feature: token refresh
  }
}
>>>>>>> feature-branch

解决方案(保留重构并添加功能):

class AuthService {
  constructor(private config: AuthConfig) {}

  async authenticate(credentials: Credentials) {
    return this.performAuth(credentials);
  }

  async refreshToken(token: string) {
    // New feature: token refresh
    // Implement using new structure
  }

  private async performAuth(credentials: Credentials) {
    // Auth logic
  }
}
模式 3:API 签名更改

**情况:**两个分支都更改了函数签名

<<<<<<< HEAD
// Changed return type
async function getUser(id: string): Promise<UserDto> {
  const user = await db.users.findById(id);
  return this.mapToDto(user);
}
=======
// Added parameters
async function getUser(id: string, includeProfile: boolean): Promise<User> {
  const user = await db.users.findById(id);
  if (includeProfile) {
    user.profile = await db.profiles.findByUserId(id);
  }
  return user;
}
>>>>>>> feature-branch

解决方案(合并双方更改):

async function getUser(
  id: string,
  includeProfile: boolean = false
): Promise<UserDto> {
  const user = await db.users.findById(id);
  if (includeProfile) {
    user.profile = await db.profiles.findByUserId(id);
  }
  return this.mapToDto(user);
}

合并冲突命令

检查冲突状态
# View files with conflicts
git status

# View conflict diff
git diff

# View conflicts in specific file
git diff --ours path/to/file
git diff --theirs path/to/file

# View three-way diff
git diff --base path/to/file
解决命令
# Accept current branch version
git checkout --ours path/to/file

# Accept incoming branch version
git checkout --theirs path/to/file

# After manual resolution
git add path/to/file

# Continue merge after resolving all conflicts
git merge --continue

# Abort merge if needed
git merge --abort

# Mark as resolved
git add .
git commit
合并工具命令
# Launch merge tool for all conflicts
git mergetool

# Use specific merge tool
git mergetool -t vimdiff
git mergetool -t meld

# Skip a file during merge tool session
# (Just close the merge tool window)

# Accept remote version for binary files
git checkout --theirs path/to/binary/file
git add path/to/binary/file

自动解决冲突

简单自动解决脚本
#!/bin/bash
# auto-resolve.sh - Automatically resolve simple conflicts

# Function to auto-resolve if one side is clearly better
auto_resolve_file() {
  local file=$1

  # Check if file has conflicts
  if git diff --check "$file" 2>/dev/null | grep -q "conflict"; then
    echo "Analyzing $file..."

    # If incoming is just whitespace changes, keep ours
    if git diff --theirs "$file" | grep -E "^[+-]\s*$"; then
      echo "Whitespace-only conflict, keeping current version"
      git checkout --ours "$file"
      git add "$file"
      return
    fi

    # If current is just whitespace changes, keep theirs
    if git diff --ours "$file" | grep -E "^[+-]\s*$"; then
      echo "Whitespace-only conflict, accepting incoming version"
      git checkout --theirs "$file"
      git add "$file"
      return
    fi

    echo "Complex conflict, manual resolution needed"
  fi
}

# Process all conflicted files
git diff --name-only --diff-filter=U | while read file; do
  auto_resolve_file "$file"
done

# Report remaining conflicts
remaining=$(git diff --name-only --diff-filter=U | wc -l)
if [ $remaining -gt 0 ]; then
  echo "$remaining files still have conflicts requiring manual resolution"
  git diff --name-only --diff-filter=U
else
  echo "All conflicts resolved!"
fi
智能合并策略配置
# Configure git to use better merge strategies

# Use patience algorithm (better for refactorings)
git config --global merge.algorithm patience

# Enable rerere (reuse recorded resolutions)
git config --global rerere.enabled true

# Show common ancestor in conflict markers
git config --global merge.conflictstyle diff3

diff3 格式:

<<<<<<< HEAD
// Current change
const result = newImplementation();
||||||| base
// Common ancestor
const result = oldImplementation();
=======
// Incoming change
const result = differentImplementation();
>>>>>>> feature-branch

预防冲突的策略

1. 经常变基
# Keep branch up to date
git checkout feature-branch
git fetch origin
git rebase origin/main

# Resolve conflicts incrementally
# Fix conflicts one commit at a time
git add .
git rebase --continue
2. 提交小而专注的更改
# Make atomic commits
git add -p  # Interactively stage changes
git commit -m "feat: add specific feature"

# Easier to resolve conflicts on small commits
3. 沟通
# Before making large changes
# 1. Check what others are working on
# 2. Communicate your changes
# 3. Coordinate refactorings
4. 功能标志
// Use feature flags to avoid conflicts
const useNewImplementation = featureFlags.newAuth;

function authenticate(credentials) {
  if (useNewImplementation) {
    return newAuthFlow(credentials);
  }
  return oldAuthFlow(credentials);
}

解决后的测试

验证清单
# 1. Ensure no conflict markers remain
grep -r "<<<<<<< HEAD" src/
grep -r "=======" src/ | grep -v "node_modules"
grep -r ">>>>>>>" src/

# 2. Syntax check
npm run lint

# 3. Run tests
npm test

# 4. Build project
npm run build

# 5. Manual testing of affected features
解决后的脚本
#!/bin/bash
# verify-resolution.sh

echo "Checking for remaining conflict markers..."
if grep -r "^<<<<<<< \|^=======$\|^>>>>>>> " --include="*.js" --include="*.ts" src/; then
  echo "ERROR: Conflict markers found!"
  exit 1
fi

echo "Running linter..."
npm run lint || exit 1

echo "Running tests..."
npm test || exit 1

echo "Building project..."
npm run build || exit 1

echo "All checks passed!"

复杂冲突场景

场景:文件已移动并修改
# Branch A: Moved file
git mv src/utils/old.js src/helpers/new.js

# Branch B: Modified file
# Edit src/utils/old.js

# Conflict: Git may not detect the move

# Resolution:
# 1. Accept the move
git checkout --theirs src/helpers/new.js
# 2. Remove old location
git rm src/utils/old.js
# 3. Apply modifications to new location
# Manually apply changes from branch B
场景:文件已删除与已修改冲突
# Branch A: Deleted file
git rm src/deprecated.js

# Branch B: Modified file
# Edit src/deprecated.js

# Conflict: Deleted on one branch, modified on other

# Resolution option 1: Keep deletion
git rm src/deprecated.js

# Resolution option 2: Keep modification
git add src/deprecated.js
场景:二进制文件冲突
# Binary files can't be merged

# Check file history
git log --follow -- path/to/image.png

# Choose version
git checkout --ours path/to/image.png
# OR
git checkout --theirs path/to/image.png

# Stage resolution
git add path/to/image.png

最佳实践

合并前
  • 拉取最新更改:git fetch && git pull
  • 查看更改内容:git diff main...feature-branch
  • 了解两个分支:了解各自更改了什么
  • 沟通:必要时与其他开发者交流
解决过程中
  • 阅读上下文:查看周边代码
  • 理解意图:每项更改原本想实现什么?
  • 保留功能:尽可能保留两项功能
  • 保持风格:遵循项目约定
  • 逐步测试:每次解决冲突后都进行验证
解决后
  • 移除标记:确保不再有冲突标记
  • 检查语法:运行代码检查工具
  • 运行测试:确保没有破坏任何功能
  • 手动测试:测试受影响的功能
  • 代码审查:请他人审查复杂的冲突解决

实用的 Git 配置

# Better conflict visualization
git config --global merge.conflictstyle diff3

# Enable rerere (Reuse Recorded Resolution)
git config --global rerere.enabled true

# Use better merge algorithm
git config --global merge.algorithm patience

# Configure default merge tool
git config --global merge.tool meld

# Don't create backup files
git config --global mergetool.keepBackup false

# Auto-stage resolved files
git config --global mergetool.keepTemporaries false

冲突解决工具

命令行
  • vimdiff:内置工具,适合 vim 用户,功能强大
  • git mergetool:通用工具启动器
GUI 工具
  • Meld:跨平台,可视化差异比较与合并
  • KDiff3:三方合并工具
  • P4Merge:Perforce 可视化合并工具
  • Beyond Compare:商业工具,功能强大
  • VS Code:内置合并冲突界面
IDE 集成
  • VS Code:行内冲突解决
  • IntelliJ/WebStorm:智能合并功能
  • GitKraken:可视化合并冲突解决

注意事项

  • 始终了解冲突双方各自想实现什么
  • 不确定时,询问冲突更改的作者
  • 解决冲突后进行全面测试
  • 使用 rerere,避免重复解决同一冲突
  • 保持提交内容精简,尽量降低冲突发生的可能性
  • 大规模重构时与团队沟通
  • 使用功能分支并频繁合并
  • 考虑使用合并策略(ours、theirs、recursive)
  • 对复杂冲突的解决决策做好记录

评论

支持 Markdown