Search code examples
gitversion-control

Git init same project in two separate systems, and synchronize changes


Context

I have programming for a while without using git, just writing code and hoping ctrl-z would work when I got it wrong.
Last week I made a little storage server with redundancy because I had years worth of projects in one laptop, and I transferred over all my project files.
Since then I've made further changes to projects in my laptop.

I've finally decided to learn git, and I'm once again facepalming pretty hard at my previous decisions.
I now want to make a repository for each of my projects, hosted on the server.

Question

Seen as I now have newer project files in my laptop, and older project files in the server (neither of which have been git-initialized), how do I initialize the project on both sides and push the changes made on my laptop onto the server?


What I've tried

In the server, I made a bare repo from the things I had there. I did this with:
git init + git add . + git commit -m "created on server"
And then making it a bare repo with How to convert a normal Git repository to a bare one?. Not entirely sure these are the adequate steps but they seem to work.

Then on the client side I tried the same init+add+commit, but then I also did
remote add origin git@server:project.git and attempted git push --set-upstream origin master.
That however failed with the following error:

To server:project.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'server:project.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

This seems to suggest git believes the upstream changes are more recent than what I have locally.
I then tried to rename the local master branch with git branch -m master thechanges followed by a pull of the server's main branch git pull origin master, but it fails with fatal: refusing to merge unrelated histories, and I'm not quite sure what to do about that. I was planning to then merge thechanges onto master and push it, but I'm not sure I'm even heading in the right direction anymore so that's where we are.


Solution

  • On the client side, after your init+add+commit step, here is a way to place that commit on top of the "server side" commit:

    git remote add origin <url>
    git fetch
    
    # emphasis on the --soft:
    git reset --soft origin/master
    
    git commit
    
    git push origin master