[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [string]$Path = ".", [ValidateSet('List', 'Add', 'Remove')] [string]$Action = 'List', [string]$WorktreePath, [string]$Branch, [switch]$Force ) $ErrorActionPreference = 'Stop' if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw "git not found in PATH" } $repo = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path $null = & git -C $repo rev-parse --is-inside-work-tree 2>$null if ($LASTEXITCODE -ne 0) { throw "Not a git repository: $repo" } $items = @() $current = @{} $lines = @(& git -C $repo worktree list --porcelain 2>$null) foreach ($line in $lines) { if ([string]::IsNullOrWhiteSpace($line)) { if ($current.Count -gt 0) { $items += [pscustomobject]$current $current = @{} } continue } $parts = $line -split ' ', 2 if ($parts.Count -eq 2) { $current[$parts[0]] = $parts[1] } else { $current[$parts[0]] = $true } } if ($current.Count -gt 0) { $items += [pscustomobject]$current } if ($Action -eq 'List') { $rows = foreach ($item in $items) { $branchName = if ($item.PSObject.Properties.Name -contains 'branch') { ([string]$item.branch).Replace('refs/heads/', '') } else { 'detached' } $commit = if ($item.PSObject.Properties.Name -contains 'HEAD') { ([string]$item.HEAD).Substring(0, [Math]::Min(7, ([string]$item.HEAD).Length)) } else { '' } [pscustomobject]@{ Worktree = $item.worktree Commit = $commit Branch = $branchName Detached = ($item.PSObject.Properties.Name -contains 'detached') } } $rows | Format-Table -AutoSize exit 0 } if ($Action -eq 'Add') { if (-not $WorktreePath) { throw "WorktreePath is required for Add." } if (-not $Branch) { throw "Branch is required for Add." } $target = [System.IO.Path]::GetFullPath($WorktreePath) if (Test-Path -LiteralPath $target) { throw "Target already exists: $target" } $null = & git -C $repo show-ref --verify --quiet "refs/heads/$Branch" 2>$null $branchExists = ($LASTEXITCODE -eq 0) if ($PSCmdlet.ShouldProcess($target, "Create worktree for $Branch")) { if ($branchExists) { & git -C $repo worktree add $target $Branch } else { & git -C $repo worktree add -b $Branch $target } exit $LASTEXITCODE } } if ($Action -eq 'Remove') { if (-not $WorktreePath) { throw "WorktreePath is required for Remove." } if (-not $Force) { throw "Remove requires -Force." } $target = [System.IO.Path]::GetFullPath($WorktreePath) if ($items.Count -gt 0 -and [System.IO.Path]::GetFullPath([string]$items[0].worktree) -eq $target) { throw "The main worktree cannot be removed." } if ($PSCmdlet.ShouldProcess($target, "Remove worktree")) { & git -C $repo worktree remove --force $target exit $LASTEXITCODE } }