Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save without committing to remote repository in Git

Tags:

git

I am facing a problem like this. I have modified a file and tested it. Let us call this state "last good state".

Then I modify some more code. Now some manager kind of guy tells me to commit and deploy what I had tested. So what I want is to save my file safely on the remote repository (I don't want a hard disk crash to destroy my changes after last good state), revert to last good state, and then commit the last good state.

In other VCS, I had the option of saving file to remote server without committing. In Git there is no such option. I can stash but that is on my local disk and is not safe from hard disk crashes. Anyone have any ideas?

like image 699
Apurva Singh Avatar asked Dec 25 '22 00:12

Apurva Singh


2 Answers

You can create a backup-branch at the same point of code..than you push this backup-branch and keep working at the other branch.

If anything goes wrong, you just checkout to your backup-branch

git branch backup
git checkout backup
git push origin backup <- at this point everything is saved at your remote

git checkout YOUR_OLD_BRANCH (develop maybe)

git checkout backup <- anytime that you want to get your "last good state"

I hope that this is what your are looking for

like image 107
Lucas Batista Gabriel Avatar answered May 21 '23 01:05

Lucas Batista Gabriel


The first step is to commit the good changes, which need to be deployed. Do:

git add foo

for any files you want to include in that commit. If you only want to include partial changes for a file in the good commit, then do:

git add --patch foo

Then commit and push:

git commit -m "Foo the bar because baz"
git push

As you mentioned, you could do git stash at this point, but that would only save your changes locally. Instead, switch to a new branch, commit your changes there, and push:

git checkout -b temp
git add .
git commit -m "Temp"
git push origin temp

Since you've committed on a separate branch, then any CI/CD you have set up won't be triggered by your temporary changes, but you are still able to push them to the server.


To automate the latter process, you could define an alias:

git config alias.server-stash "! git checkout -b $1; git add .; git commit -m 'Temp'; git push $2 $1"

Then use it as:

git server-stash temp origin

This situation is a good lesson in the VCS mantra to Commit Early, Commit Often. Especially since you have finished testing the previous changes, before moving on to something else, commit! However, even if you hadn't finished testing, still feel free to commit. Commits are local in Git, and you don't have to push them if you don't want to. (And judicious use of branches will ensure that commits that aren't ready don't get in your way.)

like image 41
Scott Weldon Avatar answered May 21 '23 02:05

Scott Weldon