What's the best practice to “git clone” into an existing folder?

后端 未结 15 1522
情书的邮戳
情书的邮戳 2020-11-28 17:19

I have a working copy of the project, without any source control meta data. Now, I\'d like to do the equivalent of git-clone into this folder, and keep my local changes.

相关标签:
15条回答
  • 2020-11-28 17:52

    There are two approaches to this. Where possible I would start with a clean folder for your new git working directory and then copy your version of things in later. This might look something like*:

    mv $dir $dir.orig
    git clone $url $dir
    rsync -av --delete --exclude '.git' $dir.orig/ $dir/
    rm -rf $dir.orig
    

    At this point you should have a pretty clean working copy with your previous working folder as the current working directory so any changes include file deletions will show up on the radar if you run git status.

    On the other hand if you really must do it the other way around, you can get the same result with something like this:

    cd $dir
    git clone --no-checkout $url tempdir
    mv tempdir/.git .
    rmdir tempdir
    git reset --mixed HEAD
    

    Either way, the first thing I would do is run something like git stash to get a copy of all your local changes set aside, then you can re-apply them and work through which ones you want to get committed.

    * Both examples assume you start out on the shell in the parent directory of your project.

    0 讨论(0)
  • 2020-11-28 17:53

    Don't clone, fetch instead. In the repo:

    git init
    git remote add origin $url_of_clone_source
    git fetch origin
    git checkout -b master --track origin/master # origin/master is clone's default
    

    Then you can reset the tree to get the commit you want:

    git reset origin/master # or whatever commit you think is proper...
    

    and you are like you cloned.

    The interesting question here (and the one without answer): How to find out which commit your naked tree was based on, hence to which position to reset to.

    0 讨论(0)
  • 2020-11-28 17:54

    This can be done by cloning to a new directory, then moving the .git directory into your existing directory.

    If your existing directory is named "code".

    git clone https://myrepo.com/git.git temp
    mv temp/.git code/.git
    rm -rf temp
    

    This can also be done without doing a checkout during the clone command; more information can be found here.

    0 讨论(0)
提交回复
热议问题