Search code examples
gitgithubmergegit-mergegit-remote

Map remote repository to an existing directory with files


I have the following issue and cannot find a solution. I have downloaded the repository yii2-debug from GitHub some time ago (az a ZIP file). I changes some files (I know I should not do it, but there was no other option). Now I want to upgrage to the newest version, and I want to do it i a way, that next time, upgrade will be easy - just pulling the latest changes from GitHub and merge.

  1. I have a directory with my current files (so a modified version 1)
  2. I want to map this directory to the remote repository on github
  3. Then pull the latest changes (let's call it version 2)
  4. Merge the new changes with my code

I tried git init on the directory, then git remote add origin, set the branch with git branch --set-upstream

Then i tried to pull the latest changes, but somehow this did not work out well. GIT thought that my changes are "newer" and all the changes which were pulled were not merge, but mostly marked as deleted files or sth similar.

Any idea how to do this correctly? I cannot get to merge the latest changes from GitHub into my code. Thanks


Solution

  • I suggest you create a new clone of the upstream repository, replace the files in that clone with your modified version, and create a new commit containing your changes.

    One way to do this is to delete all the files in your new clone, copy your modified version into the new clone, add all the files, and commit.

    A slightly quicker/cleaner way is to move the .git directory from your new clone into the directory that contains your modified version, add all the files, and commit.

    git clone https://github.com/yiisoft/yii2-debug.git
    cd yii2-debug
    git checkout -b mychanges <branch-or-tag-you-originally-downloaded>
    cd ..
    mv yii2-debug/.git modified-version
    cd modified-version
    git add -A # see note below
    git commit -m "my changes"
    

    After doing git add -A, you should review the changes with git status. It's possible that the zip you downloaded and the corresponding commit contain slightly different files (e.g. the zip file may not contain the .gitignore file). Reviewing the changes before committing gives you the opportunity to unstage changes that you didn't actually make.

    After doing this, the directory containing your modified files is the git repository, with a mychanges branch, containing a single commit on top of the version you originally downloaded. You can merge newer branches/tags/commits into this branch, or rebase the commit containing your changes onto other branches/tags.