如何将本地Git仓库推送到远程VSTS仓库的指定文件夹?
我本地C盘的项目结构如下:
myfolder/ .git folder1 folder2 folder3 folder4 .gitignore
我已经在这个文件夹里执行了git init,接着运行了git add .和git commit -m "My first commit"。现在我想把内容推送到VSTS的远程仓库,仓库地址是:
https://helloworld.visualstudio.com/VSTS_folder/_git/VSTS_folder
远程仓库的结构是这样的:
VSTS_folder/ greenFolder redFolder blueFolder blackFolder yellowFolder .gitignore README.md
其中VSTS_folder是仓库名称,greenFolder、redFolder和yellowFolder里已经有代码了。我希望把本地内容推送到远程仓库的空文件夹blackFolder里,不想直接推到根目录造成混乱。之前我试过用git remote add origin https://helloworld.visualstudio.com/VSTS_folder/_git/VSTS_folder/blackFolder但没成功,想知道正确的Git命令应该怎么写?谢谢。
解决方案
其实Git本身并没有直接推送本地内容到远程指定文件夹的命令——毕竟Git是跟踪整个仓库的版本变化,不是针对单个文件夹的独立操作。不过我们可以通过调整本地项目结构,配合常规的Git命令来实现你的需求,具体步骤如下:
1. 调整本地项目结构
回到你的本地myfolder目录,先创建一个blackFolder文件夹,然后把除了.git和.gitignore之外的所有内容(也就是folder1到folder4)都移动到这个blackFolder里。调整后的本地结构应该是这样:
myfolder/ .git blackFolder/ folder1 folder2 folder3 folder4 .gitignore
2. 提交结构变更
执行以下命令提交这次结构调整的变更:
git add . git commit -m "Move local content into blackFolder to match remote path"
3. 关联远程仓库并推送
首先关联正确的远程仓库地址(注意不要加/blackFolder,因为远程仓库的根目录就是VSTS_folder,我们已经在本地把内容放到对应路径了):
git remote add origin https://helloworld.visualstudio.com/VSTS_folder/_git/VSTS_folder
如果你之前已经错误添加过origin,可以先执行git remote remove origin删掉旧的关联,再重新添加。
最后推送到远程仓库的默认分支(如果远程用的是main分支就写main,是master就写master):
git push -u origin main
另一种可选方案(不修改本地结构)
如果你不想改动本地的原有结构,可以先把远程仓库克隆到一个临时目录:
git clone https://helloworld.visualstudio.com/VSTS_folder/_git/VSTS_folder temp-repo
然后把你本地myfolder里的folder1到folder4复制到temp-repo/blackFolder中,接着进入temp-repo目录提交并推送:
cd temp-repo git add blackFolder/ git commit -m "Add local content to blackFolder" git push
这种方法适合不想动本地现有结构的情况,但步骤相对多一点,推荐第一种方案更直接。
内容的提问来源于stack exchange,提问作者TiredOfProgramming

