Git Push to a Live Server Without Crying
Sometimes you just need to get code up to your server. Perhaps Github, Gitlab, [ENTER YOUR FAVORITE VCS HERE] is down and you’re trying to fight a fire, but you depend on your central repo. Fortunately, git is not SVN, and you could push directly to your server because it’s decentralized.
Most solutions are not as straight-forward. My solution is currently manual but it involves only a few straightforward commands. It’s done me good for many years.
It goes like this:
- Add a remote of your server with a SSH URL and the path to your git repo on the server
- Checkout a new temporary branch based off of the commit you’re currently on
- Git push
- Checkout your previous branch
- Delete temporary branch
It’s that simple. Here’s how the commands would look.
Add Remote
Note the colon. Very important because that separates your hostname from the file path on your server.
$ git remote add server ssh://server_hostname:/path/to/git/repo
Checkout new Temporary Branch
Checking out a new temporary branch from your current commit allows your code to be in a stable state until you switch over to the latest updates. Otherwise, what could happen is that you checkout an older version during the update and that could cause problems for clients interacting with your code.
Make sure that your repo is clean before you create the new branch or else the push will fail.
$ git checkout -b temp
Push your changes
$ git push server
Checkout Previous Branch and Delete the Temporary one
The idea behind deleting the branch is that in the future you don’t want to switch back to an old commit during the transition phase of pushing your changes to the server. By deleting the branch you will always need to create a new branch which will point to the latest commit before your changes as described above.
$ git checkout - # shorthand for previous branch, git checkout @{-1}
$ git branch -d temp
Now, keep pushing forward.