如何使用 IntelliJ 将更改从一个分支转移到另一个分支?

问题描述 投票:0回答:2

我对 git 还很陌生。我想创建一个项目,并且正在使用 IntelliJ 克隆我的存储库。不幸的是,IntelliJ 有自己的分支正在创建(称为 master)。现在我想将我的更改提交到 main,而不是 master。

因此,我正在尝试以下方法:

  1. 提交我的更改并将其推送到 master,以确保我的更改不会丢失。

  2. 选择 main 并执行“将 master 重新设置到 origin/main”。

  3. 选择主要并进行“结帐”。

但是,结帐后我的更改被重置并且文件夹为空。我是不是忘记了什么。感谢您的帮助。

enter image description here

我在上面解释过。

git intellij-idea git-branch git-rebase
2个回答
1
投票

默认分支名称的说明

IntelliJ 与创建新存储库时默认分支的名称

master
无关。这是一个 Git 配置。默认情况下,Git 使用全局配置中指定的名称
init.defaultBranch
。如果未指定名称,则使用
master
。有关更多详细信息,请参阅官方文档的“您的默认分支名称”部分。

您可以通过以下方式检查您的全局配置:

#check your global configurations
git config --global --list

您可以使用以下命令更改默认分支的名称:

git config --global init.defaultBranch main

像这样,您计算机上的每个新存储库都会将

main
作为其默认分支。

解决您的问题

回到你的问题,如果我正确理解你的情况,你的存储库是使用

master
分支创建的,并且在某个时刻从它创建了
main
分支。您现在已经对
master
(提交 C)进行了一些更改,并且您希望在您的
main
分支上进行这些更改。

A -- B ---- C     master
      \ 
       D -- E     main

在这种情况下,您可以将

main
重新设置为
master
之上:

#selecting the main branch
git checkout main

#relocating the main branch with master's HEAD commit as its base
git rebase master

产生以下情况:

A -- B -- C              master
           \ 
            D' -- E'     main

如果您想通过IntelliJ的界面而不是终端执行相同的操作,您需要选择选项

Checkout and Rebase onto 'master'

替代解决方案

  1. master
    分支挑选提交到
    main
    分支,并将
    master
    分支重置为其之前的提交。
# select the main branch
git checkout main

# re-writing the HEAD commit of the master branch on top of main
git cherry-pick master

# selecting the master branch
git checkout master

# resetting the master branch to its previous commit
git reset --hard HEAD~
  1. 如果
    master
    分支上的更改尚未提交,则此解决方案有效。首先,stash来自
    master
    分支的更改,然后签出
    main
    分支并在其上应用隐藏的更改。最后,在
    main
    分支上提交更改。
# while the master branch is checked out

# stashing the uncommitted changes (untracked files included)
git stash push -u

# selecting the main branch
git checkout main

# applying the stashed changes to the main branch
git stash pop

# committing the changes on the main branch
git add <file1>, ..., <fileN>
git commit -m "my commit message"

重命名分支

如果将来您发现自己处于同样的困境,您的默认分支称为

master
并且您希望将其称为
main
,您可以使用
git branch -m
重命名分支。

git branch -m master main

-1
投票

你不必使用master,你可以使用任何你想要的分支。

至于“选择 main 并执行“将 master 重新设置到 origin/main”。”

您是否将这些更改推送到了 main 中?因为您正在远程分支而不是本地分支上进行变基。

© www.soinside.com 2019 - 2024. All rights reserved.