-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-FromMaster.ps1
More file actions
487 lines (388 loc) · 13.9 KB
/
Copy pathUpdate-FromMaster.ps1
File metadata and controls
487 lines (388 loc) · 13.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
[CmdletBinding()]
param(
[ValidateSet('merge', 'rebase')]
[string]$Mode = 'rebase',
[string]$BaseBranch,
[string]$RemoteName = 'origin',
[switch]$NoPush,
[switch]$KeepTempFile
)
$ErrorActionPreference = 'Stop'
if ($IsWindows -eq $false) {
throw "This script requires a Windows environment. The temporary batch runner (.bat) is not supported on non-Windows platforms."
}
function Assert-GitSuccess {
param(
[Parameter(Mandatory = $true)]
[string]$Message
)
if ($LASTEXITCODE -ne 0) {
throw $Message
}
}
function Test-GitStateFile {
param(
[Parameter(Mandatory = $true)]
[string]$Name
)
return Test-Path (Join-Path $gitDir $Name)
}
function Get-StatusPath {
param(
[Parameter(Mandatory = $true)]
[string]$StatusLine
)
if ($StatusLine.Length -lt 4) {
return $null
}
$pathPortion = $StatusLine.Substring(3)
$renameParts = $pathPortion -split ' -> ', 2
return $renameParts[-1].Trim()
}
function Test-IgnoredDotFolderStatus {
param(
[Parameter(Mandatory = $true)]
[string]$StatusLine
)
if (-not $StatusLine.StartsWith('!! ')) {
return $false
}
$path = Get-StatusPath $StatusLine
if ([string]::IsNullOrWhiteSpace($path)) {
return $false
}
$normalizedPath = $path.Replace('\', '/')
return $normalizedPath -match '^\.[^/]+/'
}
function Get-IgnoredDotFolder {
param(
[Parameter(Mandatory = $true)]
[string]$StatusLine
)
if (-not (Test-IgnoredDotFolderStatus $StatusLine)) {
return $null
}
$path = Get-StatusPath $StatusLine
if ([string]::IsNullOrWhiteSpace($path)) {
return $null
}
$normalizedPath = $path.Replace('\', '/')
$pathParts = $normalizedPath -split '/', 2
if ($pathParts.Count -eq 0 -or [string]::IsNullOrWhiteSpace($pathParts[0])) {
return $null
}
return $pathParts[0]
}
function Get-TrimmedGitOutput {
param(
[Parameter(Mandatory = $true)]
[string[]]$Arguments
)
$output = git -C $repoRoot @Arguments
Assert-GitSuccess "Git command failed: git -C `"$repoRoot`" $($Arguments -join ' ')"
if ($null -eq $output) {
return ''
}
return ([string]$output).Trim()
}
function Test-GitRefExists {
param(
[Parameter(Mandatory = $true)]
[string]$RefName
)
git -C $repoRoot show-ref --verify --quiet $RefName
return $LASTEXITCODE -eq 0
}
function Test-BuildArtifactStatus {
param(
[Parameter(Mandatory = $true)]
[string]$StatusLine
)
if (-not ($StatusLine.StartsWith('?? ') -or $StatusLine.StartsWith('!! '))) {
return $false
}
$path = Get-StatusPath $StatusLine
if ([string]::IsNullOrWhiteSpace($path)) {
return $false
}
$normalizedPath = $path.Replace('\', '/')
return $normalizedPath -match '(^|/)(bin|obj)(/|$)'
}
function Get-BuildArtifactDirectory {
param(
[Parameter(Mandatory = $true)]
[string]$StatusLine
)
if (-not (Test-BuildArtifactStatus $StatusLine)) {
return $null
}
$path = Get-StatusPath $StatusLine
if ([string]::IsNullOrWhiteSpace($path)) {
return $null
}
$normalizedPath = $path.Replace('\', '/')
$match = [regex]::Match($normalizedPath, '^(.*?)(?:^|/)(bin|obj)(?:/.*)?$')
if (-not $match.Success) {
return $null
}
$prefix = $match.Groups[1].Value.TrimEnd('/')
$folderName = $match.Groups[2].Value
if ([string]::IsNullOrWhiteSpace($prefix)) {
return $folderName
}
return "$prefix/$folderName"
}
function Get-BaseBranchNameFromRef {
param(
[Parameter(Mandatory = $true)]
[string]$RefName
)
$pathParts = $RefName -split '/'
if ($pathParts.Count -eq 0) {
return $null
}
return $pathParts[-1]
}
function Resolve-BaseBranch {
if (-not [string]::IsNullOrWhiteSpace($BaseBranch)) {
return $BaseBranch.Trim()
}
$remoteHeadRef = git -C $repoRoot symbolic-ref --quiet "refs/remotes/$RemoteName/HEAD"
if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($remoteHeadRef)) {
return Get-BaseBranchNameFromRef ([string]$remoteHeadRef).Trim()
}
$candidateRefs = @(
"refs/heads/master",
"refs/heads/main",
"refs/remotes/$RemoteName/master",
"refs/remotes/$RemoteName/main"
)
foreach ($candidateRef in $candidateRefs) {
if (Test-GitRefExists $candidateRef) {
return Get-BaseBranchNameFromRef $candidateRef
}
}
throw "Unable to determine the base branch automatically. Specify -BaseBranch explicitly."
}
function Test-AnyGitState {
foreach ($stateFile in $stateFiles) {
if (Test-GitStateFile $stateFile) {
return $true
}
}
return $false
}
$repoRoot = (Resolve-Path $PSScriptRoot).Path
$tempBat = $null
$stashCreated = $false
$stashRef = $null
$stashName = $null
$exitCode = 0
git -C $repoRoot rev-parse --show-toplevel | Out-Null
Assert-GitSuccess "This script must be run from inside a git repository."
git -C $repoRoot remote get-url $RemoteName | Out-Null
Assert-GitSuccess "Remote '$RemoteName' was not found."
$currentBranch = Get-TrimmedGitOutput @('branch', '--show-current')
if ([string]::IsNullOrWhiteSpace($currentBranch)) {
throw "Detached HEAD is not supported. Check out a branch first."
}
$resolvedBaseBranch = Resolve-BaseBranch
$baseBranchRef = "refs/heads/$resolvedBaseBranch"
$remoteBaseBranchRef = "refs/remotes/$RemoteName/$resolvedBaseBranch"
if (-not (Test-GitRefExists $baseBranchRef) -and -not (Test-GitRefExists $remoteBaseBranchRef)) {
throw "Base branch '$resolvedBaseBranch' was not found locally. Fetch it or specify a different -BaseBranch."
}
if ($currentBranch.Equals($resolvedBaseBranch, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "You are already on '$resolvedBaseBranch'. Switch to a feature branch before running this script."
}
$gitDir = (git -C $repoRoot rev-parse --git-dir).Trim()
Assert-GitSuccess "Unable to locate the .git directory."
if (-not [System.IO.Path]::IsPathRooted($gitDir)) {
$gitDir = Join-Path $repoRoot $gitDir
}
$stateFiles = @(
'MERGE_HEAD',
'CHERRY_PICK_HEAD',
'REVERT_HEAD',
'BISECT_LOG',
'rebase-apply',
'rebase-merge'
)
foreach ($stateFile in $stateFiles) {
if (Test-GitStateFile $stateFile) {
throw "Repository has an in-progress git operation ('$stateFile'). Finish or abort it before running this script."
}
}
$statusOutput = @(git -C $repoRoot status --porcelain=v1 --untracked-files=all --ignored=matching)
Assert-GitSuccess "Unable to inspect the worktree state."
$buildArtifactDirectories = @(
$statusOutput |
ForEach-Object { Get-BuildArtifactDirectory $_ } |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
Sort-Object -Unique
)
foreach ($buildArtifactDirectory in $buildArtifactDirectories) {
$candidateBuildArtifactPath = Join-Path $repoRoot ($buildArtifactDirectory.Replace('/', [System.IO.Path]::DirectorySeparatorChar))
$fullBuildArtifactPath = [System.IO.Path]::GetFullPath($candidateBuildArtifactPath)
$repoRootWithSeparator = $repoRoot.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar
if (-not $fullBuildArtifactPath.StartsWith($repoRootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to remove build artifacts outside the repository root: $buildArtifactDirectory"
}
if (Test-Path -LiteralPath $fullBuildArtifactPath -PathType Container) {
Remove-Item -LiteralPath $fullBuildArtifactPath -Recurse -Force
Write-Host "Removed generated build artifacts: $buildArtifactDirectory"
}
}
if ($buildArtifactDirectories.Count -gt 0) {
$statusOutput = @(git -C $repoRoot status --porcelain=v1 --untracked-files=all --ignored=matching)
Assert-GitSuccess "Unable to inspect the worktree state after cleaning build artifacts."
}
$stashRelevantStatus = @($statusOutput | Where-Object { -not (Test-IgnoredDotFolderStatus $_) })
if ($stashRelevantStatus.Count -gt 0) {
$stashName = "{0} {1}" -f $Mode, (Get-Date -Format 'yyyy-MM-dd HH:mm')
$ignoredDotFolders = @(
$statusOutput |
ForEach-Object { Get-IgnoredDotFolder $_ } |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
Sort-Object -Unique
)
$stashArguments = @('stash', 'push', '--all', '--message', $stashName, '--', '.')
foreach ($ignoredDotFolder in $ignoredDotFolders) {
$stashArguments += ":(top,glob,exclude)$ignoredDotFolder/**"
}
git -C $repoRoot @stashArguments | Out-Null
Assert-GitSuccess "Unable to stash local changes before switching branches."
$stashRef = (git -C $repoRoot stash list -1 --format="%gd").Trim()
Assert-GitSuccess "Unable to inspect the created stash."
if ([string]::IsNullOrWhiteSpace($stashRef)) {
throw "A stash was created, but the script could not identify it for restoration."
}
$stashCreated = $true
}
$tempBat = Join-Path ([System.IO.Path]::GetTempPath()) ("update-from-base-{0}.bat" -f ([guid]::NewGuid().ToString('N')))
$repoRootEscaped = $repoRoot.Replace('%', '%%').Replace('"', '""')
$currentBranchEscaped = $currentBranch.Replace('%', '%%').Replace('"', '""')
$baseBranchEscaped = $resolvedBaseBranch.Replace('%', '%%').Replace('"', '""')
$remoteNameEscaped = $RemoteName.Replace('%', '%%').Replace('"', '""')
$pushChanges = if ($NoPush) { 'false' } else { 'true' }
$batchContent = @"
@echo off
setlocal
set "REPO_ROOT=$repoRootEscaped"
set "ORIGINAL_BRANCH=$currentBranchEscaped"
set "BASE_BRANCH=$baseBranchEscaped"
set "REMOTE_NAME=$remoteNameEscaped"
set "MODE=$Mode"
set "PUSH_CHANGES=$pushChanges"
cd /d "%REPO_ROOT%"
if errorlevel 1 exit /b 1
echo.
echo ^> git switch "%BASE_BRANCH%"
git switch "%BASE_BRANCH%"
if errorlevel 1 exit /b 1
echo.
echo ^> git pull --ff-only "%REMOTE_NAME%" "%BASE_BRANCH%"
git pull --ff-only "%REMOTE_NAME%" "%BASE_BRANCH%"
if errorlevel 1 exit /b 1
echo.
echo ^> git switch "%ORIGINAL_BRANCH%"
git switch "%ORIGINAL_BRANCH%"
if errorlevel 1 exit /b 1
echo.
if /i "%MODE%"=="rebase" (
echo ^> git rebase "%BASE_BRANCH%"
git rebase "%BASE_BRANCH%"
) else (
echo ^> git merge "%BASE_BRANCH%"
git merge "%BASE_BRANCH%"
)
if errorlevel 1 exit /b 1
if /i "%PUSH_CHANGES%"=="true" (
echo.
if /i "%MODE%"=="rebase" (
echo ^> git push --force-with-lease "%REMOTE_NAME%" "%ORIGINAL_BRANCH%"
git push --force-with-lease "%REMOTE_NAME%" "%ORIGINAL_BRANCH%"
) else (
echo ^> git push "%REMOTE_NAME%" "%ORIGINAL_BRANCH%"
git push "%REMOTE_NAME%" "%ORIGINAL_BRANCH%"
)
if errorlevel 1 exit /b 1
) else (
echo.
echo ^> Push skipped because -NoPush was specified.
)
echo.
echo Done.
exit /b 0
"@
Set-Content -LiteralPath $tempBat -Value $batchContent -Encoding Default
Write-Host "Original branch: $currentBranch"
Write-Host "Base branch: $resolvedBaseBranch"
Write-Host "Integration mode: $Mode"
Write-Host "Remote: $RemoteName"
Write-Host "Push changes: $(-not $NoPush)"
Write-Host "Temporary runner: $tempBat"
if ($stashCreated) {
Write-Host "Stashed current worktree as: $stashName ($stashRef)"
} else {
Write-Host "Worktree had no stash-worthy changes outside ignored dot folders. No stash created."
}
try {
& $tempBat
$exitCode = $LASTEXITCODE
}
finally {
$branchAfterRun = ''
try {
$branchAfterRun = Get-TrimmedGitOutput @('branch', '--show-current')
}
catch {
Write-Warning "Unable to determine the current branch during cleanup. Continuing with stash restoration and temp-file cleanup."
}
$hasGitState = $false
if (-not [string]::IsNullOrWhiteSpace($branchAfterRun) -and $branchAfterRun -ne $currentBranch) {
$hasGitState = Test-AnyGitState
if (-not $hasGitState) {
git -C $repoRoot switch -- $currentBranch | Out-Null
$switchBackExitCode = $LASTEXITCODE
if ($switchBackExitCode -ne 0) {
Write-Warning "Failed to switch back to the original branch '$currentBranch' during cleanup. You may still be on '$branchAfterRun'."
} else {
$branchAfterRun = $currentBranch
}
}
}
$hasGitState = Test-AnyGitState
if ($stashCreated -and -not [string]::IsNullOrWhiteSpace($stashRef)) {
if ($hasGitState) {
Write-Warning "Skipped stash restoration because the repository is in the middle of a git operation. The stash '$stashRef' was kept."
} elseif ($branchAfterRun -ne $currentBranch) {
Write-Warning "Skipped stash restoration because the repository is not back on '$currentBranch'. The stash '$stashRef' was kept."
} else {
git -C $repoRoot stash apply --index $stashRef | Out-Null
if ($LASTEXITCODE -eq 0) {
git -C $repoRoot stash drop $stashRef | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host "Restored stashed worktree from: $stashName"
} else {
Write-Warning "The stashed worktree was applied, but dropping '$stashRef' failed."
}
} else {
Write-Warning "Failed to restore stashed worktree from '$stashRef'. The stash was kept."
}
}
}
if ($KeepTempFile) {
Write-Host "Temporary batch file kept at: $tempBat"
} else {
Remove-Item -LiteralPath $tempBat -ErrorAction SilentlyContinue
Write-Host "Temporary batch file removed."
}
}
$pushSummary = if ($NoPush) { 'push skipped' } else { 'push attempted' }
if ($stashCreated) {
Write-Host "Summary: stashed dirty worktree as '$stashName', updated from '$resolvedBaseBranch' using '$Mode', and $pushSummary."
} else {
Write-Host "Summary: no stash-worthy changes outside ignored dot folders were found, updated from '$resolvedBaseBranch' using '$Mode', and $pushSummary."
}
exit $exitCode