Reputation: 2527
I've run into this situation occasionally:
git init
locally and start version controlI've read of several ways to fix this. I think one of them is to do a reset head or rebase, the other is to git pull origin master --allow-unrelated-histories
followed by git push origin master
. I'm not sure which way is the most effective/least destructive way to solve this problem. Generally, I'm not super worried about accidentally deleting the LICENSE or readme.md, but it would be bad if I accidentally deleted my local repository source code of course.
I'm aware that this situation can be avoided if I were to initiate the GitHub remote FIRST and then git clone
it, then commit my code there locally... But sometimes it just doesn't work out that way.
Upvotes: 1
Views: 1006
Reputation: 265151
I see two possibilities, whether or not you want to keep your remote history (i.e. the initial commit on GitHub):
All commands assume that you are currently on your local master
(git checkout master
) branch and all changes are committed (i.e. working directory is clean)
If you do not care about the history on GitHub (i.e. the single initial commit containing the LICENSE
and README
file), you can simply force push to your remote repository
git remote add origin your_github_repository_url
git push origin +master:master
This will push your local master commit to the remote and overwrite any commits that exist remotely (i.e. on GitHub). This will not affect your local history.
This is a bit more complicated, but still rather straightforward. You need to fetch both (unrelated) lines of history into a single repository and then merge/rebase (this will change the commit hashes of one of the two branches):
git remote add origin your_github_repository_url
git fetch
git rebase origin/master master
git push origin master:master
This will rebase your local master on top of the remote (= GitHub) master. All your local commit hashes will have changed (but since this is a new project, this is probably not a big problem).
Alternatively, you could copy the remote commit(s) to your local branch. You can cherry-pick the commit(s) to achieve that:
git remote add origin your_github_repository_url
git fetch
git cherry-pick origin/master
git push origin +master:master
This will cherry-pick (i.e. copy) the latest commit from the remote (= GitHub) on top of your local master branch and then force-push your local master branch over the remote master branch.
NOTE: if you are afraid of losing your local changes/files/commits → make a backup of your repository first (simply copy the full directory with all subdirectories)
Upvotes: 2