ChatGPT解决这个技术问题 Extra ChatGPT

How do I clone into a non-empty directory?

git

I have directory A with files matching directory B. Directory A may have other needed files. Directory B is a git repo.

I want to clone directory B to directory A but git-clone won't allow me to since the directory is non-empty.

I was hoping it would just clone .git and since all the files match I could go from there?

I can't clone into an empty directory because I have files in directory A that are not in directory B and I want to keep them.

Copying .git is not an option since I want refs to push/pull with and I don't want to set them up manually.

Is there any way to do this?

Update: I think this works, can anyone see any problems? -->

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
Just wondering what would happen if '--no-checkout' would be omitted except that the temporary clone consumes more disc space and time. Would 'git unstage' or something else still be necessary?

c
cmcginty

This worked for me:

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

NOTE: -t will set the upstream branch for you, if that is what you want, and it usually is.


This does not work in a non-empty directory when the incoming files already exist (as the original question describes). But if you git reset origin/master after the git fetch, it will work (also preserving any local changes).
fatal: Cannot update paths and switch to branch 'master' at the same time.
This answer doesn't work for me. When I do git checkout ... git complains that all my files would be overwritten and I should move them first. When I do ` git reset origin/master/` first the checkout command complains that a branch named master already exists.
git checkout master was a sufficient final step for me.
All steps worked perfectly but the last one got me: fatal: A branch named 'master' already exists. I think I did not really need it.
b
bob esponja

In the following shell commands existing-dir is a directory whose contents match the tracked files in the repo-to-clone git repository.

# Clone just the repository's .git folder (excluding files as they are already in
# `existing-dir`) into an empty temporary directory
git clone --no-checkout repo-to-clone existing-dir/existing-dir.tmp # might want --no-hardlinks for cloning local repo

# Move the .git folder to the directory with the files.
# This makes `existing-dir` a git repo.
mv existing-dir/existing-dir.tmp/.git existing-dir/

# Delete the temporary directory
rmdir existing-dir/existing-dir.tmp
cd existing-dir

# git thinks all files are deleted, this reverts the state of the repo to HEAD.
# WARNING: any local changes to the files will be lost.
git reset --hard HEAD

I needed to do git reset --hard HEAD or it wouldn't give up on the "deleted" files.
git reset HEAD worked fine for me. git reset --hard HEAD destroys any changes in your files, so if they are not exactly the same as the files in the repository, you should not do that.
git reset HEAD doesn't seem to have any affect for me. git reset --hard HEAD does - but that loses any changes you've made to the files. Is there a better solution?
@Casey's answer -- git init/remote add/fetch/checkout -- is cleaner and simpler and doesn't require any temporary folders.
@Casey's answer didn't work for me when there were already files in folders that needed to remain but that weren't in the git repo. This is useful for updating config after running install scripts where files and directories are created but you need to update/add files on top of the installed items.
P
PaulMest

A slight modification to one of the answers that worked for me:

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

to start working on the master branch straight away.


had to do reset HEAD --hard to clean the dirty existing directory, without removing irrelevant files specified in gitignore
This is the one that actually worked for me, as opposed to the @cmcginty's answer.
This is not quite equivalent to a git-clone — what's missing is the upstream information for the master branch. This can be fixed by adding git branch --set-upstream-to=origin/master master.
This version worked for me, just had to do a git reset --hard HEAD
C
Chris Stryczynski

Warning - this could potentially overwrite files.

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

Modified from @cmcginty's answer - without the -f it didn't work for me


Surely you need to checkout all the files after this with git checkout .?
M
Maciej Łebkowski

Here's what I ended up doing when I had the same problem (at least I think it's the same problem). I went into directory A and ran git init.

Since I didn't want the files in directory A to be followed by git, I edited .gitignore and added the existing files to it. After this I ran git remote add origin '<url>' && git pull origin master et voíla, B is "cloned" into A without a single hiccup.


This technique does not work in a non-empty directory when the incoming files already exist (as the original question describes).
K
KuttKatrea

I have used this a few moments ago, requires the least potentially destructive commands:

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

And voilá!


which of these commands would still be potentially destructive? I guess 'git reset', but without any option is there still destructive potential?
No command is destructive. git reset will only reset the index, but will not modify any file.
s
sealor

Another simple recipe seems to work well for me:

git clone --bare $URL .git
git config --unset core.bare

My main use case for checking out to a directory with existing files is to control my Unix dotfiles with Git. On a new account, the home directory will already have some files in it, possibly even the ones I want to get from Git.


Bare repositories are setup a little differently and while this does work I would not recommend it. :)
Can you be more specific? What is different?
Only two differences: 1.) The .git/config file indicates that the repos is bare. 2.) Files normally stored in .git is stored at the root (which you called .git)
Those are exactly the changes that cloning to .git and setting core.bare to false will take care of, so I still feel good about this method.
M
Mike6679

This worked for me:

cd existing_folder
git init
git remote add origin path_to_your_repo.git
git add .
git commit
git push -u origin master

H
Hashim Aziz

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

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

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.


K
Kevin Le - Khnle

The following worked for me. First I'd make sure the files in the a directory are source-controlled:

$ cd a
$ git init
$ git add .
$ git commit -m "..."

Then

$ git remote add origin https://URL/TO/REPO
$ git pull origin master --allow-unrelated-histories
$ git push origin master

This has definitely saved my Life. Kudos & Bitcoins !!
R
Roberto Aloi

Maybe I misunderstood your question, but wouldn't it be simpler if you copy/move the files from A to the git repo B and add the needed ones with git add?

UPDATE: From the git doc:

Cloning into an existing directory is only allowed if the directory is empty.

SOURCE: http://git-scm.com/docs/git-clone


No, the owner and the files could be arbitrary. This is for a situation with multiple developers. We all have existing directories and only one currently has a git checkout. We all largely have the same subset of files so we want to have the other developers be able to clone while retaining their files. And it should be as elegant and convenient as possible.
Honestly, I don't see the point of developing in such a condition. Can't you use branches and merge operations? Or having sub-repositories with external dependencies? Why would you want to rely on a single "git checkout"?
A "single git checkout" is not the point of the whole ordeal. It's just that this is the way it is and we need a way to move forward. I updated the original question with a solution that appears to be working. I appreciate the feedback, though.
There are lots of legitimate cases for this -- I have a complex folder tree that has to be setup BEFORE my project's source can be setup, and that folder tree contains licensed works that can't be stored on GitHub for example.
P
Philip Kirkbride

Here is what I'm doing:

git clone repo /tmp/folder
cp -rf /tmp/folder/.git /dest/folder/
cd /dest/folder
git checkout -f master

R
RODNEY ZHANG

this is work for me ,but you should merge remote repository files to the local files:

git init
git remote add origin url-to-git
git branch --set-upstream-to=origin/master master
git fetch
git status

L
Lendrick

I was looking for something similar, and here's what I came up with:

My situation is one where I have an active web tree and I was trying to create a remote repository for it without moving any of the files in the current web tree. Here's what I did:

Go to the web tree and run git init Go to the intended location of the repository and run: git clone --bare /path/to/web/repo Edit the config file in my remote repo and remove the [remote "origin"] section. Add a [remote "origin"] section to .git/config in the web tree pointing to the new remote repo.


I like this recipe a lot.
The git clone --bare here is superfluous and circuitous. Why not just git remote add origin <URL> in the first place?
g
gdlmx

I liked Dale's answer, and I also added

git clone --depth 2 --no-checkout repo-to-clone existing-dir/existing-dir.tmp
git branch dev_new214
git checkout dev_new214
git add .
git commit
git checkout dev
git merge dev_new214

The shallow depth avoided a lot of extra early dev commits. The new branch gave us a good visual history that there was some new code from this server that was placed in. That is the perfect use branches in my opinion. My thanks to the great insight of all the people who posted here.


T
Tom

I got the same issues when trying to clone to c/code

But this folder contains a whole bunch of projects.

I created a new folder in c/code/newproject and mapped my clone to this folder.

git for desktop then asked of my user and then cloned fine.


C
Christopher Eberle

I was looking for a different question when I stumbled on this: How to clone into an existent directory where the files weren't there?

At any rate, i did just this recently for some non-source-controlled copies of files on a couple of servers.

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

This:

Initializes an empty repo directory for you

Adds a remote for the repository you intend to connect to

Retrieves the repository folder contents (/.git)

Forces the default branch from git init to track origin/master

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)

For my question, the answer was the git reset --hard HEAD in Dale Forester's answer.

Alternative instructions for arbitrary branches and remote names

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

As above, this does:

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 to track /

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)

If you do a git status at the end of this, you'll see unstaged changes for any files in the current directory (the working directory) whether the working directory has anything to do with the repository structure or not.


s
shadowtalker

This question has a lot of answers, and I don't think any of them cover the option of initializing the A as a Git repo and then pulling from B to A.

# Turn `A` into a Git repo and check in files
git -C A init
git -C A add --all
git -C A commit -m "Add existing files"

# Set `B` as a remote
git -C A remote add local-B file:///B

# Fetch & merge B 'master' to A 'master'
git -C A pull --allow-unrelated local-B master