-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-ADOGit.ps1
More file actions
1071 lines (926 loc) · 49.8 KB
/
Copy pathUpdate-ADOGit.ps1
File metadata and controls
1071 lines (926 loc) · 49.8 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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Execute the operations allowing a "rename" a Git branch in an Azure DevOps Git project, in individual repositories or the entire project.
.DESCRIPTION
This script will allow a user with appropriate permissions in an Azure DevOps (ADO) environment to complete the steps
necessary to replace a default (top-level) branch with a newly created branch (e.g. replacing 'master' with 'main').
Specifically when all operations available in this script are executed, the following occurs:
1. Create a new branch in 1-to-all repositories in an ADO project, maintaining history of a specified existing "old" branch
2. Set that new branch as the default branch (i.e. top-level) branch for the repository
3. Copy all existing policies from an "old" branch to this new branch (project-level* and repository-level policies)
4. Remove policies applying to "old" branch (project-level* and repository-level)
5. Delete the "old" branch
6. Update 1-to-all Build Pipeline definitions to use the new branch as the default branch for builds
* When all repositories are specified, project-level and repository-level policies are copied.
When working on individual repositories, only the policies from those repositories are copied/removed.
.PARAMETER OrganizationName
String: The name of the Azure DevOps organization hosting the project
.PARAMETER ProjectName
String: The name of the Azure DevOps project
.PARAMETER OldBranchName
String: The name of the existing or old branch that whose commit will be used as the base of the new branch.
Specify this parameter when executing following Operations: All, AddBranch, CopyPolicies, DeletePolicies, DeleteBranch
.PARAMETER NewBranchName
String: The name of the new branch that will be created, using the commit number of the OldBranchName branch.
Specify this parameter when executing following Operations: All, AddBranch, CopyPolicies, SetNewDefault
.PARAMETER PersonalAccessToken
String: The 64-bit string generated by the user in the user settings on the Azure DevOps website for the organization matching OrganizationName.
A PersonalAccessToken must have at least the following granted for all operations in this script:
* Code: Read, Write, & Manage
* Build: Read & Execute
* Project and Team: Read, Write, & Manage
.PARAMETER ReposToUpdate
String Array: A single or list of repositories to update. Repositories are selected based on case-insensitive string match.
* For all repositories, use an asterisk. For example: -ReposToUpdate '*'
* For a single repository, specify the exact name (casing is ignored). For example: -ReposToUpdate 'tools1'
* For multiple repositories, specify a list of comma-separated items, using a PowerShell new array declaration. For example: -ReposToUpdate @('tools1', 'tools2', 'webdocs')
* Specify this parameter when executing following Operations: All, AddBranch, CopyPolicies, DeleteBranch, DeletePolicies, SetNewDefault
.PARAMETER BuildDefsToUpdate
String Array: A single or list of build definitions to update. Wildcards allowed (found via PowerShell -like).
* For all build pipeline definitions, use an asterisk. For example: -BuildDefsToUpdate '*'
* For a single build pipeline, use the exact name. For example: -BuildDefsToUpdate 'tools1 CI PR Build'
* For multiple build pipelines matching a single wildcard, use a simple string. For example: -BuildDefsToUpdate 'tools1*'
* For multiple build pipelines matching a multiple exact names or wildcar strings, use the PowerShell new array declaration. For example: -BuildDefsToUpdate @('tools1 CI PR Build', 'tools2*')
* Specify this parameter when executing following Operations: All, UpdateBuildDefs
.PARAMETER Operations
String Array: An optional parameter directing the actions of the script. If not included, 'All' operations is assumed. Script will validate against a set of known operations.
Valid Operations:
* All: All of the operations specified.
* AddBranch: Add the NewBranchName to the repositories listed in the ReposToUpdate parameter
* DeleteBranch: Delete the OldBranchName from the repositories listed in the ReposToUpdate parameter
* SetNewDefaultBranch: Set the NewBranchName as the default branch in the repositories listed in the ReposToUpdate parameter
* CopyPolicies: Copy the policies applying to to OldBranchName and apply them to NewBranchName
* If updating all repositories in a project (ReposToUpdate contains '*' ), this will include project-level policies and repository-level policies
* If updating individual repositories in a project (ReposToUpdate does not contain '*'), this will include only the policies found in those repositories
* DeletePolicies: Delete the policies applying to OldBranchName
* If updating all repositories in a project (ReposToUpdate contains '*' ), this will include project-level policies and repository-level policies
* If updating individual repositories in a project (ReposToUpdate does not contain '*'), this will include only the policies found in those repositories
* UpdateBuildDefs: Update the Build Pipeline default branch for the build defintions specified in the BuildDefsToUpdate parameter
.EXAMPLE
All operations: in the 'MyProject' project of the 'Contoso' organization, replace the 'master' branch with 'main' in all repositories.
Copy all project and repository policies that currently apply to master, to main.
Update all build defintions to use 'main' as the new default branch for builds.
Update-ADOGit.ps1 -OrganizationName 'contoso' -ProjectName 'MyProject' -OldTopBranchName 'master' -NewTopBranchName 'main' -PersonalAccessToken 'PAT_64BIT_STRING' -ReposToUpdate '*' -BuildDefsToUpdate '*' -Operations 'All'
.EXAMPLE
Copy/Move Policies from "dev" branch to "ppe" branch, for all repos.
No branch is created or deleted in this example.
Update-ADOGit.ps1 -OrganizationName 'fabrikam' -ProjectName 'WebPlatform' -OldBranchName 'dev' -NewBranchName 'ppe' -PersonalAccessToken 'PAT' -ReposToUpdate '*' -Operations @('CopyPolicies', 'DeletePolicies')
.EXAMPLE
Copy/Move Policies from "dev" branch to "ppe" branch, for only 'Tools1' repo.
No branch is created or deleted in this example.
Update-ADOGit.ps1 -OrganizationName 'contoso' -ProjectName 'WebPlatform' -OldBranchName 'dev' -NewBranchName 'ppe' -PersonalAccessToken 'PAT' -ReposToUpdate 'Tools1' -Operations @('CopyPolicies', 'DeletePolicies')
.EXAMPLE
Delete all policies for the "develop" branch, and then delete the branch.
Update-ADOGit.ps1 -OrganizationName 'contoso' -ProjectName 'WebData' -OldBranchName 'develop' -PersonalAccessToken 'PAT_64BIT_STRING' -ReposToUpdate '*' -Operations @('DeletePolicies', 'DeleteBranch')
.EXAMPLE
Delete all policies for the "develop" branch in the tools1 and tools2 repositories, and then try to delete the branch.
Update-ADOGit.ps1 -OrganizationName 'fabrikam' -ProjectName 'WebData' -OldBranchName 'develop' -PersonalAccessToken 'PAT_64BIT_STRING' -ReposToUpdate @('tools1', 'tools2') -Operations @('DeletePolicies', 'DeleteBranch')
.EXAMPLE
Create a new branch called "stuff", with the history from existing branch called "things", in the repo "repo1".
Update-ADOGit.ps1 -OrganizationName 'myorg' -ProjectName 'proj1' -OldBranchName 'things' -NewBranchName 'stuff' -PersonalAccessToken 'PAT_64BIT_STRING' -ReposToUpdate 'repo1' -Operations 'AddBranch'
.EXAMPLE
Configure a branch called "hockey" to be the default branch for the repository "winter"
Update-ADOGit.ps1 -OrganizationName 'sports' -ProjectName 'american' -NewBranchName 'hockey' -PersonalAccessToken 'PAT_64BIT_STRING' -ReposToUpdate 'winter' -Operations 'SetNewDefaultBranch'
.EXAMPLE
Update all of the Build Pipeline definitions in the project "mudflaps" to use "bigtrucks" as the name of the default branch
Update-ADOGit.ps1 -OrganizationName 'vehiclethings' -ProjectName 'mudflaps' -NewBranchName 'bigtrucks' -PersonalAccessToken 'PAT_64BIT_STRING' -BuildDefsToUpdate '*' -Operations 'UpdateBuildDefs'
#>
param (
[CmdletBinding()]
[Parameter(Mandatory = $true, HelpMessage = 'Name of the Azure DevOps organization')]
[string] $OrganizationName,
[Parameter(Mandatory = $true, HelpMessage = 'Name of the Azure DevOps project')]
[string] $ProjectName,
[Parameter(Mandatory = $true, HelpMessage = 'Personal Access Token from ADO organization')]
[string] $PersonalAccessToken,
[Parameter(Mandatory = $false, HelpMessage = 'Name of the top-level branch to replace')]
[string] $OldBranchName = $null,
[Parameter(Mandatory = $false, HelpMessage = 'Name of the new top-level branch')]
[string] $NewBranchName = $null,
[Parameter(Mandatory = $false, HelpMessage = 'List of repositories to update (case-insensitive matched by repo name, use "*" for all' )]
[string[]] $ReposToUpdate = $null,
[Parameter(Mandatory = $false, HelpMessage = 'List of build defintions to update (wildcards acceptable, use "*" for all')]
[string[]] $BuildDefsToUpdate = $null,
[Parameter(Mandatory = $false, HelpMessage = 'Operations to complete (All, AddBranch, DeleteBranch, CopyPolicies, DeletePolicies, UpdateBuildDefs')]
[ValidateSet('All', 'AddBranch', 'DeleteBranch', 'SetNewDefault', 'CopyPolicies', 'DeletePolicies', 'UpdateBuildDefs')]
[string[]] $Operations = 'All'
)
# Declare custom enum for the operations (so we don't have to worry about mistyped strings)
# Ensure these match the ValidateSet in the param above
if ((Get-Host).Version.Major -ge 5)
{
enum ADOUpdateOperation { All; AddBranch; DeleteBranch; SetNewDefault; CopyPolicies; DeletePolicies; UpdateBuildDefs }
}
else
{
Add-Type -TypeDefinition "public enum ADOUpdateOperation { All, AddBranch, DeleteBranch, SetNewDefaultBranch, CopyPolicies, DeletePolicies, UpdateBuildDefs }"
}
# =============================================================================
# Returns TRUE if the [ADOUpdateOperation] applies to Repositories
function Test-IsRepositoryOperation
{
param ( [string[]] $Operations )
$retVal = ($Operations -contains [ADOUpdateOperation]::All `
-or $Operations -contains [ADOUpdateOperation]::AddBranch `
-or $Operations -contains [ADOUpdateOperation]::DeleteBranch `
-or $Operations -contains [ADOUpdateOperation]::SetNewDefault `
-or $Operations -contains [ADOUpdateOperation]::CopyPolicies `
-or $Operations -contains [ADOUpdateOperation]::DeletePolicies)
$retVal
}
# =============================================================================
# Returns TRUE if the [ADOUpdateOperation] applies to Build Definitions
function Test-IsBuildDefinitionOperation
{
param ( [string[]] $Operations )
[bool] $retVal = ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::UpdateBuildDefs)
$retVal
}
# =============================================================================
# Returns TRUE if [ADOUpdateOperation] requires the NewBranchName be specified
function Test-RequiresNewBranchName
{
param ( [string[]] $Operations )
$retVal = ($Operations -contains [ADOUpdateOperation]::All `
-or $Operations -contains [ADOUpdateOperation]::AddBranch `
-or $Operations -contains [ADOUpdateOperation]::SetNewDefault `
-or $Operations -contains [ADOUpdateOperation]::CopyPolicies)
$retVal
}
# =============================================================================
# Returns TRUE if [ADOUpdateOperation] requires the NewBranchName be specified
function Test-RequiresOldBranchName
{
param ( [string[]] $Operations )
$retVal = ($Operations -contains [ADOUpdateOperation]::All `
-or $Operations -contains [ADOUpdateOperation]::DeleteBranch `
-or $Operations -contains [ADOUpdateOperation]::CopyPolicies `
-or $Operations -contains [ADOUpdateOperation]::DeletePolicies)
$retVal
}
# =============================================================================
# Execute a command against the ADO Rest API
# TFS 2018 U2 uses version 4.1 of the Azure DevOps API, so all queries are based on the 4.1 version
# ADO Git API Overview: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/?view=azure-devops-rest-4.1
# ADO Policies API Overview: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/?view=azure-devops-rest-4.1
# ADO Build API Overview: https://docs.microsoft.com/en-us/rest/api/azure/devops/build/?view=azure-devops-rest-4.1
function Get-ADODataFromRestMethod
{
param (
$Uri,
$PersonalAccessToken,
$Method = $null,
$Body = $null
)
$resp = $null
if ($null -eq $method)
{
$method = 'GET'
}
# Generate the header from the PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PersonalAccessToken)"))
$headers = @{authorization = "Basic $token"}
try
{
if ($null -eq $body)
{
$resp = Invoke-RestMethod -Uri $Uri -Headers $headers -Method $Method
}
else
{
$resp = Invoke-RestMethod -Uri $Uri -Headers $headers -Method $Method -Body $Body -ContentType 'application/json'
}
}
catch
{
$msg = "ERROR: Error code returned from URI: $Uri"
$msg += "`nStatusCode: $($_.Exception.Response.StatusCode.value__)"
$msg += "`nStatusDescription: $($_.Exception.Response.StatusDescription)"
if ($null -ne $_.ErrorDetails.Message)
{
$msg += "`nDetails: $(($_.ErrorDetails.Message | ConvertFrom-Json).message)"
}
Write-Error $msg
$resp = $null
}
$resp
}
# =============================================================================
# Get the list of all repositories available in a project
# If $ReposToUpdate is specified, filter the list of repositories to only those included in the $ReposToUpdate list
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-4.1
function Get-ADOGitRepositoriesFromProject
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$ReposToUpdate
)
$repoList = $null
$repoListUri = "$adoBaseApisUri/git/repositories?api-version=4.1"
Write-Host "Retrieving the list of repositories from '$repoListUri'" -ForegroundColor 'Magenta'
$resp = Get-ADODataFromRestMethod -Uri $repoListUri -PersonalAccessToken $PersonalAccessToken
if ($null -ne $resp)
{
if ($ReposToUpdate -contains '*')
{
# All of the repos
$repoList = $resp.value
}
else
{
$repoList = ($($resp.value) | Where-Object name -in $ReposToUpdate)
}
}
# Return value
$repoList
}
# =============================================================================
# Get a list of all branches from a repository
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/refs/list?view=azure-devops-rest-4.1
function Get-ADOGitBranchesFromRepository
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$Repository
)
$retVal = $null
Write-Host "Retrieving the list of branches from repository '$($Repository.name)' ($($Repository.id))" -ForegroundColor 'Magenta'
$repoBranchesUri = "$ADOBaseApisUri/git/repositories/$($Repository.id)/refs?api-version=4.1"
$resp = Get-ADODataFromRestMethod -Uri $repoBranchesUri -PersonalAccessToken $PersonalAccessToken
if ($null -ne $resp)
{
$retVal = $resp.value
}
# Return value
$retVal
}
# =============================================================================
# Create a new branch (e.g. 'refs/heads/main') in a specified repository
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/refs/create?view=azure-devops-rest-4.1
function New-ADOGitBranchInRepository
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$Repository,
$OldTopBranchObj,
$GitPathNewTopBranchName
)
$retVal = $null
# Create the new branch
# The objectId of the currentdefaultbranch is the the last commit value
# So, we can create a new branch citing that as our "newObjectId", meaning that branch's history will show that as last commit
Write-Host "Creating branch '$GitPathNewTopBranchName', based from most recent commit from branch '$($OldTopBranchObj.name)' in repository '$($Repository.name)'" -ForegroundColor 'Magenta'
$repoBranchesUri = "$ADOBaseApisUri/git/repositories/$($Repository.id)/refs?api-version=4.1"
$jsonbody = '
[
{
"name": "' + $GitPathNewTopBranchName + '",
"oldObjectId": "0000000000000000000000000000000000000000",
"newObjectId": "' + $OldTopBranchObj.objectId + '"
}
]'
$resp = Get-ADODataFromRestMethod -Uri $repoBranchesUri -PersonalAccessToken $PersonalAccessToken -Method 'POST' -Body $jsonbody
if ($null -ne $resp.value)
{
# Failures show success is "False", for example: updateStatus: invalidRefName, success: False
# When successful, updateStatus is succeeded
$retVal = $resp.value
}
$retVal
}
# =============================================================================
# Deletes the branch from the Repository
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/refs/delete?view=azure-devops-rest-4.1
function Remove-ADOGitBranchFromRepository
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$Repository,
$OldTopBranchObj
)
Write-Host "Deleting '$($OldTopBranchObj.name)' from repo '$($Repository.Name)'" -ForegroundColor 'Magenta'
$repoBranchesUri = "$ADOBaseApisUri/git/repositories/$($Repository.id)/refs?api-version=4.1"
$jsonbody = '
[
{
"name": "' + $OldTopBranchObj.name + '",
"oldObjectId": "' + $OldTopBranchObj.objectId + '",
"newObjectId": "0000000000000000000000000000000000000000"
}
]'
$resp = Get-ADODataFromRestMethod -Uri $repoBranchesUri -PersonalAccessToken $PersonalAccessToken -Method 'POST' -Body $jsonbody
$resp
}
# =============================================================================
# Set a branch (e.g. 'refs/heads/main') as the default branch in the specified repository
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/git/refs/update%20ref?view=azure-devops-rest-4.1
function Set-ADOGitBranchAsDefault
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$Repository,
$GitPathNewTopBranchName
)
Write-Host "Setting '$GitPathNewTopBranchName' as the default branch for repository '$($Repository.Name)'" -ForegroundColor 'Magenta'
$updateRepoUri = "$ADOBaseApisUri/git/repositories/$($Repository.id)?api-version=4.1"
$jsonbody = '{
"name": "' + $Repository.name + '",
"defaultBranch": "' + $GitPathNewTopBranchName + '"
}'
$resp = Get-ADODataFromRestMethod -Uri $updateRepoUri -PersonalAccessToken $PersonalAccessToken -Method 'PATCH' -Body $jsonbody
$resp
}
# =============================================================================
# Gets all of the Git-related policies from an Azure Dev Ops project
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/list?view=azure-devops-rest-4.1
function Get-ADOPoliciesFromProject
{
param (
[Parameter(ParameterSetName = 'OrgProj', Mandatory = $true)]
$OrganizationName,
[Parameter(ParameterSetName = 'OrgProj', Mandatory = $true)]
$ProjectName,
[Parameter(ParameterSetName = 'ADOBaseApiUri', Mandatory = $true)]
$ADOApisUri,
[Parameter(Mandatory = $true)]
$PersonalAccessToken
)
# Get policies so policies applying to master can be applied to main
$policiesGetConfigsUri = $null
if ($null -ne $ADOApisUri)
{
$policiesGetConfigsUri = "$ADOApisUri/policy/configurations?api-version=4.1"
}
else
{
$policiesGetConfigsUri = "https://dev.azure.com/$OrganizationName/$ProjectName/_apis/policy/configurations?api-version=4.1"
}
$resp = Get-ADODataFromRestMethod -Uri $policiesGetConfigsUri -PersonalAccessToken $PersonalAccessToken
$retVal = $null
if ($null -ne $resp)
{
$retVal = $resp.value
}
$retVal
}
# =============================================================================
# Upload a Git policy object to an Azure Dev Ops environment
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/update?view=azure-devops-rest-4.1
function New-ADOGitBranchPolicy
{
param(
$ADOBaseApisUri,
$PersonalAccessToken,
$NewPolicyObj,
$ExistingPolicies
)
# TODO: If a policy already exists for this new branch, a 403 is returned stating "The update is rejected by policy."
# Instead of updating policies assuming new policies for the new branch do not yet exist, instead should verify the new policies against the list of existing
# Add the policy for the new branch
$newPolicyJson = $NewPolicyObj | ConvertTo-Json -Depth 32
$createPolicyUri = "$ADOBaseApisUri/policy/configurations?api-version=4.1"
$resp = Get-ADODataFromRestMethod -Uri $createPolicyUri -PersonalAccessToken $PersonalAccessToken -Method 'POST' -Body $newPolicyJson
$retVal = $false
if ($null -ne $resp)
{
# TODO: This currently relies on Get-ADODataFromRestMethod returning $null when it gets a 403, for example
$retVal = $true
}
$retVal
}
# =============================================================================
# Creates a string with information about a policy for output into a log
function Get-ADOGitPolicyLogString
{
param (
$Policy
)
$scope = $Policy.settings.scope[0]
$msg = "Id = $($Policy.type.id) -- DisplayName = $($Policy.type.displayName) -- scope.refName = $($scope.refName) -- "
if ($null -ne $scope.repositoryId)
{
$msg += "scope.repositoryId = $($scope.repositoryId)"
}
else
{
$msg += "scope.repositoryId = Cross-Repository"
}
$msg
}
# =============================================================================
# Copy the policies applying to the old branch to the new branch
# If $Repository is null, then copy the Project-level policies
# If $Repository is specified, then copy the Repository-level policies
# Create: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create?view=azure-devops-rest-4.1
# Get: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/get?view=azure-devops-rest-4.1
# List: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/list?view=azure-devops-rest-4.1
function Copy-ADOGitBranchPolicies
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$ProjectName,
$Repository,
$GitPathOldTopBranchName,
$GitPathNewTopBranchName
)
$policyList = Get-ADOPoliciesFromProject -ADOApisUri $ADOBaseApisUri -PersonalAccessToken $PersonalAccessToken
if ($null -eq $policyList)
{
# it failed, continue to next repo
Write-Warning "Failed get policy definitions for project '$ProjectName', cannot update policy definitions."
throw
}
foreach ($policy in $policyList)
{
$copyPolicy = $false
foreach ($scope in $policy.settings.scope)
{
if (($null -eq $scope.repositoryId -and $null -eq $Repository) `
-or ($null -ne $scope.repositoryId -and $Repository.id -eq $scope.repositoryId))
{
if ($null -ne $scope.refName -and $scope.refName -eq $GitPathOldTopBranchName)
{
# Use this object as the basis for the new policy we are creating
# This update is done here as there can be (though usually aren't) multiple scopes
$scope.refName = "$GitPathNewTopBranchName"
$copyPolicy = $true
}
}
}
if ($copyPolicy)
{
Write-Host "Copying Policy: $(Get-ADOGitPolicyLogString $policy)" -ForegroundColor 'Magenta'
# Different policies require different fields; not all fields can be specified. The Guids are constant and identify the policy.
# These policies are covered in the Configurations/Create document: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create?view=azure-devops-rest-4.1
$newPolicy = $null
switch ($policy.type.id)
{
# Approval count
'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
minimumApproverCount = $policy.settings.minimumApproverCount
creatorVoteCounts = $policy.settings.creatorVoteCounts
scope = $policy.settings.scope
}
}
}
# Build Policy
'0609b952-1397-4640-95ec-e00a01b2c241'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
buildDefinitionId = $policy.settings.buildDefinitionId
scope = $policy.settings.scope
}
}
}
# Comment Requirement
'c6a1889d-b943-4856-b76f-9e46bb6b0df2'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
scope = $policy.settings.scope
}
}
}
# Merge Strategy
'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
useSquashMerge = $policy.settings.useSquashMerge
scope = $policy.settings.scope
}
}
}
# Required reviewers
'fd2167ab-b0be-447a-8ec8-39368250530e'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = [PSCustomObject] @{
requiredReviewerIds = $policy.settings.requiredReviewerIds
filenamePatterns = $policy.settings.filenamePatterns
message = $policy.settings.message
scope = $policy.settings.scope
}
}
if ($null -ne $policy.settings.addedFilesOnly)
{
# this isn't always present and the RestAPI does not like when it is a null value
$newPolicy.settings | Add-Member -MemberType NoteProperty -Name 'addedFilesOnly' -Value $policy.settings.addedFilesOnly
}
}
# Work Item required
'40e92b44-2fe1-4dd6-b3d8-74a9c21d0c6e'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
scope = $policy.settings.scope
}
}
}
# Require a successful status
'cbdc66da-9728-4af8-aada-9a5a32e4a226'
{
$newPolicy = @{
isEnabled = $policy.IsEnabled
isBlocking = $policy.isBlocking
type = @{ id = $policy.type.id }
settings = @{
statusName = $policy.settings.statusName
statusGenre = $policy.settings.statusGenre
authorId = $policy.settings.authorId
invalidateOnSourceUpdate = $policy.settings.invalidateOnSourceUpdate
defaultDisplayName = $policy.settings.defaultDisplayName
policyApplicability = $policy.settings.policyApplicability
scope = $policy.settings.scope
}
}
}
default
{
Write-Warning "Policy id '$($policy.type.id)' is not recognized, cannot copy policy to new branch"
}
} # Switch statement
# TODO: If adding a policy that already exists, a 403 is returned, which currently makes for a lot of red text
# For the moment, just continue with the loop
$ignoredRetVal = New-ADOGitBranchPolicy -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -NewPolicyObj $newPolicy -ExistingPolicies $null
}
} # foreach policy
# TODO: Need better error handling, especially for the case where a policy already exists
$retVal = $true
$retVal
}
# =============================================================================
# Deletes a policy applying to a branch
# If $Repository is $null, the policy is Project-wide (cross-repository)
# If $Repository is not $null, the policy is a repository-level policy
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/delete?view=azure-devops-rest-4.1
function Remove-ADOGitBranchPolicies
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$ProjectName,
$Repository,
$GitPathOldTopBranchName
)
$policyList = Get-ADOPoliciesFromProject -ADOApisUri $ADOBaseApisUri -PersonalAccessToken $PersonalAccessToken
if ($null -eq $policyList)
{
# it failed, continue to next repo
Write-Warning "Failed get policy definitions for project '$ProjectName', cannot update policy definitions."
throw
}
foreach ($policy in $policyList)
{
$scope = $policy.settings.scope[0]
if (($null -eq $scope.repositoryId -and $null -eq $Repository) `
-or ($null -ne $scope.repositoryId -and $Repository.id -eq $scope.repositoryId))
{
if ($null -ne $scope.refName -and $scope.refName -eq "$GitPathOldTopBranchName")
{
Write-Host "Removing policy: $(Get-ADOGitPolicyLogString $policy)" -ForegroundColor 'Magenta'
# Delete the old one, this returns a 204 if successful
$deletePolicyUri = "$ADOBaseApisUri/policy/configurations/$($policy.id)?api-version=4.1"
$deletePolicyResponse = Get-ADODataFromRestMethod -Uri $deletePolicyUri -PersonalAccessToken $PersonalAccessToken -Method 'DELETE'
if ($null -eq $deletePolicyResponse)
{
Write-Warning "Failed to delete policy '$($policy.type.displayname)' applying to branch '$GitPathOldTopBranchName'"
}
}
}
}
}
# =============================================================================
# Gets the list of Build Pipeline definitions in a project
# Returns a list of build definitions matching those specified in $BuildDefsToUpdate (returns all if '*' is specified)
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/build/definitions/list?view=azure-devops-rest-4.1
function Get-ADOBuildPipelineDefintions
{
param (
$ADOBaseApisUri,
$PersonalAccessToken,
$BuildDefsToUpdate
)
$retVal = $null
$buildDefsBaseUri = "$ADOBaseApisUri/build/definitions?api-version=4.1"
$resp = Get-ADODataFromRestMethod -Uri $buildDefsBaseUri -PersonalAccessToken $PersonalAccessToken
if ($null -ne $resp.value)
{
$allBuildDefs = $resp.value
if ($BuildDefsToUpdate -contains '*')
{
# Match all, so return all
$retVal = $allBuildDefs
}
else
{
$retVal = New-Object -TypeName 'System.Collections.ArrayList'
foreach ($buildDefName in $BuildDefsToUpdate)
{
foreach ($match in ($allBuildDefs | Where-Object name -like $buildDefName))
{
$retVal += $match
}
}
}
}
$retVal
}
# =============================================================================
# Update the default branch of a build defintion
# Reference: https://docs.microsoft.com/en-us/rest/api/azure/devops/build/definitions/update?view=azure-devops-rest-4.1
function Update-ADOBuildPipelineDefaultBranch
{
param(
$ADOBaseApisUri,
$PersonalAccessToken,
$BuildDefinitionToUpdate,
$GitPathNewTopBranchName
)
$retVal = $false
# The URL (note "L", not "I") property of the BuildDefinition points to the most recent version of that definition; query that for the default branch
$buildDefLatestObj = Get-ADODataFromRestMethod -Uri $BuildDefinitionToUpdate.url -PersonalAccessToken $PersonalAccessToken
if ($null -eq $buildDefLatestObj)
{
Write-Warning "Cannot update build definition '$($BuildDefinitionToUpdate.name)', error returned when querying to determine current default branch"
}
elseif ($buildDefLatestObj.repository.defaultBranch -eq $GitPathNewTopBranchName)
{
Write-Host "Build Definition '$($BuildDefinitionToUpdate.name)': default branch is already '$GitPathNewTopBranchName'" -ForegroundColor 'Gray'
$retVal = $true
}
else
{
Write-Host "Updating Build Definition '$($BuildDefinitionToUpdate.name)': setting default branch to '$GitPathNewTopBranchName'" -ForegroundColor 'Magenta'
$buildDefLatestObj.repository.defaultBranch = "$GitPathNewTopBranchName"
$buildDefJson = $buildDefLatestObj | ConvertTo-Json -Depth 32
$buildDefUpdateUri = "$ADOBaseApisUri/build/definitions/$($BuildDefinitionToUpdate.id)?api-version=4.1"
$resp = Get-ADODataFromRestMethod -Uri $buildDefUpdateUri -PersonalAccessToken $PersonalAccessToken -method 'PUT' -body $buildDefJson
if ($null -ne $resp)
{
$retVal = $true
}
}
$retVal
}
# =============================================================================
# Returns the ADO Base APIs URI that is used as the base part of the Uri for the other REST Apis
function Get-ADOBaseApisUri
{
param (
$OrganizationName,
$ProjectName
)
$adoBaseApisUri = "https://dev.azure.com/$OrganizationName/$ProjectName/_apis"
$adoBaseApisUri
}
# =============================================================================
# Do the operations related to the repositories
function Start-RepositoriesUpdate
{
param (
$OrganizationName,
$ProjectName,
$GitPathOldTopBranchName,
$GitPathNewTopBranchName,
$PersonalAccessToken,
$ReposToUpdate,
$Operations
)
# When updating policies on the project level, there's no need to do them more than once
$projectCopyPoliciesComplete = $false
$projectDeletePoliciesComplete = $false
$adoBaseApisUri = Get-ADOBaseApisUri -OrganizationName $OrganizationName -ProjectName $ProjectName
Write-Host "Updating Repositories for the '$OrganizationName/$ProjectName'..." -ForegroundColor 'Green'
# Get the repos in the project, limit down to the repos we specified at the top of the script
$repoList = Get-ADOGitRepositoriesFromProject -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -ReposToUpdate $ReposToUpdate
if ($null -eq $repoList)
{
throw "Failed to retrieve list of repositories from organization '$OrganizationName', project '$ProjectName'"
}
foreach ($repo in $repoList)
{
Write-Host "Updating top-level branch in repository '$($repo.name)' in project '$OrganizationName/$ProjectName'..." -ForegroundColor 'Green'
$repoRefs = Get-ADOGitBranchesFromRepository -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $repo
if ($null -eq $repoRefs)
{
# it failed, continue to next repo
Write-Warning = "Failed to retrieve list of branches from repository '$($repo.name)' ($($repo.id)), in organization '$OrganizationName', project '$ProjectName'"
continue
}
$oldTopBranchObj = $repoRefs | Where-Object name -eq "$GitPathOldTopBranchName"
if ($null -eq $oldTopBranchObj)
{
Write-Warning "There exists no branch named '$GitPathOldTopBranchName' in repository '$($repo.name)', continuing to next repo in list."
continue
}
# This will be null if the new top branch does not yet exist
$newTopBranchObj = $repoRefs | Where-Object name -eq $GitPathNewTopBranchName
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::AddBranch)
{
if ($null -eq $newTopBranchObj)
{
# Create the new branch, including all history from the last commit on the old branch
$newBranchResponse = New-ADOGitBranchInRepository -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $repo -OldTopBranchObj $oldTopBranchObj -GitPathNewTopBranchName $GitPathNewTopBranchName
if ($null -eq $newBranchResponse -or $false -eq $newBranchResponse.success)
{
# Failures show success is "False", for example
# updateStatus : invalidRefName, success : False
# When successful, updateStatus is succeeded
$warnMsg = "Failed to create branch '$GitPathNewTopBranchName' in repository '$($repo.name), continuing to next repo in list.'"
if ($null -ne $newBranchResponse.updateStatus)
{
$warnMsg += "`nUpdateStatus returned: $($newBranchResponse.updateStatus)"
}
Write-Warning $warnMsg
continue
}
}
else
{
# The branch that the user wants to create already exists
Write-Warning "Repo '$($repo.Name)' already has branch '$GitPathNewTopBranchName'. Skipping creation of branch."
}
}
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::SetNewDefault)
{
if ($repo.defaultBranch -eq "$GitPathNewTopBranchName")
{
# Already has this branch, so continue
Write-Host "Repo '$($repo.name)' already has '$NewBranchName' as the default branch, continuing to next repo."
}
else
{
$setDefaultResponse = Set-ADOGitBranchAsDefault -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $repo -GitPathNewTopBranchName $GitPathNewTopBranchName
if ($null -eq $setDefaultResponse.defaultBranch -or $setDefaultResponse.defaultBranch -ne $GitPathNewTopBranchName)
{
$warnMsg = "Failed to set '$GitPathNewTopBranchName' as default branch in repository '$($repo.name). Continuing to next repo in list."
if ($null -ne $setDefaultResponse.defaultBranch)
{
$warnMsg += "`nDefault branch for repository '$($repo.name)' is: '$($setDefaultResponse.defaultBranch)'"
}
Write-Warning $warnMsg
continue
}
}
}
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::CopyPolicies)
{
# Copy policies applying to the old top level branch to the new one
# TODO: If a policy already exists, it returns a 403. Ignore the response until better handling is implemented
Write-Host "Copying repository-level policies in repository '$($repo.name)' that apply to '$GitPathOldTopBranchName' to new branch '$GitPathNewTopBranchName'" -ForegroundColor 'Magenta'
$ignoredRetVal = Copy-ADOGitBranchPolicies -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -ProjectName $ProjectName `
-Repository $repo -GitPathOldTopBranchName $GitPathOldTopBranchName -GitPathNewTopBranchName $GitPathNewTopBranchName
if ($false -eq $projectCopyPoliciesComplete)
{
# TODO: See note regarding the return value above
Write-Host "Copying any project-level policies that apply to '$GitPathOldTopBranchName' to new branch '$GitPathNewTopBranchName'" -ForegroundColor 'Magenta'
$ignoredRetVal = Copy-ADOGitBranchPolicies -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -ProjectName $ProjectName `
-Repository $null -GitPathOldTopBranchName $GitPathOldTopBranchName -GitPathNewTopBranchName $GitPathNewTopBranchName
}
}
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::DeletePolicies)
{
# Delete the policies that apply to the old branch
# TODO: See note regarding return value in CopyPolicies section above
Write-Host "Deleting any repository-level policies (repository '$($repo.name)') that apply to branch '$GitPathOldTopBranchName'" -ForegroundColor 'Magenta'
$ignoredRetVal = Remove-ADOGitBranchPolicies -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $repo -GitPathOldTopBranchName $GitPathOldTopBranchName
if ($ReposToUpdate -contains '*' -and $false -eq $projectDeletePoliciesComplete)
{
# Updating all repositories in the project, so delete the project-wide policies
# TODO: See note regarding return value in CopyPolicies section above
Write-Host "Deleting any project-level policies (proejct '$ProjectName') that apply to branch '$GitPathOldTopBranchName'" -ForegroundColor 'Magenta'
$ignoredRetVal = Remove-ADOGitBranchPolicies -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $null -GitPathOldTopBranchName $GitPathOldTopBranchName
}
}
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::DeleteBranch)
{
# Delete the branch from this repo
# Note: this may fail because of inherited policies requiring Merges to complete operations, so it should occur after policies applying to it are removed
$branchRemovedResponse = Remove-ADOGitBranchFromRepository -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -Repository $repo -OldTopBranchObj $oldTopBranchObj
if ($null -eq $branchRemovedResponse -or $false -eq $branchRemovedResponse.success)
{
$warnMsg = "Failed to delete $($OldTopBranchObj.name) from repository $($repo.name)"
if ($null -ne $branchRemovedResponse.updateStatus)
{
$warnMsg += "`nUpdateStatus returned: $($branchRemovedResponse.updateStatus)"
}
Write-Warning $warnMsg
}
}
}
}
# =============================================================================
# Update the build definitions for this project
function Start-BuildDefinitionsUpdate
{
param (
$OrganizationName,
$ProjectName,
$GitPathNewTopBranchName,
$PersonalAccessToken,
$BuildDefsToUpdate,
$Operations
)
$adoBaseApisUri = Get-ADOBaseApisUri -OrganizationName $OrganizationName -ProjectName $ProjectName
if ($Operations -contains [ADOUpdateOperation]::All -or $Operations -contains [ADOUpdateOperation]::UpdateBuildDefs)
{
# Get the build definitions for the Project
Write-Host "Updating Build Pipeline Definitions for the '$OrganizationName/$ProjectName'..." -ForegroundColor 'Green'
$matchedBuildDefs = Get-ADOBuildPipelineDefintions -ADOBaseApisUri $adoBaseApisUri -PersonalAccessToken $PersonalAccessToken -BuildDefsToUpdate $BuildDefsToUpdate
if ($null -eq $matchedBuildDefs)
{
# it failed, continue to next repo
Write-Warning "Failed get build definitions for project '$ProjectName', cannot update build definitions."
throw
}
if ($matchedBuildDefs.Count -eq 0)
{
Write-Warning 'No build definitions matched the wildcard filters provided in the ''BuildDefsToUpdate'' parameter!'
}