Skip to content

Instantly share code, notes, and snippets.

@shanselman
Created December 28, 2025 22:58
Show Gist options
  • Select an option

  • Save shanselman/5ab04d4e047a71eebd00b9568197aae4 to your computer and use it in GitHub Desktop.

Select an option

Save shanselman/5ab04d4e047a71eebd00b9568197aae4 to your computer and use it in GitHub Desktop.
agent-git-trees.ps1
# PowerShell functions for managing git worktrees with agent pattern
# Based on: https://gist.github.com/dhh/18575558fc5ee10f15b6cd3e108ed844
function ga {
<#
.SYNOPSIS
Create a new git worktree and branch
.DESCRIPTION
Creates a new git worktree with a branch name following the pattern:
../[current-dir]--[branch-name]
.PARAMETER BranchName
The name of the new branch to create
.EXAMPLE
ga feature-123
#>
param(
[Parameter(Mandatory=$true)]
[string]$BranchName
)
$currentDir = Split-Path -Leaf (Get-Location)
$worktreePath = Join-Path ".." "$currentDir--$BranchName"
Write-Host "Creating worktree at: $worktreePath" -ForegroundColor Cyan
git worktree add -b $BranchName $worktreePath
if ($LASTEXITCODE -eq 0) {
# Uncomment if you use mise: mise trust -a $worktreePath
Set-Location $worktreePath
}
}
function gd {
<#
.SYNOPSIS
Remove current worktree and its branch
.DESCRIPTION
Removes the current git worktree and deletes its associated branch.
Expects the directory to follow the pattern: [root]--[branch-name]
.EXAMPLE
gd
#>
$currentPath = Get-Location
$currentDir = Split-Path -Leaf $currentPath
# Check if current directory follows the worktree pattern
if ($currentDir -notmatch '--') {
Write-Host "Error: Current directory doesn't appear to be a worktree (no '--' separator found)" -ForegroundColor Red
return
}
# Parse root and branch from directory name
$parts = $currentDir -split '--', 2
$rootDir = $parts[0]
$branchName = $parts[1]
Write-Host "About to remove worktree and delete branch '$branchName'" -ForegroundColor Yellow
$confirmation = Read-Host "Are you sure? (y/N)"
if ($confirmation -eq 'y' -or $confirmation -eq 'Y') {
# Navigate to root directory
$parentPath = Split-Path -Parent $currentPath
$rootPath = Join-Path $parentPath $rootDir
if (Test-Path $rootPath) {
Set-Location $rootPath
# Remove worktree using directory name, not full path
Write-Host "Removing worktree: $currentDir" -ForegroundColor Cyan
git worktree remove $currentDir --force
# Delete branch
Write-Host "Deleting branch: $branchName" -ForegroundColor Cyan
git branch -D $branchName
} else {
Write-Host "Error: Root directory not found at $rootPath" -ForegroundColor Red
}
} else {
Write-Host "Cancelled." -ForegroundColor Yellow
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment