-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathWorktree-CreateFromBranch.ps1
More file actions
431 lines (370 loc) · 12.9 KB
/
Copy pathWorktree-CreateFromBranch.ps1
File metadata and controls
431 lines (370 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<#
.SYNOPSIS
Create (or open) a git worktree for a branch and open it in a new VS Code window.
.DESCRIPTION
- Worktrees are placed under ../<main-folder-of-repo>.worktrees/<branch_name>
- If invoked from within an existing worktree, path names are based on the main repo root.
- If the branch already has a worktree (or the folder already exists as a worktree), it opens that.
- If a VS Code window already appears to be open for that worktree, it attempts to bring it to the foreground.
Colorization and workspace generation is delegated to scripts/Setup-WorktreeColor.ps1.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[string]$BranchName = "",
# Optional explicit color slot override (0-based index into Setup-WorktreeColor palette).
[Nullable[int]]$ColorIndex = $null,
# Print the actions that would be taken, but do not create/move/open anything.
[switch]$DryRun
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$scriptRepoRoot = (Get-Item $PSScriptRoot).Parent.FullName
$colorizeScript = Join-Path $scriptRepoRoot "scripts\Setup-WorktreeColor.ps1"
function ConvertTo-CanonicalBranchName([string]$name) {
if ([string]::IsNullOrWhiteSpace($name)) {
throw "BranchName is empty."
}
$name = $name.Trim()
if ($name.StartsWith("refs/heads/")) {
return $name.Substring("refs/heads/".Length)
}
if ($name.StartsWith("origin/")) {
return $name.Substring("origin/".Length)
}
return $name
}
function Get-RepoRoot([string]$anyPathInRepo) {
$top = & git -C $anyPathInRepo rev-parse --show-toplevel 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($top)) {
throw "Not a git repo (or git missing). Path: $anyPathInRepo"
}
return $top.Trim()
}
function Get-MainRepoRoot([string]$anyPathInRepo) {
$top = Get-RepoRoot $anyPathInRepo
$common = & git -C $anyPathInRepo rev-parse --git-common-dir 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($common)) {
# Fallback: assume the current toplevel is the main root.
return $top
}
$common = $common.Trim()
$commonPath = $common
if (-not [System.IO.Path]::IsPathRooted($commonPath)) {
$commonPath = Join-Path $top $commonPath
}
try {
$commonPath = (Resolve-Path -LiteralPath $commonPath).Path
}
catch {
# If Resolve-Path fails (e.g. unusual git state), assume it's already usable.
}
# Walk up until we find the .git directory.
$probe = $commonPath
while ($true) {
if ([string]::Equals((Split-Path $probe -Leaf), ".git", [System.StringComparison]::OrdinalIgnoreCase)) {
break
}
$parent = Split-Path $probe -Parent
if ([string]::IsNullOrWhiteSpace($parent) -or $parent -eq $probe) {
# Give up and use current toplevel.
return $top
}
$probe = $parent
}
return (Split-Path $probe -Parent)
}
function Get-IsWorktree([string]$rootPath) {
$gitPath = Join-Path $rootPath ".git"
return (Test-Path $gitPath -PathType Leaf)
}
function ConvertTo-CanonicalPath([string]$path) {
if ([string]::IsNullOrWhiteSpace($path)) {
return ""
}
try {
return ([System.IO.Path]::GetFullPath($path)).ToLowerInvariant()
}
catch {
return $path.ToLowerInvariant()
}
}
function Convert-BranchToRelativePath([string]$branch) {
# Allow feature/foo to become ...\feature\foo
$segments = @($branch -split '[\\/]' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
if ($segments.Length -eq 0) {
throw "Invalid branch name: '$branch'"
}
return $segments
}
function Get-WorktreesRoot([string]$mainRepoRoot) {
$repoName = Split-Path $mainRepoRoot -Leaf
$repoParent = Split-Path $mainRepoRoot -Parent
return (Join-Path $repoParent ("{0}.worktrees" -f $repoName))
}
function Get-GitWorktrees([string]$mainRepoRoot) {
$lines = @(& git -C $mainRepoRoot worktree list --porcelain 2>$null)
if ($LASTEXITCODE -ne 0) {
throw "Failed to list git worktrees."
}
if ($null -eq $lines -or $lines.Length -eq 0) {
return @()
}
$worktrees = New-Object System.Collections.Generic.List[object]
$current = $null
foreach ($line in $lines) {
if ([string]::IsNullOrWhiteSpace($line)) {
if ($null -ne $current -and -not [string]::IsNullOrWhiteSpace($current.Path)) {
$worktrees.Add($current)
}
$current = $null
continue
}
if ($line.StartsWith("worktree ")) {
if ($null -ne $current -and -not [string]::IsNullOrWhiteSpace($current.Path)) {
$worktrees.Add($current)
}
$current = [pscustomobject]@{ Path = $line.Substring("worktree ".Length); Branch = "" }
continue
}
if ($null -eq $current) {
continue
}
if ($line.StartsWith("branch ")) {
$current.Branch = $line.Substring("branch ".Length)
continue
}
if ($line -eq "detached") {
$current.Branch = "(detached)"
continue
}
}
if ($null -ne $current -and -not [string]::IsNullOrWhiteSpace($current.Path)) {
$worktrees.Add($current)
}
return $worktrees.ToArray()
}
function Get-BranchChoices([string]$mainRepoRoot) {
# Return a single flat list: local branches first, then remotes.
# Each group is already sorted newest-first by git.
$localLines = @(& git -C $mainRepoRoot for-each-ref --sort=-committerdate --format="%(refname:short)`t%(committerdate:iso8601)" refs/heads 2>$null)
if ($LASTEXITCODE -ne 0) {
throw "Failed to list local branches."
}
$remoteLines = @(& git -C $mainRepoRoot for-each-ref --sort=-committerdate --format="%(refname:short)`t%(committerdate:iso8601)" refs/remotes/origin 2>$null)
if ($LASTEXITCODE -ne 0) {
throw "Failed to list remote branches."
}
$choices = New-Object System.Collections.Generic.List[object]
foreach ($line in $localLines) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
$parts = $line -split "`t", 2
$name = $parts[0]
if ([string]::IsNullOrWhiteSpace($name)) { continue }
$when = if ($parts.Length -gt 1) { $parts[1] } else { "" }
$choices.Add([pscustomobject]@{ Kind = "local"; Name = $name; Display = $name; Date = $when })
}
foreach ($line in $remoteLines) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
$parts = $line -split "`t", 2
$name = $parts[0]
if ([string]::IsNullOrWhiteSpace($name)) { continue }
# Skip origin/HEAD -> origin/main pointer.
if ($name -eq "origin/HEAD") { continue }
$when = if ($parts.Length -gt 1) { $parts[1] } else { "" }
$display = $name
if ($display.StartsWith("origin/")) { $display = $display.Substring("origin/".Length) }
$choices.Add([pscustomobject]@{ Kind = "remote"; Name = $name; Display = $display; Date = $when })
}
return $choices.ToArray()
}
function Select-Branch([object[]]$choices) {
if ($null -eq $choices -or $choices.Length -eq 0) {
throw "No branches found."
}
Write-Host "Select a branch (local first, then origin/*; newest first within each):"
for ($i = 0; $i -lt $choices.Length; $i++) {
$c = $choices[$i]
$kind = if ($c.Kind -eq "local") { "L" } else { "R" }
$when = if ([string]::IsNullOrWhiteSpace($c.Date)) { "" } else { " ($($c.Date))" }
Write-Host (" {0}) [{1}] {2}{3}" -f ($i + 1), $kind, $c.Display, $when)
}
while ($true) {
$raw = Read-Host ("Enter selection (1-{0})" -f $choices.Length)
[int]$idx = 0
if ([int]::TryParse($raw, [ref]$idx) -and $idx -ge 1 -and $idx -le $choices.Length) {
return $choices[$idx - 1]
}
Write-Warning "Invalid selection."
}
}
function ConvertTo-CanonicalWorktreeBranch([string]$branchRef) {
if ([string]::IsNullOrWhiteSpace($branchRef)) {
return ""
}
if ($branchRef.StartsWith("refs/heads/")) {
return $branchRef.Substring("refs/heads/".Length)
}
return $branchRef
}
function Test-BranchExists([string]$mainRepoRoot, [string]$ref) {
& git -C $mainRepoRoot show-ref --verify --quiet $ref 2>$null
return ($LASTEXITCODE -eq 0)
}
function Set-VsCodeWindowForegroundIfOpen([string]$worktreePath, [string]$branchName) {
# Best-effort: match window title by folder name or branch name.
$folderName = Split-Path $worktreePath -Leaf
$needles = @($folderName, $branchName) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
$procs = @(Get-Process -Name "Code" -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 })
if ($procs.Length -eq 0) {
return $false
}
$windowMatches = @()
foreach ($p in $procs) {
$title = $p.MainWindowTitle
if ([string]::IsNullOrWhiteSpace($title)) {
continue
}
foreach ($n in $needles) {
if ($title -like "*$n*") {
$windowMatches += $p
break
}
}
}
if ($windowMatches.Length -eq 0) {
return $false
}
try {
Add-Type -Namespace FieldWorks -Name Win32 -MemberDefinition @"
using System;
using System.Runtime.InteropServices;
public static class Win32 {
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
}
"@ -ErrorAction SilentlyContinue
$target = $windowMatches[0]
# 9 = SW_RESTORE
[void][FieldWorks.Win32]::ShowWindowAsync($target.MainWindowHandle, 9)
[void][FieldWorks.Win32]::SetForegroundWindow($target.MainWindowHandle)
Write-Host "VS Code already open for this worktree; focusing existing window."
return $true
}
catch {
Write-Warning "VS Code already appears to be open, but focusing failed."
throw "VS Code already exists for that worktree."
}
}
$mainRepoRoot = Get-MainRepoRoot $scriptRepoRoot
$branchChoice = $null
if ([string]::IsNullOrWhiteSpace($BranchName)) {
$choices = Get-BranchChoices $mainRepoRoot
$branchChoice = Select-Branch $choices
$BranchName = if ($branchChoice.Kind -eq "remote") { $branchChoice.Display } else { $branchChoice.Name }
}
$branch = ConvertTo-CanonicalBranchName $BranchName
$worktreesRoot = Get-WorktreesRoot $mainRepoRoot
$desiredPath = $worktreesRoot
foreach ($seg in (Convert-BranchToRelativePath $branch)) {
$desiredPath = Join-Path $desiredPath $seg
}
$worktrees = Get-GitWorktrees $mainRepoRoot
$normalizedDesired = ConvertTo-CanonicalPath $desiredPath
$existing = $null
foreach ($wt in $worktrees) {
if (-not [string]::IsNullOrWhiteSpace($wt.Branch)) {
$wtBranch = ConvertTo-CanonicalWorktreeBranch $wt.Branch
if ($wtBranch -eq $branch) {
$existing = $wt
break
}
}
}
if ($null -eq $existing) {
foreach ($wt in $worktrees) {
if ((ConvertTo-CanonicalPath $wt.Path) -eq $normalizedDesired) {
$existing = $wt
break
}
}
}
$targetWorktreePath = $null
if ($null -ne $existing) {
$targetWorktreePath = $existing.Path
Write-Host "Found existing worktree for branch '$branch': $targetWorktreePath"
}
elseif (Test-Path $desiredPath -PathType Container -ErrorAction SilentlyContinue) {
if (Get-IsWorktree $desiredPath) {
$targetWorktreePath = $desiredPath
Write-Host "Found existing worktree folder for branch '$branch': $targetWorktreePath"
}
else {
throw "Folder exists but is not a git worktree: $desiredPath"
}
}
else {
# Create worktree
New-Item -ItemType Directory -Path $worktreesRoot -Force | Out-Null
New-Item -ItemType Directory -Path (Split-Path $desiredPath -Parent) -Force | Out-Null
$localRef = "refs/heads/$branch"
$remoteRef = "refs/remotes/origin/$branch"
$hasLocal = Test-BranchExists -mainRepoRoot $mainRepoRoot -ref $localRef
$hasRemote = $false
if (-not $hasLocal) {
$hasRemote = Test-BranchExists -mainRepoRoot $mainRepoRoot -ref $remoteRef
}
if ($DryRun) {
if ($hasLocal) {
Write-Host "[DRYRUN] Would create worktree at $desiredPath for existing local branch '$branch'."
}
elseif ($hasRemote) {
Write-Host "[DRYRUN] Would create worktree at $desiredPath for remote branch 'origin/$branch' (and create local branch '$branch')."
}
else {
Write-Host "[DRYRUN] Would create new branch '$branch' and worktree at $desiredPath."
}
$targetWorktreePath = $desiredPath
}
else {
if ($hasLocal) {
Write-Host "Creating worktree at $desiredPath for existing local branch '$branch'..."
& git -C $mainRepoRoot worktree add $desiredPath $branch
}
elseif ($hasRemote) {
Write-Host "Creating worktree at $desiredPath for remote branch 'origin/$branch'..."
& git -C $mainRepoRoot worktree add -b $branch $desiredPath "origin/$branch"
}
else {
Write-Host "Branch '$branch' not found; creating new branch and worktree at $desiredPath..."
& git -C $mainRepoRoot worktree add -b $branch $desiredPath
}
if ($LASTEXITCODE -ne 0) {
throw "git worktree add failed."
}
}
$targetWorktreePath = $desiredPath
}
if (-not $DryRun -and -not (Test-Path $targetWorktreePath -PathType Container)) {
throw "Target worktree path does not exist: $targetWorktreePath"
}
# If VS Code is already open for this worktree, try to focus it.
if (-not $DryRun -and (Set-VsCodeWindowForegroundIfOpen -worktreePath $targetWorktreePath -branchName $branch)) {
return
}
# Open a new VS Code window for the worktree workspace file (colorized).
if ($DryRun) {
Write-Host "[DRYRUN] Would open VS Code on: $targetWorktreePath"
return
}
if (-not (Test-Path $colorizeScript -PathType Leaf)) {
throw "Missing colorize script: $colorizeScript"
}
$colorizeArgs = @{
Action = "Launch"
WorktreePath = $targetWorktreePath
}
if ($PSBoundParameters.ContainsKey("ColorIndex")) {
$colorizeArgs.ColorIndex = $ColorIndex
}
& $colorizeScript @colorizeArgs