记录:解决 Git 合并冲突的问题

161 阅读2分钟

背景

在项目开发过程中,我们经常需要从远程仓库的不同分支拉取代码并进行合并。最近,在尝试从 master 分支直接拉取 service_platform 分支的代码时遇到了冲突。本文将记录这一问题的解决过程,以便未来遇到类似情况时能够快速应对。

git clone 命令本身不支持直接指定克隆某个特定分支。默认情况下,git clone 会克隆远程仓库的默认分支(通常是 master 或 main)。

虽然 git clone 本身不支持直接指定分支,但可以通过 --branch 选项来实现类似的效果。这种方法会克隆指定的分支,并且只下载该分支的历史记录.

   git clone --branch service_platform git@codeup.aliyun.com:snackpub/sneak.git
   cd one-plus

查看当前是哪个版本:

[jenkins@VM-0-2-centos one-plus]$ git branch --show-current 
    error: unknown option `show-current'

[jenkins@VM-0-2-centos one-plus]$ git branch
  master
* service_platform

问题描述

在本地克隆了 master 分支后,执行以下命令:

git clone git@codeup.aliyun.com:snackpub/sneak.git
cd one-plus
git pull git@codeup.aliyun.com:snackpub/sneak.git service_platform

结果出现了冲突,Git 无法自动合并 master 分支和 service_platform 分支之间的不同更改.

image.png

解决步骤

  1. 克隆仓库

首先,确保已经克隆了仓库:

    git clone git@codeup.aliyun.com:snackpub/sneak.git
    cd one-plus

2. 切换到 service_platform 分支

创建并切换到 service_platform 分支:
   git checkout -b service_platform origin/service_platform
   //    git checkout service_platform

3. 拉取最新的 service_platform 分支

拉取远程 service_platform 分支的最新代码:
   git pull origin service_platform

4. 解决冲突

如果在拉取过程中出现冲突,Git 会提示哪些文件存在冲突。手动打开这些文件,找到冲突标记并解决冲突。冲突标记通常如下所示
  <<<<<<< HEAD
  // 当前分支的代码
  =======
  // 要合并的分支的代码
  >>>>>>> service_platform

编辑这些文件,保留正确的代码,并删除冲突标记。

  1. 添加已解决的文件 将已解决的文件添加到暂存区:
   git add < conflicted file >

6. 提交更改 提交解决冲突后的更改:

   git commit -m "Resolve conflicts with service_platform"

7. 推送更改

  git push origin service_platform

8. 预防措施

为了避免未来的冲突,建议在进行合并操作前,先确保本地分支是最新的

git fetch origin
git merge origin/master

这样可以提前发现并解决潜在的冲突。

总结

通过上述步骤,成功解决了从 master 分支直接拉取 service_platform 分支代码时出现的冲突问题。