Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get number of stashes in git

My "oldest" stash in a project is something I need to re-apply from time to time. (Yes, there's a reason for this, and yes, it's terrible, but fixing the underlying issue would be more time-consuming than just using git stash for now.)

However, the oldest stash has the highest number in the list, so I can't apply it without first using git stash list to see what number it is.

Is there some way to make Git print the number of stashes it's currently holding, so that something like this would always print the last stash (in a shell supporting this kind of command-interpolation)?

git stash apply $(git stash <count-command>)

I realize I can use something like this:

 git stash list | tail -1 | awk '{print $1}' | grep -oP '\d+'

...but that's pretty hideous, so I'd like to know if there's something simpler.

like image 759
Kyle Strand Avatar asked Dec 17 '18 21:12

Kyle Strand


3 Answers

Given a small sample repository with this stashes:

> git stash list
stash@{0}: WIP on foo/master: d9184b5 ...
stash@{1}: WIP on foo/master: d9184b5 ...

this gives you the number of stash entries:

> git rev-list --walk-reflogs --count refs/stash
2

But you have to substract 1 to get the last entry :-( Thanks to @alfunx that can be done without shell arithmetic:

> git rev-list --walk-reflogs --count --skip 1 refs/stash
1

But to get the oldest stash ref directly you can use this:

> git log --walk-reflogs --pretty="%gd" refs/stash | tail -1
stash@{1}

This works in your case, because git stash apply supports both a plain number and stash@{$NUMBER} as an identifier for a stash.

like image 135
A.H. Avatar answered Nov 15 '22 09:11

A.H.


The given solutions are over-complicated.

A simple solution is just to count the number of lines given by git stash list

$ git stash list | wc -l
     65
like image 24
donatJ Avatar answered Nov 15 '22 09:11

donatJ


Since your stash is just a single commit, you do not strictly speaking need to use a stash mechanism. Once you know the SHA of your stash once, you can either cherry-pick it every time by SHA, or add a tag to it so you can cherry-pick it by label.

When cherry-picking, use the -n or --no-commit flag.

like image 40
Mad Physicist Avatar answered Nov 15 '22 09:11

Mad Physicist