Skip to content

Commit a9f640f

Browse files
committed
Filter already-merged commits from status and compare
When PRs at the bottom of a stack are merged via the GitHub UI (squash or merge commit), the remote named stack branch still contains those commits. Because their SHAs aren't ancestors of the target after a squash merge, getCommitStack's range walk can't filter them out, so status shows a spurious "N remote-only commits" warning and compare renders them as [remote-only] rows. Use git cherry to detect commits whose patches are already present in the target branch, regardless of merge strategy. Add getAlreadyAppliedShas to GitClient (implemented via git cherry in CliGitClient) and filter both local and remote stacks in getStatusString, getCompareString, and appendUniqueCommitsSummary. Merged commits are hidden from the output with a message like "3 commits already merged into main (not shown). Run jaspr rebase to clean up." When all commits are merged, status and compare return a single-line message instead of rendering an empty stack. commit-id: I8082a27e
1 parent 3dd2fcd commit a9f640f

4 files changed

Lines changed: 182 additions & 9 deletions

File tree

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,21 @@ class CliGitClient(
875875
}
876876
}
877877

878+
override fun getAlreadyAppliedShas(upstream: String, head: String): Set<String> {
879+
logger.trace("getAlreadyAppliedShas {} {}", upstream, head)
880+
return try {
881+
executeCommand(listOf("git", "cherry", upstream, head))
882+
.output
883+
.lines
884+
.filter { it.startsWith("- ") }
885+
.map { it.removePrefix("- ").trim() }
886+
.toSet()
887+
} catch (e: Exception) {
888+
logger.debug("Failed to run git cherry {} {}", upstream, head, e)
889+
emptySet()
890+
}
891+
}
892+
878893
override fun mergeTreeWriteTree(
879894
base: String,
880895
ours: String,

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,13 @@ interface GitClient {
291291
*/
292292
fun patchId(sha: String): String?
293293

294+
/**
295+
* Returns full SHAs of commits reachable from [head] whose patches are already present in
296+
* [upstream] (equivalent to the `-` lines in `git cherry <upstream> <head>`). Used to detect
297+
* commits that have been squash-merged or cherry-picked into the target branch.
298+
*/
299+
fun getAlreadyAppliedShas(upstream: String, head: String): Set<String> = emptySet()
300+
294301
/**
295302
* Returns the tree SHA for [ref] (equivalent to `git rev-parse <ref>^{tree}`). Throws if [ref]
296303
* doesn't resolve to a commit. Useful for comparing tree contents across refs without walking

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

Lines changed: 100 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,27 @@ class GitJaspr(
252252
if (navState != null) refSpec.copy(localRef = navState.headBeforeDetach) else refSpec
253253

254254
val remoteBranches = queries.getRemoteBranches()
255-
val stack = queries.getCommitStack(effectiveRefSpec.localRef, effectiveRefSpec.remoteRef)
256-
if (stack.isEmpty()) return theme.muted("Stack is empty.") + "\n"
255+
val rawStack = queries.getCommitStack(effectiveRefSpec.localRef, effectiveRefSpec.remoteRef)
256+
if (rawStack.isEmpty()) {
257+
return theme.muted("Stack is empty.") + "\n"
258+
}
259+
260+
val upstream = "$remoteName/${effectiveRefSpec.remoteRef}"
261+
val stack = filterAlreadyApplied(rawStack, upstream, effectiveRefSpec.localRef)
262+
val numAlreadyMerged = rawStack.size - stack.size
263+
264+
if (stack.isEmpty()) {
265+
val mergedDescription =
266+
if (numAlreadyMerged == 1) {
267+
"The commit in your stack has"
268+
} else {
269+
"All $numAlreadyMerged commits in your stack have"
270+
}
271+
return theme.warning(
272+
"$mergedDescription been merged into ${effectiveRefSpec.remoteRef}. " +
273+
"Run `jaspr rebase` to clean up."
274+
) + "\n"
275+
}
257276

258277
val statuses = getRemoteCommitStatuses(stack, remoteBranches, queries)
259278
val commitsWithDuplicateIds =
@@ -271,6 +290,7 @@ class GitJaspr(
271290
statuses,
272291
commitsWithDuplicateIds,
273292
numCommitsBehindBase,
293+
numAlreadyMerged,
274294
effectiveRefSpec,
275295
stack,
276296
remoteBranches,
@@ -284,6 +304,7 @@ class GitJaspr(
284304
statuses: List<RemoteCommitStatus>,
285305
commitsWithDuplicateIds: Map<String, List<RemoteCommitStatus>>,
286306
numCommitsBehindBase: Int,
307+
numAlreadyMerged: Int,
287308
refSpec: RefSpec,
288309
stack: List<Commit>,
289310
remoteBranches: List<RemoteBranch>,
@@ -344,6 +365,16 @@ class GitJaspr(
344365

345366
appendNamedStackInfo(stack, remoteBranches, theme, queries)
346367

368+
if (numAlreadyMerged > 0) {
369+
appendLine()
370+
appendLine(
371+
theme.warning(
372+
"$numAlreadyMerged ${commitOrCommits(numAlreadyMerged)} already merged " +
373+
"into ${refSpec.remoteRef} (not shown). " +
374+
"Run `jaspr rebase` to clean up."
375+
)
376+
)
377+
}
347378
if (numCommitsBehindBase > 0) {
348379
appendLine()
349380
appendLine(
@@ -460,14 +491,17 @@ class GitJaspr(
460491
val targetRef =
461492
RemoteNamedStackRef.parse(stackName, config.remoteNamedStackBranchPrefix)?.targetRef
462493
?: return
494+
val upstream = "$remoteName/$targetRef"
463495
val remoteStack =
464496
try {
465-
queries.getCommitStack("$remoteName/$stackName", targetRef)
497+
val raw = queries.getCommitStack("$remoteName/$stackName", targetRef)
498+
filterAlreadyApplied(raw, upstream, "$remoteName/$stackName")
466499
} catch (e: Exception) {
467500
logger.debug("Failed to walk remote stack '{}': {}", stackName, e.message)
468501
return
469502
}
470-
val localIds = localStack.mapNotNull(Commit::id).toSet()
503+
val filteredLocal = filterAlreadyApplied(localStack, upstream, localStack.last().hash)
504+
val localIds = filteredLocal.mapNotNull(Commit::id).toSet()
471505
val remoteIds = remoteStack.mapNotNull(Commit::id).toSet()
472506
val remoteOnly = (remoteIds - localIds).size
473507
val localOnly = (localIds - remoteIds).size
@@ -668,11 +702,14 @@ class GitJaspr(
668702
val effectiveLocalRef = navState?.headBeforeDetach ?: refSpec.localRef
669703
val cursorSha = navState?.stack?.getOrNull(navState.cursorIndex)?.sha
670704

671-
val localStack = gitClient.getCommitStack(remoteName, effectiveLocalRef, refSpec.remoteRef)
672-
if (localStack.isEmpty()) return theme.muted("Stack is empty.") + "\n"
705+
val rawLocalStack =
706+
gitClient.getCommitStack(remoteName, effectiveLocalRef, refSpec.remoteRef)
707+
if (rawLocalStack.isEmpty()) {
708+
return theme.muted("Stack is empty.") + "\n"
709+
}
673710

674711
val stackName =
675-
when (val result = getExistingStackName(localStack, remoteBranches)) {
712+
when (val result = getExistingStackName(rawLocalStack, remoteBranches)) {
676713
is Found -> result.name
677714
is MultipleStacksContainCommit ->
678715
throw GitJasprException(
@@ -686,14 +723,51 @@ class GitJaspr(
686723
}
687724
val namedStackRef =
688725
checkNotNull(RemoteNamedStackRef.parse(stackName, config.remoteNamedStackBranchPrefix))
689-
val remoteStack =
690-
gitClient.getCommitStack(remoteName, "$remoteName/$stackName", namedStackRef.targetRef)
726+
val upstream = "$remoteName/${namedStackRef.targetRef}"
727+
val rawRemoteStack =
728+
gitClient.getCommitStack(
729+
remoteName,
730+
"$remoteName/$stackName",
731+
namedStackRef.targetRef,
732+
)
733+
val localStack = filterAlreadyApplied(rawLocalStack, upstream, effectiveLocalRef)
734+
val remoteStack = filterAlreadyApplied(rawRemoteStack, upstream, "$remoteName/$stackName")
735+
736+
val mergedLocalIds =
737+
rawLocalStack.mapNotNull(Commit::id).toSet() - localStack.mapNotNull(Commit::id).toSet()
738+
val mergedRemoteIds =
739+
rawRemoteStack.mapNotNull(Commit::id).toSet() -
740+
remoteStack.mapNotNull(Commit::id).toSet()
741+
val numAlreadyMerged = (mergedLocalIds + mergedRemoteIds).size
742+
743+
if (localStack.isEmpty() && remoteStack.isEmpty() && numAlreadyMerged > 0) {
744+
val mergedDescription =
745+
if (numAlreadyMerged == 1) {
746+
"The commit has"
747+
} else {
748+
"All $numAlreadyMerged commits have"
749+
}
750+
return theme.warning(
751+
"$mergedDescription been merged into ${namedStackRef.targetRef}. " +
752+
"Nothing to compare. Run `jaspr rebase` to clean up."
753+
) + "\n"
754+
}
691755

692756
return DivergenceClassifier(getJasprDir(), gitClient).use { classifier ->
693757
val rows = alignStacks(localStack, remoteStack, classifier)
694758
buildString {
695759
if (navState != null) appendLine(navBanner(navState, theme))
696760
append(renderCompare(rows, "$remoteName/$stackName", theme, cursorSha = cursorSha))
761+
if (numAlreadyMerged > 0) {
762+
appendLine()
763+
appendLine(
764+
theme.warning(
765+
"$numAlreadyMerged ${commitOrCommits(numAlreadyMerged)} already " +
766+
"merged into ${namedStackRef.targetRef} (not shown). " +
767+
"Run `jaspr rebase` to clean up."
768+
)
769+
)
770+
}
697771
}
698772
}
699773
}
@@ -2775,6 +2849,23 @@ class GitJaspr(
27752849

27762850
private fun commitOrCommits(count: Int) = if (count == 1) "commit" else "commits"
27772851

2852+
/**
2853+
* Removes commits from [commits] whose patches are already present in [upstream], as determined
2854+
* by `git cherry`. Full SHAs from `git cherry` are matched against abbreviated [Commit.hash]
2855+
* values via prefix comparison.
2856+
*/
2857+
private fun filterAlreadyApplied(
2858+
commits: List<Commit>,
2859+
upstream: String,
2860+
head: String,
2861+
): List<Commit> {
2862+
val appliedShas = gitClient.getAlreadyAppliedShas(upstream, head)
2863+
if (appliedShas.isEmpty()) return commits
2864+
return commits.filter { commit ->
2865+
appliedShas.none { sha -> sha.startsWith(commit.hash) }
2866+
}
2867+
}
2868+
27782869
private fun prOrPrs(count: Int) = if (count == 1) "pr" else "prs"
27792870

27802871
/**

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3731,6 +3731,66 @@ interface GitJasprTest {
37313731
}
37323732
}
37333733

3734+
@Status
3735+
@Compare
3736+
@Test
3737+
fun `status and compare hide commits already merged into target`() {
3738+
withTestSetup(useFakeRemote) {
3739+
createCommitsFrom(
3740+
testCase {
3741+
repository {
3742+
commit { title = "one" }
3743+
commit { title = "two" }
3744+
commit { title = "three" }
3745+
commit { title = "four" }
3746+
commit {
3747+
title = "five"
3748+
localRefs += "development"
3749+
}
3750+
}
3751+
}
3752+
)
3753+
3754+
push()
3755+
3756+
// Simulate squash-merging the bottom 3 PRs into main by cherry-picking them onto
3757+
// main. Cherry-picks have the same patch-id as the originals, so git cherry detects
3758+
// them as already applied.
3759+
val stackCommits = localGit.logRange("$remoteName/main", "development")
3760+
val bottomThree = stackCommits.take(3)
3761+
3762+
localGit.checkout("$remoteName/main")
3763+
for (commit in bottomThree) {
3764+
localGit.cherryPick(commit)
3765+
}
3766+
localGit.push(listOf(RefSpec("+HEAD", "main")), remoteName)
3767+
localGit.checkout("development")
3768+
localGit.fetch(remoteName)
3769+
3770+
// Status should show only the 2 unmerged commits
3771+
val status = getAndPrintStatusString()
3772+
val statusRows = status.lines().filter { it.startsWith("[") }
3773+
assertEquals(2, statusRows.size, "Expected 2 commit rows in status, got:\n$status")
3774+
assertContains(status, ": five")
3775+
assertContains(status, ": four")
3776+
assertContains(status, "3 commits already merged into main (not shown)")
3777+
assertContains(status, "3 commits behind main")
3778+
3779+
// Compare should also show only the 2 unmerged commits
3780+
val compare = getAndPrintCompareString()
3781+
val compareLines = compare.lines().filter { it.contains("five") || it.contains("four") }
3782+
assertEquals(
3783+
2,
3784+
compareLines.size,
3785+
"Expected 2 rows in compare for four and five, got:\n$compare",
3786+
)
3787+
assertFalse(compare.contains(": one"), "Should not show merged commit 'one'")
3788+
assertFalse(compare.contains(": two"), "Should not show merged commit 'two'")
3789+
assertFalse(compare.contains(": three"), "Should not show merged commit 'three'")
3790+
assertContains(compare, "3 commits already merged into main (not shown)")
3791+
}
3792+
}
3793+
37343794
@Status
37353795
@Test
37363796
fun `status stack check all mergeable`() {

0 commit comments

Comments
 (0)