Kalle Richter
Kalle Richter

Reputation: 8768

How to get a file from stash which has been save in untracked state?

Consider the following workflow: I created new (untracked) tests for a class after making changes to it which made the tests necessary and then realized that I need to change the logic of another set of tests which I thought would be a different commit, so I ran git stash save -u. Then, I realized that I need the stashed tests. How to get them as easy as possible?

My approach would be git stash branch and checkout the untracked test files (as described in How to get just one file from another branch), but that only works if no conflicts occur if the stash is applied (warning: git stash branch pops the stash anyway and messes up your working directory although failing with a verbose error message would be the way to go here).

I only want the untracked file(s) from the stash, but not the rest of it.

I'm using git 2.14.1 on Ubuntu 17.10.

Upvotes: 2

Views: 77

Answers (2)

Uriel
Uriel

Reputation: 659

I know this is an old thread but here's my 2c: Git allows you to reference any hash or symbolic hash name. I think the easiest way to do it is to use git checkout stash@{n} -- path/to/untracked/file.ext.

Upvotes: 0

dimwittedanimal
dimwittedanimal

Reputation: 656

Here's how I would solve this, based on comments.

git checkout -b <clean branch, before changes>
git stash apply

Here, you'll have tracked & untracked files. You can then use:

git reset HEAD <tracked files>
git checkout <clean branch> -- <"tracked files">

This should reset them to the clean branch state. Then you just need to:

git add <untracked files>
git commit -m "Tests"
git checkout <old, dirty branch>

Continue making changes, until ready for commit.

git commit -m "More Tests"
git merge <clean branch, before changes>

There's probably some errors here, but I hope you understand what I'm trying to say. At this point you'll likely have conflicts, that you can deal with however you deal with conflicts.

Edit: Of course, depending on how many changes you have, merging and dealing with conflicts may not be the best/fastest way to do this. If it's like one file that's changed, I'd do the same flow, but after removing the tracked files, I would just bring in the changes from the <old, dirty branch> into the <clean branch, with untracked changes, potentially already committed>.

Upvotes: 1

Related Questions