我的目录A中有与目录b匹配的文件,目录A中可能有其他需要的文件。目录B是一个git repo。

我想克隆目录B到目录A,但是git-clone不允许我这样做,因为目录是非空的。

我希望它只是克隆。git,因为所有的文件匹配我可以从那里去?

我不能克隆到一个空目录,因为我在目录A中有不在目录B中的文件,我想保留它们。

复制.git不是一个选项,因为我想用引用来推/拉,我不想手动设置它们。

有什么办法可以做到吗?

更新:我认为这是有效的,有人能看到任何问题吗?-->

cd a
git clone --no-hardlinks --no-checkout ../b a.tmp 
mv a.tmp/.git .
rm -rf a.tmp
git unstage # apparently git thinks all the files are deleted if you don't do this

当前回答

我在几分钟前使用过这个,它需要最小的潜在破坏性命令:

cd existing-dir
git clone --bare repo-to-clone .git
git config --unset core.bare
git remote rm origin
git remote add origin repo-to-clone
git reset

瞧!

其他回答

这招对我很管用:

git init
git remote add origin PATH/TO/REPO
git fetch
git reset origin/master  # Required when the versioned files existed in path before "git init" of this repo.
git checkout -t origin/master

注意:-t将为您设置上游分支,如果这是您想要的,而且通常是这样。

警告-这可能会覆盖文件。

git init     
git remote add origin PATH/TO/REPO     
git fetch     
git checkout -t origin/master -f

修改自@cmcginty的回答-没有-f对我来说没用

我在几分钟前使用过这个,它需要最小的潜在破坏性命令:

cd existing-dir
git clone --bare repo-to-clone .git
git config --unset core.bare
git remote rm origin
git remote add origin repo-to-clone
git reset

瞧!

对其中一个对我有用的答案稍加修改:

git init
git remote add origin PATH/TO/REPO
git pull origin master

直接开始在主分支上工作。

我在寻找一个不同的问题时,我偶然发现了这个问题:如何克隆到一个存在的目录,而文件不存在?

无论如何,我最近对几个服务器上的一些非源代码控制的文件副本就这样做了。

cd <target directory>
git init
git remote add origin <repository URI>
git fetch
git branch -f master origin/master
git reset
git show HEAD:.gitignore > .gitignore

这样的:

为您初始化一个空的回收目录 为要连接的存储库添加一个远程 检索存储库文件夹内容(/.git) 强制git init中的默认分支跟踪origin/master 取消获取所创建的所有更改(我不准确地理解在获取时staging所有文件的机制) 存储库的.gitignore文件中的副本(如果要使用该文件,则需要该文件)

对于我的问题,答案是git重置——Dale Forester的答案是hard HEAD。

用于任意分支和远程名称的替代指令

git init
git remote add <remotename> <repository URI>
git checkout -b <localbranchname>
git fetch <remotename> <remotebranchname>
git branch -f <localbranchname> <remotename>/<remotebranchname>
git reset
git show HEAD:.gitignore > .gitignore

如上所述,这是:

Initializes an empty repo directory for you Adds a remote for the repository you intend to connect to Sets the local branch name. Optional, but recommended to keep branches straight if you're doing more than one branch on the same environment Retrieves the repository folder contents (/.git) Forces the local branch from git checkout -b <localbranchname> to track <remote>/<remotebranchname> Unstages all changes created by the fetch (I don't precisely understand the mechanism for staging all the files on fetch) Copies in the repository's .gitignore file (which you'll want if you're going to use it)

如果您在最后执行git状态,您将看到当前目录(工作目录)中的任何文件都发生了未分阶段的更改,无论工作目录是否与存储库结构有关。