Skip to content

Commit 86e612b

Browse files
dkattanCopilot
andcommitted
feat: improve Move-Commit destination handling
Add an explicit -CreateDestinationBranch/-BaseRef path for Move-Commit while keeping the default missing-destination behavior strict and actionable. Also add Pester coverage for the new branch-creation flow and document it in the README. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent b494e95 commit 86e612b

3 files changed

Lines changed: 251 additions & 25 deletions

File tree

‎GitSplit.Tests.ps1‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,17 @@ Import-Module '$escapedManifestPath' -Force
641641
}
642642

643643
Describe "Move-Commit" {
644+
It "throws an actionable error when the destination branch is missing" {
645+
Push-Location $script:TempRepoPath
646+
try {
647+
{ Move-Commit -CommitRef HEAD -DestinationBranch 'missing-dest' } |
648+
Should -Throw -ExpectedMessage "*Destination branch 'missing-dest' does not exist locally or on origin.*git branch missing-dest <base-ref>*-CreateDestinationBranch -BaseRef <base-ref>*"
649+
}
650+
finally {
651+
Pop-Location
652+
}
653+
}
654+
644655
It "cherry-picks HEAD to another branch without switching the current branch" {
645656
Push-Location $script:TempRepoPath
646657
try {
@@ -674,6 +685,34 @@ Import-Module '$escapedManifestPath' -Force
674685
}
675686
}
676687

688+
It "can create the destination branch from an explicit base ref" {
689+
Push-Location $script:TempRepoPath
690+
try {
691+
$sourceBranch = (git rev-parse --abbrev-ref HEAD).Trim()
692+
$sourceBranch | Should -Not -Be 'HEAD'
693+
694+
'created-dest-line' | Add-Content -Path 'a.txt'
695+
git add a.txt | Out-Null
696+
$msg = "Created destination move $(New-Guid)"
697+
git commit -m $msg | Out-Null
698+
$LASTEXITCODE | Should -Be 0
699+
700+
$baseCommit = (git rev-parse HEAD~1).Trim()
701+
702+
$result = Move-Commit -CommitRef HEAD -DestinationBranch 'created-dest' -CreateDestinationBranch -BaseRef 'HEAD~1'
703+
$result | Should -Be 'created-dest'
704+
705+
(git rev-parse --abbrev-ref HEAD).Trim() | Should -Be $sourceBranch
706+
(git rev-parse created-dest^).Trim() | Should -Be $baseCommit
707+
708+
$destSubjects = (git log created-dest -n 50 --pretty=format:%s) -join "`n"
709+
$destSubjects | Should -Match ([regex]::Escape($msg))
710+
}
711+
finally {
712+
Pop-Location
713+
}
714+
}
715+
677716
It "can write a reviewable Move-Commit script without executing it" {
678717
$scriptPath = $null
679718
Push-Location $script:TempRepoPath
@@ -716,6 +755,47 @@ Import-Module '$escapedManifestPath' -Force
716755
}
717756
}
718757

758+
It "can generate and execute a Move-Commit script that creates the destination branch" {
759+
$scriptPath = $null
760+
Push-Location $script:TempRepoPath
761+
try {
762+
'script-created-line' | Add-Content -Path 'a.txt'
763+
git add a.txt | Out-Null
764+
$msg = "Scripted created destination $(New-Guid)"
765+
git commit -m $msg | Out-Null
766+
$LASTEXITCODE | Should -Be 0
767+
768+
$baseCommit = (git rev-parse HEAD~1).Trim()
769+
770+
$scriptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("move-commit-create-" + (New-Guid) + ".ps1")
771+
if (Test-Path $scriptPath) {
772+
Remove-Item -Path $scriptPath -Force
773+
}
774+
775+
Move-Commit -CommitRef HEAD -DestinationBranch 'script-created-dest' -CreateDestinationBranch -BaseRef 'HEAD~1' -OutputScriptPath $scriptPath | Out-Null
776+
777+
$scriptText = Get-Content -Path $scriptPath -Raw
778+
$scriptText | Should -Match ([regex]::Escape("`$destinationCreateBaseRef = 'HEAD~1'"))
779+
$scriptText | Should -Match ([regex]::Escape("`$destinationCreateBaseCommit = '$baseCommit'"))
780+
$scriptText | Should -Match ([regex]::Escape('& git worktree add -b $destinationBranch $destWorktreePath $destinationCreateBaseCommit'))
781+
782+
$result = & $scriptPath
783+
784+
$result | Should -Be 'script-created-dest'
785+
(git rev-parse --abbrev-ref HEAD).Trim() | Should -Be 'main'
786+
(git rev-parse script-created-dest^).Trim() | Should -Be $baseCommit
787+
788+
$destSubjects = (git log script-created-dest -n 50 --pretty=format:%s) -join "`n"
789+
$destSubjects | Should -Match ([regex]::Escape($msg))
790+
}
791+
finally {
792+
if ($scriptPath -and (Test-Path $scriptPath)) {
793+
Remove-Item -Path $scriptPath -Force
794+
}
795+
Pop-Location
796+
}
797+
}
798+
719799
It "can execute a generated Move-Commit script later" {
720800
$scriptPath = $null
721801
Push-Location $script:TempRepoPath
@@ -895,6 +975,17 @@ Import-Module '$escapedManifestPath' -Force
895975
Pop-Location
896976
}
897977
}
978+
979+
It "requires -BaseRef when creating the destination branch" {
980+
Push-Location $script:TempRepoPath
981+
try {
982+
{ Move-Commit -CommitRef HEAD -DestinationBranch 'missing-base-ref' -CreateDestinationBranch } |
983+
Should -Throw -ExpectedMessage '*requires -BaseRef when -CreateDestinationBranch is specified*'
984+
}
985+
finally {
986+
Pop-Location
987+
}
988+
}
898989
}
899990

900991
Describe "Deterministic test hooks" {

‎GitSplit.psm1‎

Lines changed: 154 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,24 @@ function Test-GitRefExists {
204204
throw "Failed to inspect git ref '$Ref'.`n$($query.Output)"
205205
}
206206

207+
function Get-MoveCommitMissingDestinationBranchMessage {
208+
[CmdletBinding()]
209+
[OutputType([string])]
210+
param(
211+
[Parameter(Mandatory = $true)]
212+
[ValidateNotNullOrEmpty()]
213+
[string]$DestinationBranch
214+
)
215+
216+
return @(
217+
"Destination branch '$DestinationBranch' does not exist locally or on origin."
218+
"Create it first with:"
219+
" git branch $DestinationBranch <base-ref>"
220+
"Or rerun with:"
221+
" Move-Commit -DestinationBranch $DestinationBranch -CreateDestinationBranch -BaseRef <base-ref>"
222+
) -join [Environment]::NewLine
223+
}
224+
207225
function Test-GitCommitIsAncestor {
208226
[CmdletBinding()]
209227
[OutputType([bool])]
@@ -615,9 +633,23 @@ function New-MoveCommitPlan {
615633
[switch]$ForcePushSource,
616634

617635
[Parameter()]
618-
[switch]$AutoStash
636+
[switch]$AutoStash,
637+
638+
[Parameter()]
639+
[switch]$CreateDestinationBranch,
640+
641+
[Parameter()]
642+
[string]$BaseRef
619643
)
620644

645+
if ($CreateDestinationBranch -and [string]::IsNullOrWhiteSpace($BaseRef)) {
646+
throw "Move-Commit requires -BaseRef when -CreateDestinationBranch is specified."
647+
}
648+
649+
if (-not $CreateDestinationBranch -and -not [string]::IsNullOrWhiteSpace($BaseRef)) {
650+
throw "Move-Commit only accepts -BaseRef together with -CreateDestinationBranch."
651+
}
652+
621653
$repoRoot = Get-GitRepoRoot
622654
$currentBranch = Get-GitCurrentBranch
623655
if ($currentBranch -eq 'HEAD') {
@@ -629,12 +661,37 @@ function New-MoveCommitPlan {
629661

630662
$branchExists = Test-GitRefExists -Ref "refs/heads/$DestinationBranch"
631663
$remoteBranchExists = Test-GitRefExists -Ref "refs/remotes/origin/$DestinationBranch"
664+
$planCreatesDestinationBranch = $false
665+
$destinationCreateBaseRef = $null
666+
$destinationCreateBaseCommit = $null
667+
632668
if (-not $branchExists -and -not $remoteBranchExists) {
633-
throw "Destination branch '$DestinationBranch' does not exist locally or on origin. Create it first."
669+
if (-not $CreateDestinationBranch) {
670+
throw (Get-MoveCommitMissingDestinationBranchMessage -DestinationBranch $DestinationBranch)
671+
}
672+
673+
$planCreatesDestinationBranch = $true
674+
$destinationCreateBaseRef = $BaseRef.Trim()
675+
$destinationCreateBaseCommit = Resolve-GitCommit -Ref $destinationCreateBaseRef -ErrorMessage "Base reference '$destinationCreateBaseRef' is not valid."
676+
}
677+
elseif ($CreateDestinationBranch) {
678+
throw @(
679+
"Destination branch '$DestinationBranch' already exists locally or on origin."
680+
"Remove -CreateDestinationBranch or choose a different branch name."
681+
) -join [Environment]::NewLine
682+
}
683+
684+
$destinationRef = if ($planCreatesDestinationBranch) {
685+
"refs/heads/$DestinationBranch"
686+
}
687+
elseif ($branchExists) {
688+
"refs/heads/$DestinationBranch"
689+
}
690+
else {
691+
"refs/remotes/origin/$DestinationBranch"
634692
}
635693

636-
$destinationRef = if ($branchExists) { "refs/heads/$DestinationBranch" } else { "refs/remotes/origin/$DestinationBranch" }
637-
$useRemoteTrackingBranch = $remoteBranchExists -and -not $branchExists
694+
$useRemoteTrackingBranch = $remoteBranchExists -and -not $branchExists -and -not $planCreatesDestinationBranch
638695
$plannedStashName = New-GitSplitStashName -Operation 'move-commit'
639696
$plannedDestWorktreePath = New-GitSplitWorktreePath -RepoRoot $repoRoot
640697
$plannedSourceWorktreePath = $null
@@ -669,6 +726,13 @@ function New-MoveCommitPlan {
669726
'$moveSucceeded = $false'
670727
)
671728

729+
if ($planCreatesDestinationBranch) {
730+
$steps += New-GitStep -Kind Literal -Lines @(
731+
'$destinationCreateBaseRef = ' + (ConvertTo-PowerShellStringLiteral $destinationCreateBaseRef)
732+
'$destinationCreateBaseCommit = ' + (ConvertTo-PowerShellStringLiteral $destinationCreateBaseCommit)
733+
)
734+
}
735+
672736
if ($sourceRemovalPlan) {
673737
$steps += New-GitStep -Kind Literal -Lines @(
674738
'$sourceWorktreePath = ' + (ConvertTo-PowerShellStringLiteral $plannedSourceWorktreePath)
@@ -702,13 +766,21 @@ function New-MoveCommitPlan {
702766
'if ($currentHead -ne $expectedHead) {'
703767
' throw "This script expected HEAD ''$expectedHead'' but found ''$currentHead''."'
704768
'}'
705-
'& git show-ref --verify --quiet $destinationRef'
706-
'if ($LASTEXITCODE -ne 0) {'
707-
' if ($useRemoteTrackingBranch) {'
708-
' throw "Destination branch ''$destinationBranch'' no longer exists on origin."'
709-
' }'
710-
' throw "Destination branch ''$destinationBranch'' no longer exists locally."'
711-
'}'
769+
)
770+
771+
if (-not $planCreatesDestinationBranch) {
772+
$guardLines += @(
773+
'& git show-ref --verify --quiet $destinationRef'
774+
'if ($LASTEXITCODE -ne 0) {'
775+
' if ($useRemoteTrackingBranch) {'
776+
' throw "Destination branch ''$destinationBranch'' no longer exists on origin."'
777+
' }'
778+
' throw "Destination branch ''$destinationBranch'' no longer exists locally."'
779+
'}'
780+
)
781+
}
782+
783+
$guardLines += @(
712784
'$status = @(& git status --porcelain)'
713785
'if ($LASTEXITCODE -ne 0) {'
714786
' throw "Failed to determine git status."'
@@ -725,6 +797,27 @@ function New-MoveCommitPlan {
725797
' $stashed = $true'
726798
'}'
727799
)
800+
801+
if ($planCreatesDestinationBranch) {
802+
$guardLines += @(
803+
'& git show-ref --verify --quiet "refs/heads/$destinationBranch"'
804+
'if ($LASTEXITCODE -eq 0) {'
805+
' throw "Destination branch ''$destinationBranch'' already exists locally."'
806+
'}'
807+
'& git show-ref --verify --quiet "refs/remotes/origin/$destinationBranch"'
808+
'if ($LASTEXITCODE -eq 0) {'
809+
' throw "Destination branch ''$destinationBranch'' already exists on origin."'
810+
'}'
811+
'$runtimeBaseRefCommit = (& git rev-parse --verify "$destinationCreateBaseRef^{commit}").Trim()'
812+
'if ($LASTEXITCODE -ne 0 -or $runtimeBaseRefCommit -notmatch ''^[0-9a-f]{40}$'') {'
813+
' throw "Base reference ''$destinationCreateBaseRef'' is no longer valid. Re-run Move-Commit with -CreateDestinationBranch -BaseRef <base-ref>."'
814+
'}'
815+
'if ($runtimeBaseRefCommit -ne $destinationCreateBaseCommit) {'
816+
' throw "Base reference ''$destinationCreateBaseRef'' resolved to ''$runtimeBaseRefCommit'', but this plan expected ''$destinationCreateBaseCommit''. Re-run Move-Commit so the branch is created from the intended base."'
817+
'}'
818+
)
819+
}
820+
728821
$steps += New-GitStep -Kind Literal -Lines $guardLines
729822

730823
$executionLines = @(
@@ -736,18 +829,34 @@ function New-MoveCommitPlan {
736829
' throw "Planned destination worktree path ''$destWorktreePath'' already exists."'
737830
'}'
738831
'try {'
739-
' if ($useRemoteTrackingBranch) {'
740-
' & git worktree add -b $destinationBranch $destWorktreePath "origin/$destinationBranch" 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
741-
' if ($LASTEXITCODE -ne 0) {'
742-
' throw "git worktree add -b $destinationBranch failed"'
743-
' }'
744-
' }'
745-
' else {'
746-
' & git worktree add $destWorktreePath $destinationBranch 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
747-
' if ($LASTEXITCODE -ne 0) {'
748-
' throw "git worktree add $destinationBranch failed"'
749-
' }'
750-
' }'
832+
)
833+
834+
if ($planCreatesDestinationBranch) {
835+
$executionLines += @(
836+
' & git worktree add -b $destinationBranch $destWorktreePath $destinationCreateBaseCommit 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
837+
' if ($LASTEXITCODE -ne 0) {'
838+
' throw "git worktree add -b $destinationBranch $destinationCreateBaseCommit failed"'
839+
' }'
840+
)
841+
}
842+
else {
843+
$executionLines += @(
844+
' if ($useRemoteTrackingBranch) {'
845+
' & git worktree add -b $destinationBranch $destWorktreePath "origin/$destinationBranch" 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
846+
' if ($LASTEXITCODE -ne 0) {'
847+
' throw "git worktree add -b $destinationBranch failed"'
848+
' }'
849+
' }'
850+
' else {'
851+
' & git worktree add $destWorktreePath $destinationBranch 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
852+
' if ($LASTEXITCODE -ne 0) {'
853+
' throw "git worktree add $destinationBranch failed"'
854+
' }'
855+
' }'
856+
)
857+
}
858+
859+
$executionLines += @(
751860
' $destWorktreeCreated = $true'
752861
' & git -C $destWorktreePath cherry-pick $commitHash 2>&1 | ForEach-Object { $_ | Out-String | Write-Host }'
753862
' if ($LASTEXITCODE -ne 0) {'
@@ -920,6 +1029,9 @@ function New-MoveCommitPlan {
9201029
return New-GitPlan -Name 'Move-Commit' -Metadata @{
9211030
CommitHash = $commitHash
9221031
DestinationBranch = $DestinationBranch
1032+
CreateDestinationBranch = [bool]$planCreatesDestinationBranch
1033+
DestinationBaseRef = $destinationCreateBaseRef
1034+
DestinationBaseCommit = $destinationCreateBaseCommit
9231035
SourceBranch = $currentBranch
9241036
SourceHead = $currentHead
9251037
RemoveFromSource = [bool]$RemoveFromSource
@@ -2817,7 +2929,16 @@ function Move-Commit {
28172929
Commit-ish to move/copy. Defaults to HEAD.
28182930
28192931
.PARAMETER DestinationBranch
2820-
The destination branch to receive the commit. Must exist locally or on origin.
2932+
The destination branch to receive the commit. Must exist locally or on origin
2933+
unless -CreateDestinationBranch is specified.
2934+
2935+
.PARAMETER CreateDestinationBranch
2936+
If specified, creates the destination branch instead of requiring it to already
2937+
exist. Requires -BaseRef.
2938+
2939+
.PARAMETER BaseRef
2940+
The base ref to create the destination branch from when -CreateDestinationBranch
2941+
is specified.
28212942
28222943
.PARAMETER RemoveFromSource
28232944
If specified, removes the commit from the current branch after applying it to the destination.
@@ -2869,6 +2990,12 @@ function Move-Commit {
28692990
[Parameter()]
28702991
[switch]$AutoStash,
28712992

2993+
[Parameter()]
2994+
[switch]$CreateDestinationBranch,
2995+
2996+
[Parameter()]
2997+
[string]$BaseRef,
2998+
28722999
[Parameter()]
28733000
[ValidateNotNullOrEmpty()]
28743001
[string]$OutputScriptPath
@@ -2880,7 +3007,9 @@ function Move-Commit {
28803007
-RemoveFromSource:$RemoveFromSource `
28813008
-Push:$Push `
28823009
-ForcePushSource:$ForcePushSource `
2883-
-AutoStash:$AutoStash
3010+
-AutoStash:$AutoStash `
3011+
-CreateDestinationBranch:$CreateDestinationBranch `
3012+
-BaseRef $BaseRef
28843013

28853014
if ($OutputScriptPath) {
28863015
if ($PSCmdlet.ShouldProcess($OutputScriptPath, 'Write Move-Commit execution script')) {

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ This is meant to pair with `Split-Commit`:
111111
2) Use `Move-Commit` to move one of those commits to a different branch.
112112

113113
> Note: `Move-Commit -RemoveFromSource` rewrites history.
114+
>
115+
> By default, `Move-Commit` fails if the destination branch does not already exist.
116+
> To create it intentionally, use `-CreateDestinationBranch -BaseRef <ref>`.
114117
115118
```powershell
116119
# Copy HEAD to another branch (no branch switching in your current worktree)
@@ -119,6 +122,9 @@ Move-Commit -CommitRef HEAD -DestinationBranch feature/extracted
119122
# Move HEAD to another branch and remove it from the current branch
120123
Move-Commit -CommitRef HEAD -DestinationBranch feature/extracted -RemoveFromSource
121124
125+
# Create the destination branch from origin/main, then move HEAD onto it
126+
Move-Commit -CommitRef HEAD -DestinationBranch feature/extracted -CreateDestinationBranch -BaseRef origin/main
127+
122128
# Generate a reviewable script now and execute it later
123129
Move-Commit -CommitRef HEAD~1 -DestinationBranch feature/extracted -OutputScriptPath ./move-commit.ps1
124130
```

0 commit comments

Comments
 (0)