11 ms·
I've seen more stash accidents than any other kind with git. Stashing is more dangerous than committing or branching, and to me it doesn't seem to provide any a
by dahart 10y ago
I've seen more stash accidents than any other kind with git. Stashing is more dangerous than committing or branching, and to me it doesn't seem to provide any advantages... do people actually find stashing easier than branching? Is it just because when you branch you have to name it, and that causes friction? I stay away from stash.
Right from the man page: "If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms."
https://git-scm.com/docs/git-stash https://git-scm.com/docs/git-stash
--
I do like shorty. My version:
alias gits='git status -sb'
--
My next fave is rebase the current branch against it's upstream branch point:
[alias]
rearrange = "!git rebase -i $(git merge-base HEAD @{u})"
git rearrange ftw.
- ryanSrich 10y agoI use stash when I forget to branch. So I might be working and then realize I never branched. So I stash my changes, create a new branch, and then pop my changes on the new branch.
- dahart 10y agoMakes sense, but fwiw, there's a safer alternative: branch immediately, then go back to the source branch and reset. There's nothing wrong with your workflow, btw, stash works in that case, as long as you immediately pop & don't get interrupted by lunch or a phone call. Stashing is obviously providing some value that people like, it's very popular. But considering that it has extra danger, and that it's really easy to work without stash, I'm still confused why it's so popular. And fwiw, most of the stash accidents I've seen are fairly simple scenarios like you described, and some teeny tiny twist or interruption causes someone to get confused and lose their stash, or think they lost their stash, and panic.
- leephillips 10y agoI'm not a git expert (yet), but I agree. I've read the stash man page a few times and tried to imagine when I'd want to use it over the alternatives, but I never do.
- ben174 10y agoWhy stash? Why not just branch then commit?
- Grue3 10y agoBecause you might be currently not at the place where you intended to branch off. For example trying to make a bugfix on an experimental feature branch, but then you realize you should branch it off master.
- geofft 10y agoSo branch to a temporary branch, commit, checkout the branch you wanted to be on, cherry-pick the temporary branch to grab its head commit, then delete the temporary branch once you're sure you don't need it. This isn't completely safe because deleting a branch also deletes its reflogs, but it does avoid use of the stash command at all, which I find good for my own safety (because it reduces cognitive load). And it scales obviously to making multiple commits onto the temporary branch, etc.
- eridius 10y agoOr even just branch, commit, rebase onto the desired branch.
- ashark 10y agoMy #1 use of stash is as the quickest way to express "get rid of all this crap". I rarely intend to ever retrieve it.
- ianleeclark 10y agogit checkout -- . Also works well for this use case
- loeg 10y ago'git reset'.
- ashark 10y agoDoesn't do the same thing, without some more options. Stash is shorter.
- dahart 10y agoNow here's one I actually like. As an alternative to git reset, a git stash is safer, and gives you an easier way than reflog to recover if you dropped a commit you want back.
- spike021 10y agoFor one of my projects, the 'build process' requires that I use the git archive command (basically archive to .tar.gz without any git-related files/directories). git archive on its own is fine for final builds because it's based off of HEAD for the current branch, but if I want to test a build with working changes, I would either need to commit all the changes _or_ use git stash and then archive based on the state I just stashed. So in this case git stash works a lot better for a 'temporary' commit, kind of deal. It might not be optimal but I've found the process to work pretty well for this particular project's situation.
- spinningarrow 10y agoIf you're stashing your changes, that means they're just in the working copy and haven't been committed to the incorrect branch. In this case, simply create the branch and switch to it (git checkout -b branchname) and you're good. It's like it never happened ;) (remember that branches are just labels - until you commit it doesn't really matter).
- ryanSrich 10y agoTypically once I've noticed I haven't branched is after I've already added and committed.
- sammoth 10y agoThen just create the branch where you are, and afterwards go back and reset the original branch
- convolvatron 10y agoand make sure to patch up the upstream reference
- prashnts 10y agoI use `legit` aliases for this. It allows me to do `git sprout <new branch name>`, where it stashes my untracked changes, create a new branch, pop the stash and applies it. Pretty handy! legit: https://github.com/kennethreitz/legit https://github.com/kennethreitz/legit [1] [Ignore the pretentious "for humans" tagline though...]
- majewsky 10y ago`git sprout <branch-name>` looks identical to `git checkout -b <branch-name>`.
- mlvljr 10y agoWhy not branch some moment after realizing you forgot to and then go back to the (now gone a bit far) original branch and reset it to the original commit? Simple and does not require any arcane tricks.
- spinningarrow 10y agoWhile it's true that they can't be recovered through the "normal" safety mechanisms, they can certainly be recovered - that too up to 30 days in most cases. `git fsck` can help here [0]. Also when a stash is dropped, it's SHA is printed to the console. If the console buffer hasn't been cleared and you realise it soon enough, recovery can be quite straightforward. [0]: http://stackoverflow.com/questions/89332/how-to-recover-a-dropped-stash-in-git http://stackoverflow.com/questions/89332/how-to-recover-a-dr...
- dahart 10y agoYep true, and to be fair to the man page, that's the next sentence after the one I quoted. But, fsck is a big hammer, and most people I've had to help recover their stashes completely glaze over when they see commands named fsck and reflog. Some people when faced with fsck opt to give up and recreate the lost changes, it's that intimidating. And why not just avoid accidents? git's role in life is to be a safety net. Stash is hanging halfway over the edge of the net. Yes it's still possible to recover from accidents, but it's harder. That alone makes it more dangerous. It should be hard to screw up, not hard to recover.
- dasil003 10y agoYou're right of course, but whereas for a lot of purposes I understand the impulse of "I don't have time to learn this". For so many things that's the right call, but for a developer using git I would like to insert the brain worm that maybe it isn't. I consider git to be on the short list of career-long tools. The rest of the list is linux, bash and vim. Knowledge of these things has a long half life and will serve me across jobs. Even a language I've used for 10+ years in my daily work like Ruby is more likely to become obsolete within my career than git. And the thought of using git without understanding reflog is anxiety producing. The beauty of git is not in memorizing its arcane syntax, it's in understanding the elegant data model. That's my case for why every developer should at least know git-reflog. git-fsck I have to admit never having used :)
- DigitalJack 10y agopersonally I rarely stash and often it's just to get rid of a bunch of crap. rather than googling reset --hardhatheadhenry, I stash and drop. Total hack I know, but whatever.
- pkamb 10y ago> do people actually find stashing easier than branching? Branching wouldn't be enough, you'd need to commit your entire working copy to approximate a stash. I'd say it's generally a bug-prone mistake any time you commit your entire working copy (rather than staging lines/hunks on a one-commit-per-feature/bug basis). So branching and committing and pushing into a `backupForTomorrow` branch is fine, but you have to be sure to get rid of that commit via something like a mixed reset when you start working on it again. If that temporary backup commit somehow stays around in the final feature branch, a stash would be much preferred.
- randallsquared 10y agoCommitting your entire working copy to a separate branch can work just like a safe stash: $ git branch master * cool-feature-1 $ git checkout -b stash-2016.09.30T01.10 $ git add -A; git commit -m "stashing WIP for later; maybe add some commentary to remind myself what I'm doing" $ git branch master cool-feature-1 * stash-2016.09.30T01.10 $ git checkout master $ git branch * master cool-feature-1 stash-2016.09.30T01.10 # do other things # later... $ git checkout cool-feature-1 $ git merge --no-commit --no-ff stash-2016.09.30T01.10 Automatic merge went well; stopped before committing as requested $ git reset $ git status On branch cool-feature-1 Untracked files: ... And now your old WIP is back, ready to keep working, and in the meantime you could have pushed up your "stash" to a remote and grabbed it back. There might be something terribly wrong with this, but if there's not, then I don't understand why git stash doesn't do something similar to this by default.
- dahart 10y ago> Branching wouldn't be enough, you'd need to commit ... Yes, you're right. I mentioned both committing I branching. I imagine commits only as the alternative to a single stash/pop, and commits & branching as the alternative to using multiple stashes. > I'd say it's generally a bug-prone mistake any time you commit your entire working copy The workflow I'd use instead of stash is to commit, do things, then reset --soft. Exact same effect as stash, except that it's less bug-prone, there's an easier & safer recovery mechanism in case of problems. > If that temporary backup commit somehow stays around in the final feature branch, a stash would be much preferred. You're comparing making a small mess to losing work. Your opinion is your own, I'm not here to argue, but in my book the downside of losing work while using a revision control system is much larger than the downside of accidentally preserving imperfect commit refactoring. You're preferring something superficially nice over the actual safety mechanisms that is git's sole purpose.
- chocolatebunny 10y agoI mostly only stash when I want to rebase -i because rebase -i seems to complain when I have uncommitted changes.
- dahart 10y agoThat's a good example of what I'd consider to be a mildly unsafe use of stash, since if anything goes wrong you can lose unsaved changes. It's easier to forget what you're doing if you have merge conflicts during your rebase, or end up stashing something else while you rebase. The safer alternative workflow is: git commit -am "WIP" # Just throw your uncommitted changes into a commit git rebase -i origin/master # you might want to checkout my git rearrange command above git reset --soft HEAD^ # now un-stage your uncommitted changes and keep working The advantage of this is getting your uncommitted changes into a commit that can be easily recovered if anything goes wrong. Even though you get rid of the commit, this process is all stored in the reflog, and you can undo any of it easily and without resorting to fsck.
- __david__ 10y agoYou might check out "git rebase --autostash" if you haven't already.
- eatbitseveryday 10y agoIn regards to stash, yes, loss is problematic, but one can simulate it by saving the diff to a file: git diff > my-stash.diff Then you can even commit these if you like, or copy them to a safer directory. Applying them is just an invocation of `patch`.
- mwpmaybe 10y agoOr even better than patch, git apply.
- eridius 10y agoWhy did you write your rearrange with the ! form? The whole point of the leading ! is to say "don't prefix my alias with `git`", but then you go ahead and prefix your alias with `git`. You should be able to write that as rearrange = "rebase -i $(git merge-base HEAD @{u})"
- dahart 10y agoHa! You're right, that's silly, thanks! I didn't even notice. I don't remember why, it's been a long time, but I think I had a tricky pipe command to figure out the upstream branch-point a long time ago before I learned about merge-base and @{u}.
- msoucy 10y agoI was under the impression that you needed to use !-form if you wanted git to use the shell itself, and that not using it basically just does an exec on the subcommand? Is that inaccurate?
- eridius 10y agoHmm, maybe you're right. I don't know anymore. I thought it just prefixed aliases with "git " and otherwise ran them as normal, but I admit I haven't researched this topic in a long time.
- raverbashing 10y agoStashing is great Because some things are only possible while there are no changes. (I changed this one-off file for testing or debugging something, need to pull latest changes, so I stash) Stashing comes from a tool called quilt https://savannah.nongnu.org/projects/quilt https://savannah.nongnu.org/projects/quilt
- kozak 10y agoMy IDE stashes things behind the scenes quite often, allowing me to do many operations on "dirty" workspaces.
- rplst8 10y agoDo people really use stash for things they value longer than a few minutes? I've only ever used stash as a way to store changes that I made on the wrong branch. git checkout my_old_branch (wrong branch not realized yet) - work work work... git status - "oh, I'm on the wrong branch" git stash git checkout the_correct_branch git pull git stash apply (or git pop - but you lose what was on the top of the stash)
- dahart 10y ago> Do people really use stash for things they value longer than a few minutes? You'd be surprised. ;) Even a few minutes can get you into trouble though. The very last person I helped out of a stash crisis two days ago did exactly what you outlined, fully intending to stash pop immediately, and couldn't find his change and panicked. What actually happened was he'd unknowingly stashed again during his branch switch, and his first stash was there, but not on the top of the stack. GitHub desktop was auto-stashing or something. (GitHub desktop has made several very strange choices...) Anyway when my friend applied an empty stash, he thought he'd lost his changes. He called for help on a Saturday, and I tried to point him in the right direction over email, but by the time I got to a terminal to see what happened, he'd already rewritten most of his change, having decided it was a loss. OK, FWIW here are some safer alternatives to switching branches without stash: - First thing to know is that you can switch branches with uncommitted changes in your working tree. You don't have to do anything else, git will protect against conflicts, so why not always try this first? It's less work most of the time. If git complains, you can: git commit -am "WIP for the_correct_branch" git checkout the_correct_branch git cherry-pick my_old_branch git reset --soft HEAD^ # Optional, if you want to unstage ... Later ... git checkout my_old_branch git log ... Notice the leftover commit ... git reset --hard HEAD^ Or here's an alternative that doesn't leave the dangling commit for later: git commit -am "WIP" git branch work # you can always do this with uncommitted changes git reset --hard HEAD^ # still on my_old_branch here git checkout the_correct_branch git cherry-pick work git branch -d work If anything goes wrong with these workflows, my changes have been dropped in two branches, they'll be easy to find in the reflog, and the gc timer doesn't even start yet because they're still referenced. It's really hard to lose the changes this way. The only option with the stash flow if the stash gets lost while switching branches is to use fsck, and the gc timer starts immediately because the stash is not referenced. I mention the gc timer because some of the accidents I've seen are people popping stashes and only realizing later that they popped a different change than they thought they did. They way this happens is people who are beginners to git. Once you know git, it's hard to imagine popping the wrong stash and not knowing it, but I've seen it happen multiple times. This is why I advise everyone to avoid stash - for beginners, it looks deceptively and attractively simple, but is easy to get in hot water. It's also another git subsystem to learn, as if git wasn't hard enough to learn. For git experts, it's so easy to avoid using stash, there are always safer alternatives.
- warp 10y agoI tend to stash debug code, so for example I'm working on a feature, and while developing I've added a bunch of console.log()s (or pprint.pprint()s, print_r()s, whatever). Then I can do: git add --patch # include only the code I want comitted git stash --keep-index # now I can do some tests without my debug cruft git commit And then ship the feature to staging/production, if there are any remaining issues with it I still have my debug cruft in the stash. It's rarely needed, so I don't want the overhead of a branch for it. If I lose it it's also easy enough to just add the debug code I need at that moment in case the stash was cleared.
- __david__ 10y ago> do people actually find stashing easier than branching? Absolutely. I stash things all the time. I find feature branches only useful for pull requests. My own code never uses feature branches unless I'm unsure of where I'm headed with the feature—I'll need to continually come back to it and build it a little at a time. But that's very rare. > Right from the man page: "If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms." Then don't ever use those commands. I don't. Checking one of my repos: $ git stash list | wc -l 46 I just let the stash grow unbounded. Usually it's for cleaning up unfinished features or debugging when manipulating the repo (in which case it gets popped almost immediately). But often I'll just hit a point where I don't care about what I have too much, but I think it might have promise in the future and so I'll just stash and start over. One of the wonderful git commands is "git stash list -p", letting me search the diffs for code I know I've written at some point.
- jakub_g 10y agoOne of the hardest thing about git is the multitude of options and workflows. It makes it powerful but also intimidating for newbies - so many commands and flags! Having several years of git experience, I've set up on the following workflow, which avoids stashing and mixed resets. I think it's quite safe and simple. 1. using feature branches for everything (except when I'm the only developer in a given repo); I have `goto` and `forkto` and aliases for git checkout / git checkout -b 2. frequent, small commits - for backups, and to have "recovery point" for this scenario when you change one line and everything's on fire and you can't find out what's going on for next one hour 3. try to never do partial commits, always commit everything ( git add -A . && git commit ). This teaches you a discipline to do one thing at a time. If you have a sudden need to do something else, git branch, git commit, git checkout previous-branch. Or git commit, continue working, git rebase -i to reorder/squash commits later if needed. 4. for "work in progress, will come back later" commit I have an alias "wip" = "git commit -A . -m 'wip'" 5. for permanently throwing away stuff, "git reset --hard" (used rarely) 6. since I do lots of small commits, at the end of development I clean up with `git rebase -i`, squash stuff, improve commit messages if needed, maybe reorder etc. Due to 2 and 3 I basically don't use stash at all. I think however not everyone is so keen on interactive rebase as much as I do :)
- dirkdk 10y agoyeah, I find myself more doing a local commit with message WIP. I switch branches to do something else, come back, look at the log and if WIP, roll back the last commit
- phasmantistes 10y agoIn Chromium (well, actually depot_tools[1], the closest thing Chromium has to a developer SDK) we provide `git freeze`[2] and `git thaw`[3]. These behave similarly to 'stash', but instead of taking your content and putting it who-knows-where, they commit it on top of your current branch in a special FREEZE commit (or multiple commits, if you have both staged and unstaged changes) which they then know how to thaw out again. Our other tools (such as `git rebase-update`[4]) also know how to deal with FREEZE commits, and can automatically thaw them for you when you go back to working on that branch. [1] https://chromium.googlesource.com/chromium/tools/depot_tools.git https://chromium.googlesource.com/chromium/tools/depot_tools... [2] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-freeze.html https://commondatastorage.googleapis.com/chrome-infra-docs/f... [3] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-thaw.html https://commondatastorage.googleapis.com/chrome-infra-docs/f... [4] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-rebase-update.html https://commondatastorage.googleapis.com/chrome-infra-docs/f...
- dahart 10y agoBrilliant! I wonder why git stash wasn't implemented similarly in the first place.
- derefr 10y agoMy hypothesis: git was implemented assuming that—at least for large projects—you would have a local on-disk bare clone of the repo, and then multiple workdir checkouts of that bare clone sitting on different branches. The setup with a single clone containing a workdir with a .git dir inside it is a hack that's nice for "on-the-go" use-cases, but wasn't intended for serious developers contributing many changes to the same codebase. git-stash, then, is only for the use-cases that are not better solved by just leaving your WIP workdir as it is and checking out another, concurrent workdir for your new feature. Such as, for example, taking code you were accidentally writing on one branch, and "shifting it over" onto some other branch; or "moving your changes out of the way" to run some tool that is broken by them, then putting them back in place, because you really still are working on them.
- bandushrew 10y agoI frequently swap between branches, for code review, or to move temporarily to something else for a short time. I decide whether to commit what I have done or whether to stash it for now, based on what state it is in. If I am still in the exploratory stage of the work, I usually wont commit, I will just stash and come back to it later. Its a useful thing to be able to do at time when i am not yet ready to COMMIT to the changes I have made.
- dahart 10y agoOf course I can't tell what your comfort level with git it. The more expert you are, the more it doesn't matter, and you can use stash safely. I am not judging anyone or their workflows. It's the stash command that has the problem, because it circumvents git. That said, my reaction to your comment is that you're taking "commit" too seriously. ;) Nothing in git is a commitment until you push. Nothing. If you haven't heard the phrase "commit early, commit often", consider that and take it to heart. If you have work you care about and even might want to save, then you should commit it. Git was literally made for the purpose of managing multiple versions of exploratory work -- to not use commits and branches for that purpose is to not use git to its full potential. Stashing things you care about for some later time strikes me as the kind of use of stash that is the most prone to data loss. But again, if you're comfortable using fsck, none of this applies to you.
- bandushrew 10y agoIf code is important enough to me that I care whether or not I lose it, I commit and push. I prefer to commit discrete change sets (not features, or stories, just a discrete set of changes that achieve a piece of what I am wanting, dont break the code base and dont break the build). I have heard that phrase, I live by it and encourage others to do the same. it is especially important when working as a part of a bigger team on the same area of the code. Teams that commit early and often are happy teams :) OTOH I use stash constantly, multiple times every day, when switching between branches, because sometimes its just handy to be able to put stuff aside to look at something else. I dont recall ever losing code because of it, but it is certainly possible and its not hard to see how it could happen.
- kkirsche 10y agoHonestly I stash only cause I don't fully understand how to branch and bring my changes with me when I realize I should have branched earlier
- dahart 10y agoThis is a great answer, honestly, and you're not alone. FWIW, here's how. Since stash only captures uncommitted changes, I assume you're working on master and want to create a feature branch, and you've already made some changes for the branch. git checkout -b myFeature That's it. Uncommitted changes aren't in a branch yet, so they don't have to be stashed before you make a new one. You can always start a branch from wherever you are, and switch to it, and your changes will be right there. Now you can commit, and your commit will be on the branch myFeature. BTW, you can switch branches without stashing too. Git will prevent you from messing up your uncommitted changes. If that happens, then you can commit or stash first. The safest course of action is always to commit any changes first before you do anything. It's also easy to build your feature branch if you have both committed and uncommitted changes already, or if you want to base your feature branch off a different branch than the one you're working in. I'm already spamming you, so just say so if you'd like me to outline those.
- kkirsche 10y agoThank you for explaining this! I didn't know that and will start incorporating that into my workflow :) thanks for teaching me something new!