如何将新项目代码推送到已有 GitHub 仓库的特定分支?

4
我在代码中加入了远程仓库的起点。
我的现有仓库有三个分支:mastertestuser

但在添加并确认远程origin后,使用命令'git remote -v','git branch --list'命令仅显示一个分支,即master

我不知道它是否确切地指向我想要推送代码的那个起点。
我想要将新代码推到test分支。

git branch -avv

 master                     first commit
 origin                     first commit
* test                       first commit
 remotes/origin/master      Update register.tsx
 remotes/origin/test        Update next.config.js
 remotes/origin/aman        june 25

我希望将其推送到远程测试分支并删除本地分支 origin、test 和 master。
 git switch -c test
 fatal: only one reference expected

当我试图从VSCode切换到remote/origin/test分支时,它会显示分支'test'已经存在。

1个回答

1

为此,您需要:

git fetch

然后,git branch -avv命令将显示所有分支及其SHA1。
注意:只有git branch --all/-a才会列出本地和远程分支。
您可以比较masterorigin/master提交。
说明:请参见“Git Internals - The Refspec”。
$ git remote add origin https://github.com/schacon/simplegit-progit

Running the command above adds a section to your repository’s .git/config file, specifying the name of the remote (origin), the URL of the remote repository, and the refspec to be used for fetching:

[remote "origin"]
  url = https://github.com/schacon/simplegit-progit
  fetch = +refs/heads/*:refs/remotes/origin/*
fetch refspec是Git fetch会从远程仓库中找到的所有远程分支的原因,它会将这些分支放入origin命名空间中。
我希望将新代码推送到测试分支。
如果您有:
- 目前正在修改但尚未添加/提交的代码 - 只有一个本地分支(master)
您可以执行以下操作:
git fetch
git switch -c test
git add .
git commit -m "Code for test"
git rebase origin/test
git push

由于您首先执行了 git fetch,本地分支 test 将自动跟随 origin/test
请参见 git switch

If <branch> is not found, but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to:

$ git switch -c <branch> --track <remote>/<branch>
“rebase” 步骤确保您的本地提交已经在 “origin/test” 上完成/回放。
我有一个本地提交,但那并非我的本意。
我想把代码推送到远程的 remote/test 分支,然后删除所有本地分支,如 masterorigintest
为了确保不会失去任何东西,我将执行以下操作:
  • 在其他位置克隆远程库,直接使用 git clone --branch/-b 命令检出 test 分支
  • 导入你当前的代码
  • test 分支上创建新的提交
  • 推送 test
也就是说:
cd /path/to/existing/local/repo
cd ..
git clone -b test https://github.com/<me>/<myRemoteRepo> repo2
cd repo2
git --work-tree=../repo add .
git commit -m "Import from original local repo"
git push

@aman 你的意思是一个本地,一个远程吗?不要犹豫编辑你的问题:你可以在那里格式化你的编辑,而评论中没有格式化。 - VonC
@aman 你似乎只有一个本地分支。我的回答适用。 - VonC
当我尝试切换到测试分支时,它显示分支已经存在。 - aman
@aman,我没有看到你的编辑。你想用远程测试历史记录替换所有本地测试分支吗?你在测试分支上有想要保留的本地提交吗? - VonC
让我们在聊天中继续这个讨论 - VonC
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接