Управление git worktree
Показывает рабочие деревья, создаёт новое и удаляет только указанный worktree после подтверждения.
Что делает скрипт
Скрипт читает git worktree list --porcelain и показывает путь, коммит и ветку. Add создаёт дерево с новой или существующей веткой. Remove требует Force и подтверждения, а основной worktree удалить нельзя. Без Action выполняется только просмотр.
- Remove удаляет каталог worktree. Нужны -Force и подтверждение.
Быстрый старт
powershell -File Git-WorktreeManager.ps1 -Path . -Action List
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Git-WorktreeManager.ps1 -Path .powershell -File Git-WorktreeManager.ps1 -Path . -Action Add -WorktreePath ..\app-feature -Branch feature/uipowershell -File Git-WorktreeManager.ps1 -Path . -Action Remove -WorktreePath ..\app-feature -Force
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
winget install Git.Git
Git-WorktreeManager.ps1
[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
}
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.