Skip to content

Commit ee91e55

Browse files
committed
Let jaspr goto accept a commit hash, not just a position
Picking a commit out of `jaspr status` meant counting rows to turn "I want <hash>" into a position. `jaspr goto` now accepts a commit hash (or any commit-ish that resolves to a stack member) in addition to a numeric position. navigateTo(position) is refactored to share the move logic with a new navigateToDestination(dest), which disambiguates: a valid in-range position is treated as a position (so "-1" is never git-resolved), and anything else is resolved as a commit and matched against the stack. This keeps ordinary positions working while also handling an all-digit abbreviated hash correctly. A destination that is neither an in-range position nor a stack commit errors cleanly, and an out-of-range number still reports the position range error. commit-id: I50fb77f0
1 parent de93aaf commit ee91e55

3 files changed

Lines changed: 165 additions & 17 deletions

File tree

‎git-jaspr/src/main/kotlin/sims/michael/gitjaspr/Cli.kt‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1496,10 +1496,16 @@ class Top :
14961496

14971497
class Goto :
14981498
GitJasprSubcommand(
1499-
helpText = "Move to position N in the stack (1 = bottom, -1 = top, -2 = second from top)"
1499+
helpText =
1500+
"Move to a stack position (1 = bottom, -1 = top, -2 = second from top) " +
1501+
"or a commit hash in the stack"
15001502
) {
15011503
private val targetOpts by TargetOptions()
1502-
private val position by argument("n").int()
1504+
private val destination by
1505+
argument(
1506+
"commit-or-position",
1507+
help = "A commit hash in the stack, or a position (e.g. 2, -1)",
1508+
)
15031509

15041510
override suspend fun doRun() {
15051511
val jaspr = appWiring.gitJaspr
@@ -1511,7 +1517,7 @@ class Goto :
15111517
}
15121518
jaspr.clearNavState()
15131519
}
1514-
when (val result = jaspr.navigateTo(targetOpts.target, position)) {
1520+
when (val result = jaspr.navigateToDestination(targetOpts.target, destination)) {
15151521
NavMoveResult.NoSession -> renderer.info { "Already at the top of the stack." }
15161522
is NavMoveResult.MovedWithin -> print(jaspr.getNavPositionString(result.state, theme))
15171523
is NavMoveResult.ReachedTop -> printReachedTop(jaspr, result)

‎git-jaspr/src/main/kotlin/sims/michael/gitjaspr/GitJaspr.kt‎

Lines changed: 70 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3062,29 +3062,85 @@ class GitJaspr(
30623062
* above the current cursor; checks out directly when below. If the target is the top of the
30633063
* stack, ends the session and restores the source branch (mirroring [navigateToTop]).
30643064
*/
3065-
fun navigateTo(targetRef: String, position: Int): NavMoveResult {
3066-
requireForUser(position != 0) {
3067-
"Position must not be zero. Use positive N (1 = bottom) or negative N (-1 = top)."
3065+
fun navigateTo(targetRef: String, position: Int): NavMoveResult =
3066+
navigateToPosition(reconciledOrInitNavState(targetRef), position)
3067+
3068+
/**
3069+
* Navigate to a stack [destination] given as either a position (see [navigateTo]) or a
3070+
* commit-ish (hash, abbreviated hash, etc.) that resolves to a commit in the stack. A valid
3071+
* in-range position is honored as a position; anything else is resolved as a commit, so an
3072+
* all-digit abbreviated hash still lands on the right commit rather than being read as a
3073+
* position. Errors cleanly when [destination] is neither.
3074+
*/
3075+
fun navigateToDestination(targetRef: String, destination: String): NavMoveResult {
3076+
val state = reconciledOrInitNavState(targetRef)
3077+
val size = state.stack.size
3078+
val asInt = destination.toIntOrNull()
3079+
val inPositionRange = asInt != null && (asInt in 1..size || asInt in -size..-1)
3080+
3081+
// A commit match wins only when the argument isn't already a valid in-range position, so
3082+
// ordinary positions (including "-1") are never handed to git for resolution.
3083+
if (!inPositionRange) {
3084+
val commitIndex = tryResolveStackIndex(state.stack, destination)
3085+
if (commitIndex != null) {
3086+
val sha = state.stack[commitIndex].sha.take(7)
3087+
return navigateToTarget(state, commitIndex, sha, "You are already on commit $sha.")
3088+
}
3089+
}
3090+
return if (asInt != null) {
3091+
// Numeric but not a stack commit: position handling gives the range / zero error.
3092+
navigateToPosition(state, asInt)
3093+
} else {
3094+
throw GitJasprException("'$destination' is not a commit in the current stack.")
30683095
}
3096+
}
30693097

3098+
private fun reconciledOrInitNavState(targetRef: String): NavState {
30703099
val existingState = readNavState()
3071-
val state =
3072-
if (existingState != null && gitClient.isHeadDetached()) {
3073-
reconcile(existingState, targetRef)
3074-
} else {
3075-
initNavState(targetRef)
3076-
}
3100+
return if (existingState != null && gitClient.isHeadDetached()) {
3101+
reconcile(existingState, targetRef)
3102+
} else {
3103+
initNavState(targetRef)
3104+
}
3105+
}
3106+
3107+
/**
3108+
* Resolve [commitish] to the index of the matching entry in [stack], or null when it doesn't
3109+
* resolve to a commit that is present in the stack.
3110+
*/
3111+
private fun tryResolveStackIndex(stack: List<StackEntry>, commitish: String): Int? {
3112+
val resolvedHash =
3113+
runCatching { gitClient.log(commitish, 1).single().hash }.getOrNull() ?: return null
3114+
return stack.indexOfFirst { entry -> entry.sha == resolvedHash }.takeIf { it >= 0 }
3115+
}
30773116

3117+
private fun navigateToPosition(state: NavState, position: Int): NavMoveResult {
3118+
requireForUser(position != 0) {
3119+
"Position must not be zero. Use positive N (1 = bottom) or negative N (-1 = top)."
3120+
}
30783121
val targetIndex = resolvePosition(position, state.stack.size)
3079-
val cursor = state.cursorIndex
3122+
return navigateToTarget(
3123+
state,
3124+
targetIndex,
3125+
reflogLabel = "$position",
3126+
alreadyThereMessage = "Already at position $position of the stack.",
3127+
)
3128+
}
30803129

3081-
requireForUser(targetIndex != cursor) { "Already at position $position of the stack." }
3130+
private fun navigateToTarget(
3131+
state: NavState,
3132+
targetIndex: Int,
3133+
reflogLabel: String,
3134+
alreadyThereMessage: String,
3135+
): NavMoveResult {
3136+
val cursor = state.cursorIndex
3137+
requireForUser(targetIndex != cursor) { alreadyThereMessage }
30823138

30833139
if (targetIndex < cursor) {
30843140
val target = gitClient.log(state.stack[targetIndex].sha, 1).single()
30853141
gitClient.checkout(
30863142
state.stack[targetIndex].sha,
3087-
reflogMessage = "jaspr nav to $position (${target.shortMessage})",
3143+
reflogMessage = "jaspr nav to $reflogLabel (${target.shortMessage})",
30883144
)
30893145
val newState = state.copy(cursorIndex = targetIndex)
30903146
writeNavState(newState)
@@ -3097,13 +3153,13 @@ class GitJaspr(
30973153
replayEntries(
30983154
state.stack,
30993155
(cursor + 1)..targetIndex,
3100-
reflogCommand = "nav to $position",
3156+
reflogCommand = "nav to $reflogLabel",
31013157
)
31023158
return if (targetIndex == updatedStack.lastIndex) {
31033159
val finalCommit = gitClient.log(GitClient.HEAD, 1).single()
31043160
endNavSession(
31053161
state.copy(stack = updatedStack),
3106-
reflogMessage = "jaspr nav to $position (${finalCommit.shortMessage})",
3162+
reflogMessage = "jaspr nav to $reflogLabel (${finalCommit.shortMessage})",
31073163
)
31083164
reachedTop(state, updatedStack, replayedCount = replayedCount)
31093165
} else {

‎git-jaspr/src/test/kotlin/sims/michael/gitjaspr/GitJasprTest.kt‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,92 @@ interface GitJasprTest {
722722
}
723723
}
724724

725+
@Nav
726+
@Test
727+
fun `goto by abbreviated commit hash checks out that commit`() {
728+
withTestSetup(useFakeRemote) {
729+
createCommitsFrom(
730+
testCase {
731+
repository {
732+
commit { title = "one" }
733+
commit { title = "two" }
734+
commit {
735+
title = "three"
736+
localRefs += "development"
737+
}
738+
}
739+
checkout = "development"
740+
}
741+
)
742+
localGit.fetch(remoteName)
743+
// Stack is bottom-to-top: [one, two, three].
744+
val two = localGit.getCommitStack(remoteName, GitClient.HEAD, DEFAULT_TARGET_REF)[1]
745+
746+
val result =
747+
assertIs<NavMoveResult.MovedWithin>(
748+
gitJaspr.navigateToDestination(DEFAULT_TARGET_REF, two.hash.take(7))
749+
)
750+
751+
assertEquals(1, result.state.cursorIndex)
752+
assertTrue(localGit.isHeadDetached())
753+
assertEquals(two.hash, localGit.log(GitClient.HEAD, 1).single().hash)
754+
}
755+
}
756+
757+
@Nav
758+
@Test
759+
fun `goto by position still works through navigateToDestination`() {
760+
withTestSetup(useFakeRemote) {
761+
createCommitsFrom(
762+
testCase {
763+
repository {
764+
commit { title = "one" }
765+
commit { title = "two" }
766+
commit {
767+
title = "three"
768+
localRefs += "development"
769+
}
770+
}
771+
checkout = "development"
772+
}
773+
)
774+
// Position 1 is the bottom of the stack.
775+
val result =
776+
assertIs<NavMoveResult.MovedWithin>(
777+
gitJaspr.navigateToDestination(DEFAULT_TARGET_REF, "1")
778+
)
779+
assertEquals(0, result.state.cursorIndex)
780+
}
781+
}
782+
783+
@Nav
784+
@Test
785+
fun `goto with a commit not in the stack reports a clean error`() {
786+
withTestSetup(useFakeRemote) {
787+
createCommitsFrom(
788+
testCase {
789+
repository {
790+
commit { title = "one" }
791+
commit {
792+
title = "two"
793+
localRefs += "development"
794+
}
795+
}
796+
checkout = "development"
797+
}
798+
)
799+
localGit.fetch(remoteName)
800+
// The base commit is resolvable but sits below the stack, so it isn't a member.
801+
val base = localGit.log("$remoteName/$DEFAULT_TARGET_REF", 1).single().hash
802+
803+
val exception =
804+
assertThrows<GitJasprException> {
805+
gitJaspr.navigateToDestination(DEFAULT_TARGET_REF, base.take(7))
806+
}
807+
assertContains(exception.message.orEmpty(), "not a commit in the current stack")
808+
}
809+
}
810+
725811
@Nav
726812
@Test
727813
fun `goto current position is rejected`() {

0 commit comments

Comments
 (0)