-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtfs_git.ps1
More file actions
575 lines (485 loc) · 18.9 KB
/
tfs_git.ps1
File metadata and controls
575 lines (485 loc) · 18.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
####################################################################################################################
# This is a small utility script that implements basic workflow with git-tfs.
#
# Syntax: tfs_git.ps1 [push | pull | mergetrunk]
#
# The implement workflow is the following:
# 1. git-tfs is used to clone TFS repository and to maintain the bridge between git and TFS
# 2. master branch is *always* the same as TFS = NO GIT COMMITS IN THE MASTER BRANCH
# 3. All work is done in feature branches
# 4. Pulling changes from TFS:
# - Switch to master
# - git tfs pull
# - Switch to feature branch
# - git rebase master
# 5. Pushing changes to TFS:
# - On a feature branch
# - git tfs checkintool
#
# For convenient usage, you can add both push and pull to VisualStudio as external commands.
####################################################################################################################
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateSet('Push', 'Pull', 'MergeTrunk', 'MergeBranch', 'StartFeature')]
$Action,
[Parameter(Mandatory=$false, Position=1)]
[String]
$Name
)
function Get-LocalOrParentPath($path) {
$checkIn = Get-Item -Force .
while ($checkIn -ne $null) {
$pathToTest = [System.IO.Path]::Combine($checkIn.fullname, $path)
if (Test-Path -LiteralPath $pathToTest) {
return $pathToTest
} else {
$checkIn = $checkIn.parent
}
}
return $null
}
function Get-GitBranch {
# On Windows (or case insensitive systems in general), git will not mark a branch with *
# if it has been checked out using a different case (e.g. your branch is XYZ but you checked it out as xyz).
# If that is the case, we'll try a few other approaches to get the current branch
$branch = git branch | Select-String '\*'
if ($branch -ne $null) {
return $branch.ToString().Substring(1).Trim()
}
$branch = git symbolic-ref HEAD
if ($branch -ne $null) {
$refDir = $branch.ToString().Trim()
$branch = Split-Path -Leaf $refDir
$gitDir = Get-LocalOrParentPath .git
if ($gitDir -ne $null) {
# The magic symbol here is * which forces Get-Item to enumerate matching file system entries
# and return them in their correct case.
# Without it, Get-Item would return the entry exactly as it was in $refDir
$branchDir = Get-Item -Force "$gitDir/$refDir*" | ?{ $_.Name -eq $branch } | Select-Object -First 1
if ($branchDir -ne $null) {
return $branchDir.Name
}
}
return $branch
}
}
function Get-TopLevelDir {
$rootDir = git 'rev-parse' '--show-toplevel'
return $rootDir
}
function Get-GitDir {
return (Join-Path (Get-TopLevelDir) '.git')
}
function Test-GitRebaseInProgress {
$gitDir = Get-GitDir
return (Test-Path -PathType Container (Join-Path $gitDir 'rebase-apply')) -or (Test-Path -PathType Container (Join-Path $gitDir 'rebase-merge'))
}
function Test-GitUncommittedChanges {
$output = git status -z
return ( ($output -ne $null) -and ($output.Trim() -ne "") )
}
function Run-GitExtensions {
Param
(
[Parameter(Mandatory=$false, Position=0)]
[String[]]
$ArgumentList,
[Parameter(Mandatory=$false)]
[Switch]
$NoWait = $false
)
$gitex = Get-Command gitex -TotalCount 1
# In case this is an alias, resolve it into actual path
if ((Test-Path $gitex) -eq $false) {
$gitex = $gitex.Definition
}
if ([System.IO.Path]::GetExtension($gitex) -ne '.exe') {
$gitex = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($gitex), 'GitExtensions.exe')
if ((Test-Path $gitex) -eq $false) {
Write-Host "** Cannot find $gitex"
Exit 1
}
}
$process = Start-Process $gitex -ArgumentList $ArgumentList -PassThru
if ($NoWait -eq $false) {
$process.WaitForExit()
}
}
function Test-GitConflicts {
$diff = git diff --name-only --diff-filter=U
if ($diff -eq $null) {
return $false
}
return $diff.ToString().Trim() -ne ''
}
function Git-Rcheckin {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Remote
)
if ($script:authorsFile -eq $null) {
# Look for authors.txt
$authorsFile = @( (Join-Path (Get-TopLevelDir) authors.txt), (Join-Path $PSScriptRoot authors.txt) ) | ?{ Test-Path $_ } | Select-Object -First 1
if ($authorsFile) {
$script:authorsFile = "`"--authors=$authorsFile`""
Write-Host "Using authors file $authorsFile"
} else {
$script:authorsFile = ''
}
}
# Use Tee-Object here to send output to both console and variable
git tfs rcheckin -i $Remote -a --no-build-default-comment $script:authorsFile | Tee-Object -Variable rcheckinOutput
$script:rcheckinOutput = $rcheckinOutput
}
function Resolve-MergeConflicts {
Param
(
[Parameter(Mandatory=$false, Position=0)]
[Switch]
$AllowUncommittedChanges=$false
)
while (Test-GitConflicts) {
Write-Host -Foreground Red '* Conflicts detected, please resolve to continue'
$elapsedTime = Measure-Command { Run-GitExtensions mergeconflicts }
if ($elapsedTime.TotalSeconds -le 5) {
$LastExitCode = 0
Write-Host -Foreground Yellow '* Waiting for you to resolve conflicts manually, press ENTER to continue'
do
{
$key = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
while ($key.VirtualKeyCode -ne 13)
}
if (($LastExitCode -ne 0) -or (Test-GitConflicts)) {
Write-Host -Foreground Red '* Failed to rebase -- please fix manually'
Exit 1
}
if (Test-GitRebaseInProgress) {
git rebase '--continue'
}
}
if (!$AllowUncommittedChanges -and (Test-GitUncommittedChanges)) {
Write-Host -Foreground Red '* Unexpected changes in working tree, please fix manually'
Exit 1
}
}
function New-BranchMapping {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Definitions
)
$result = @()
[regex]$reDefinition = '(?imn)^\s*(?<source>.+?)\s*:\s*(?<target>.+?)\s*(#.*)?$'
foreach ($match in $reDefinition.Matches($Definitions)) {
$result += New-Object 'Tuple[string, string]'("^$($match.Groups['source'].Value)$", $match.Groups['target'])
}
return $result
}
function Get-FeatureBranch {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Branch
)
# Branch mapping is
if (!$script:branchMapping) {
$script:branchMapping = New-BranchMapping '
Develop: master
Dev: master
Refactor_.+: master # Refactoring branches map to master
Dev_(.+): $1 # Convention: main development for feature branches is done on a Dev_ branch
# Git-flow compatible naming
# feature/.+: $0 # No rule needed for feature branches - they should just map to themselves
hotfix/.+: master # Hotfix branches are done off trunk and usually do not have a matching TFS branch
'
}
$result = $script:branchMapping | ?{ $Branch -match $_.Item1 } | %{ $Branch -replace $_.Item1, $_.Item2 } | Select-Object -First 1
if ($result) {
return $result
}
return $Branch
}
function Get-TfsRemote {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Branch
)
$featureBranch = Get-FeatureBranch $Branch
if ($featureBranch -eq 'master') {
return 'default'
}
$branches = @(git branch -r | %{ $_.Trim() })
$candidates = ($Branch, $featureBranch, "_$Branch", "_$featureBranch")
return $candidates | ?{ "tfs/$_" -in $branches } | Select-Object -First 1
}
function Test-NewCommits {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Branch,
[Parameter(Mandatory=$true, Position=1)]
[String]
$ParentBranch
)
# Get the number of commits on $Branch that are not in $ParentBranch
$changes = (git rev-list --left-only --count "$Branch...$ParentBranch").Trim()
if ($changes -eq '0') {
return $false
}
Write-Host -Foreground Yellow "* Found $changes new commits in $Branch"
return $true
}
function Rebase-IfNeeded {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Branch,
[Parameter(Mandatory=$true, Position=1)]
[String]
$ParentBranch
)
if (Test-NewCommits $ParentBranch $Branch) {
Write-Host -Foreground Green "* Rebasing '$Branch' on '$ParentBranch'"
# Note the use of autosquash to process any in-comment commands and preserve-merges to preserve merges
# We also specify the target branch, to ensure correctness
git rebase -q --preserve-merges --autosquash $ParentBranch $Branch
Resolve-MergeConflicts
}
}
function Pull-FromTfs {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$currentBranch,
[Parameter(Mandatory=$true, Position=1)]
[String]
$featureBranch,
[Parameter(Mandatory=$true, Position=2)]
[String]
$tfsRemote,
[Parameter(Mandatory=$false)]
[Switch]
$NoRebase=$false
)
# Use a script-level array to store the branches we have already pulled from.
# This will prevent multiple pulls of the same branch
if (!$script:BranchesPulledFrom) {
$script:BranchesPulledFrom = @()
}
$alreadyPulled = $false
if ($featureBranch -in $script:BranchesPulledFrom) {
$alreadyPulled = $true
} else {
$script:BranchesPulledFrom += @($featureBranch)
}
if (!$alreadyPulled) {
Write-Host -Foreground Green "* Getting latest changes from branch '$featureBranch'"
$followSwitch = '--parents'
if ($tfsRemote -eq 'default') {
$followSwitch = '--ignore-branches'
}
git tfs fetch $followSwitch -i $tfsRemote
}
if ($currentBranch -and !$NoRebase) {
Rebase-IfNeeded $currentBranch "tfs/$tfsRemote"
}
}
function Push-ToTfs {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$currentBranch,
[Parameter(Mandatory=$true, Position=1)]
[String]
$featureBranch,
[Parameter(Mandatory=$true, Position=2)]
[String]
$tfsRemote
)
Pull-FromTfs $currentBranch $featureBranch $tfsRemote
Git-Rcheckin $tfsRemote
if ($LastExitCode -ne 0) {
Write-Host -Foreground Red "* Failed to push to TFS"
}
}
function Merge-Branch {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$currentBranch,
[Parameter(Mandatory=$true, Position=1)]
[String]
$featureBranch,
[Parameter(Mandatory=$true, Position=2)]
[String]
$tfsRemote,
[Parameter(Mandatory=$true, Position=3)]
[String]
$branchToMerge
)
$canUseCheckinTool = $true
if (($branchToMerge -eq 'master') -or ($featureBranch -eq 'master') -or ($currentBranch -eq 'master')) {
$canUseCheckinTool = $false
}
$tfsRemoteToMerge = Get-TfsRemote $branchToMerge
Pull-FromTfs $branchToMerge $branchToMerge $tfsRemoteToMerge -NoRebase
if ($featureBranch -ne $branchToMerge) {
Pull-FromTfs $featureBranch $featureBranch $tfsRemote -NoRebase
# There are new commits on this branch - we don't want to push those
# We only want to push the merge (when it happens).
# So, we create a temporary branch to hold current state
if (Test-NewCommits $featureBranch "tfs/$tfsRemote") {
$tempBranch = "$featureBranch-$([System.Guid]::NewGuid().ToString('N'))"
Write-Host -Foreground Yellow "* Branch '$featureBranch' has local commits - they will not be part of this merge"
git checkout -B $tempBranch --no-track "tfs/$tfsRemote"
}
try {
# Then merge into the feature branch (note that we are merging tfs remote to avoid any local changes on source branch)
Write-Host -Foreground Green "* Merging $branchToMerge into branch $featureBranch"
$commitMessage = "Merged $branchToMerge into branch $featureBranch"
git merge --commit --no-ff --no-edit --no-log -q -m "$commitMessage" "tfs/$tfsRemoteToMerge"
# ... and resolve any merge conflicts along the way
if (Test-GitUncommittedChanges) {
Write-Host -Foreground Red '* Conflicts detected, please resolve to continue'
Run-GitExtensions mergeconflicts
if (($LastExitCode -ne 0) -or (Test-GitConflicts)) {
Write-Host -Foreground Red "* Failed to merge -- please fix manually"
Exit 1
}
git commit -a --no-edit -q -m "$commitMessage"
}
# Push the merge to TFS
if ((Test-NewCommits (Get-GitBranch) "tfs/$tfsRemote")) {
Write-Host -Foreground Green "* Pushing feature branch '$featureBranch' to TFS branch 'tfs/$tfsRemote'"
Git-Rcheckin $tfsRemote
Resolve-MergeConflicts
$failedMessage = $script:rcheckinOutput | ?{ $_ -like '*The item*is not a branch of*' } | Select-Object -First 1
if ($canUseCheckinTool -and ($failedMessage -ne $null)) {
Write-Host -Foreground Yellow "* Regular checkin failed, trying with checkintool"
git tfs checkintool -i $tfsRemote --no-build-default-comment -m "$commitMessage"
}
if ($LastExitCode -ne 0) {
Write-Host -Foreground Red '** Failed to push to TFS'
return 1
}
} else {
Write-Host -Foreground Yellow '* No new commits created, nothing will be pushed to TFS'
}
} finally {
if ($tempBranch) {
Write-Host -Foreground Yellow "* Restoring local commits for '$featureBranch'"
git checkout $featureBranch -f
git branch -D $tempBranch
Rebase-IfNeeded $featureBranch "tfs/$tfsRemote"
}
}
}
if ($currentBranch -ne (Get-GitBranch)) {
Rebase-IfNeeded $currentBranch $featureBranch
}
return 0
}
function New-FeatureBranch {
Param
(
[Parameter(Mandatory=$true, Position=0)]
[String]
$Feature
)
if (!$Feature) {
Write-Host -Foreground Red "Feature name not specified"
return 1
}
if ((Get-GitBranch) -ne 'master') {
git checkout master --force
}
if ($Feature -like '*-*') {
$tfsFeature = [System.Globalization.CultureInfo]::InvariantCulture.TextInfo.ToTitleCase($Feature.ToLowerInvariant()).Replace('-', '')
} else {
$tfsFeature = $Feature
}
$gitBranch = $Feature
$tfsBranchPath = @(git tfs branch -r `
| %{ $_.Split('$') | Select-Object -Last 1 } `
| ?{ $_ -ne '' -and $tfsFeature -eq (Split-Path -Leaf $_) })
if (!$tfsBranchPath -or ($tfsBranchPath.Length -eq 0)) {
$tfsProjectRoot = git tfs branch `
| ?{ $_ -like '*default ->*' } `
| %{ $_.Split('$') } `
| Select-Object -Last 1 `
| Split-Path -Parent `
| %{ $_.Replace('\', '/') }
$tfsBranchPath = "`$$tfsProjectRoot/branches/$tfsFeature"
Write-Host -Foreground Green "* Creating TFS branch '$tfsBranchPath' and local git branch '$gitBranch'"
git tfs branch $tfsBranchPath $gitBranch --comment="Created branch $Feature"
} elseif ($tfsBranchPath.Length -eq 1) {
$tfsBranchPath = "`$$tfsBranchPath"
Write-Host -Foreground Green "* Using existing TFS branch '$tfsBranchPath' and creating local git branch '$gitBranch'"
git tfs branch --init $tfsBranchPath $gitBranch
} else {
Write-Host -Foreground Red "* Cannot initialise branch for feature '$Feature', multiple TFS branches exist: $([string]::join(', ', $tfsBranchPath)), $($tfsBranchPath.Length)"
return 1
}
if ($gitBranch -ne (Get-GitBranch)) {
# Sometimes git tfs fails to create local git branch, so we have to
# This will checkout the branch if it exists and create it if it doesn't
$branches = git branch | ?{ $_ -like "* $gitBranch"} | Select-Object -First 1
if ($branches -ne $null) {
git checkout $gitBranch
} else {
git checkout tfs/$tfsFeature -b $gitBranch
}
}
return 0
}
$currentBranch = Get-GitBranch
$featureBranch = Get-FeatureBranch $currentBranch
$tfsRemote = Get-TfsRemote $currentBranch
if (!$tfsRemote) {
Write-Host -Foreground Red "* Cannot find TFS remote for branch $currentBranch"
Exit 1
}
Write-Host -Foreground Green "* Git Branch: $currentBranch"
if ($featureBranch -ne $currentBranch) {
Write-Host -Foreground Green "* Feature Branch: $featureBranch"
}
Write-Host -Foreground Green "* TFS Branch: tfs/$tfsRemote"
Write-Host
$hasStash = Test-GitUncommittedChanges
if (Test-GitUncommittedChanges) {
Write-Host -Foreground Yellow "* There are uncommitted changes in branch $currentBranch. Creating a stash"
git stash save -u
}
if ($Action -eq 'push') {
Push-ToTfs $currentBranch $featureBranch $tfsRemote
} elseif ($Action -eq 'pull') {
Pull-FromTfs $currentBranch $featureBranch $tfsRemote
} elseif ($Action -eq 'mergetrunk') {
$exitCode = Merge-Branch $currentBranch $featureBranch $tfsRemote master
} elseif ($Action -eq 'StartFeature') {
$exitCode = New-FeatureBranch $Name
} elseif ($Action -eq 'MergeBranch') {
$exitCode = Merge-Branch $currentBranch $featureBranch $tfsRemote $Name
}
if ($hasStash -and ($currentBranch -eq (Get-GitBranch))) {
Write-Host -Foreground Green '* Restoring stashed changes'
git stash pop -q
Resolve-MergeConflicts -AllowUncommittedChanges
}
Write-Host -Foreground Green '** Completed **'
if ($exitCode) {
Exit $exitCode
}