forked from GoogleCloudPlatform/dotnet-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuildTools.psm1
1279 lines (1215 loc) · 43.4 KB
/
BuildTools.psm1
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
# Copyright(c) 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
##############################################################################
# HOW TO USE THE FUNCTIONS IN THIS MODULE
##############################################################################
<#
PS ...> Import-Module .\BuildTools.psm1
WARNING: The names of some imported commands from the module 'BuildTools' include unapproved verbs that might make them less
discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For
a list of approved verbs, type Get-Verb.
PS ...> cd .\aspnet\2-structured-data
PS ...\aspnet\2-structured-data> Run-TestScripts
...
0 SUCCEEDED
2 FAILED
.\runTestsWithDatastore.ps1
.\runTestsWithSql.ps1
# Oh no! My tests failed. I forgot to update the Web.Configs from my
# environment variables.
PS ...\aspnet\2-structured-data> Update-Config
.\Web.config is modified. Overwrite? [Y]es, [N]o, Yes to [A]ll: a
C:\Users\Jeffrey Rennie\gitrepos\getting-started-dotnet\aspnet\2-structured-data\Web.config
C:\Users\Jeffrey Rennie\gitrepos\getting-started-dotnet\aspnet\2-structured-data\Views\Web.config
# And run the tests again.
PS ...\aspnet\2-structured-data> Run-TestScripts
...
2 SUCCEEDED
.\runTestsWithDatastore.ps1
.\runTestsWithSql.ps1
0 FAILED
# Yay! They succeeded.
# I can also just run any test script directly:
PS ...\aspnet\2-structured-data> .\runTestsWithDatastore.ps1
...
PASS 4 tests executed in 10.671s, 4 passed, 0 failed.
# Or, I can run the test and leave IISExpress running to debug:
PS ...\aspnet\2-structured-data> Set-BookStore mysql
PS ...\aspnet\2-structured-data> Run-IISExpressTest -LeaveRunning
# Don't submit the changes to Web.configs.
PS ...\aspnet\2-structured-data> Unstage-Config
Unstaged changes after reset:
M aspnet/2-structured-data/Views/Web.config
M aspnet/2-structured-data/Web.config
# Submit my changes.
PS ...\aspnet\2-structured-data>git commit
# Clean up, cause I'm done.
PS ...\aspnet\2-structured-data> Revert-Config
#>
##############################################################################
#.SYNOPSIS
# Adds a setting to a Web.config configuration.
#
#.PARAMETER Config
# The root xml object from a Web.config or App.config file.
#
#.PARAMETER Key
# The name of the key to set.
#
#.PARAMETER Value
# The value to set.
#
#.EXAMPLE
# Add-Setting $config 'GoogleCloudSamples:ProjectId' $env:GoogleCloudSamples:ProjectId
##############################################################################
function Add-Setting($Config, [string]$Key, [string]$Value) {
$x = Select-Xml -Xml $Config.Node -XPath "appSettings/add[@key='$Key']"
if ($x) {
$x.Node.value = $Value
}
}
##############################################################################
#.SYNOPSIS
# Logical operator.
#
#.DESCRIPTION
# When anything in pipelined to the function, outputs the inputs.
# Otherwise, evaluates the script block and returns the result.
#
#.PARAMETER ScriptBlock
# The script block to execute if $input is empty.
##############################################################################
function When-Empty($Target, $ArgList, [ScriptBlock]$ScriptBlock) {
if ($Target) {
@($Target) + $ArgList
} elseif ($ArgList) {
$ArgList
} else {
&$ScriptBlock
}
}
##############################################################################
#.SYNOPSIS
# Finds all the Web.config files in subdirectories.
#
##############################################################################
filter Get-Config ($Target, $ArgList, $Mask="Web.config") {
$paths = When-Empty $Target $ArgList {Find-Files -Masks $Mask}
if ($paths) {
$paths | Resolve-Path -Relative
}
}
##############################################################################
#.SYNOPSIS
# Updates Web.config files, pulling values from environment variables.
#
#.DESCRIPTION
# Asks the user before overwriting files that have already been modified.
# Don't forget to Revert-Config or Unstage-Config before 'git commit'ing!
#
#.PARAMETER Yes
# Never ask the user if they want to overwrite a modified Web.config. Just
# overwrite it.
#
#.INPUTS
# Paths to Web.config. If empty, recursively searches directories for
# Web.config files.
#
#.OUTPUTs
# Paths to Web.configs that this function modified.
#
#.EXAMPLE
# Update-Config
##############################################################################
filter Update-Config ([switch]$Yes) {
$configs = Get-Config $_ $args
foreach($configPath in $configs) {
if (-not $Yes -and (git status -s $configPath)) {
do {
$reply = Read-Host "$configPath is modified. Overwrite? [Y]es, [N]o, Yes to [A]ll"
} until ("y", "n", "a" -contains $reply)
if ("n" -eq $reply) { continue }
if ("a" -eq $reply) { $Yes = $true }
}
$config = Select-Xml -Path $configPath -XPath configuration
if (-not $config) {
continue;
}
Add-Setting $config 'GoogleCloudSamples:BookStore' $env:GoogleCloudSamples:BookStore
Add-Setting $config 'GoogleCloudSamples:ProjectId' $env:GoogleCloudSamples:ProjectId
Add-Setting $config 'GoogleCloudSamples:BucketName' $env:GoogleCloudSamples:BucketName
Add-Setting $config 'GoogleCloudSamples:AuthClientId' $env:GoogleCloudSamples:AuthClientId
Add-Setting $config 'GoogleCloudSamples:AuthClientSecret' $env:GoogleCloudSamples:AuthClientSecret
$connectionString = Select-Xml -Xml $config.Node -XPath "connectionStrings/add[@name='LocalMySqlServer']"
if ($connectionString) {
if ($env:GoogleCloudSamples:ConnectionString) {
$connectionString.Node.connectionString = $env:GoogleCloudSamples:ConnectionString;
} elseif ($env:Data:MySql:ConnectionString) {
# TODO: Stop checking this old environment variable name when we've
# updated all the scripts.
$connectionString.Node.connectionString = $env:Data:MySql:ConnectionString;
}
}
$config.Node.OwnerDocument.Save($config.Path);
$config.Path
}
}
##############################################################################
#.SYNOPSIS
# Updates Web.config files. Sets the BookStore setting.
#
#.INPUTS
# Paths to Web.config. If empty, recursively searches directories for
# Web.config files.
#
#.EXAMPLE
# Set-BookStore mysql
##############################################################################
filter Set-BookStore($BookStore) {
$configs = Get-Config $_ $args
foreach($configPath in $configs) {
$config = Select-Xml -Path $configPath -XPath configuration
Add-Setting $config 'GoogleCloudSamples:BookStore' $BookStore
$config.Node.OwnerDocument.Save($config.Path)
}
}
##############################################################################
#.SYNOPSIS
# Reverts Web.config files.
#
#.DESCRIPTION
# git must be in the current PATH.
#
#.INPUTS
# Paths to Web.config. If empty, recursively searches directories for
# Web.config files.
##############################################################################
filter Revert-Config {
$configs = Get-Config $_ $args
$silent = git reset HEAD $configs
git checkout -- $configs
}
##############################################################################
#.SYNOPSIS
# Unstages Web.config files.
#
#.DESCRIPTION
# git must be in the current PATH.
#
#.INPUTS
# Paths to Web.config. If empty, recursively searches directories for
# Web.config files.
##############################################################################
filter Unstage-Config {
$configs = Get-Config $_ $args
git reset HEAD $configs
}
##############################################################################
#.SYNOPSIS
# Recursively find all the files that match a mask.
#
#.PARAMETER Path
# Start searching from where? Defaults to the current directory.
#
#.PARAMETER Masks
# A list of masks to match against the files.
#
#.PARAMETER MaxDepth
# How deep should we look into subdirectories? Default is no limit.
#
#.PARAMETER AntiMasks
# Stop recursing when we reach a directory with a matching name.
#
#.EXAMPLE
# Find-Files -Masks *.txt
##############################################################################
function Find-Files($Path = $null, [string[]]$Masks = '*', $MaxDepth = -1,
$Depth=0, [string[]]$AntiMasks = @('bin', 'obj', 'packages', '.git'))
{
foreach ($item in Get-ChildItem $Path | Sort-Object -Property Mode,Name)
{
if ($Masks | Where {$item -like $_})
{
$item.FullName
}
if ($AntiMasks | Where {$item -like $_})
{
# Do not recurse.
}
elseif ($MaxDepth -ge 0 -and $Depth -ge $MaxDepth)
{
# We have reached the max depth. Do not recurse.
}
elseif (Test-Path $item.FullName -PathType Container)
{
Find-Files $item.FullName $Masks $MaxDepth ($Depth + 1) $AntiMasks
}
}
}
##############################################################################
#.SYNOPSIS
# Look for a matching file in this directory and parent directories.
#
#.PARAMETER Masks
# A list of masks to match against the files.
#
#.EXAMPLE
# UpFind-File *.txt
##############################################################################
function UpFind-File([string[]]$Masks = '*')
{
$dir = Get-Item .
while (1)
{
foreach ($item in Get-ChildItem $dir | Sort-Object -Property Mode,Name)
{
if ($Masks | Where {$item -like $_})
{
return $item.FullName
}
}
if (!$dir.parent)
{
return
}
$dir = Get-Item $dir.parent.FullName
}
}
##############################################################################
#.SYNOPSIS
# Sets the timeout for a runTests.ps1.
#
#.DESCRIPTION
# When Run-TestScripts calls a runTests.ps1, then the runTests.ps1 can call
# Set-TestTimeout to override the default timeout.
#
#.EXAMPLE
# Set-TestTimeout 900
##############################################################################
function Set-TestTimeout($seconds) {
New-Object PSObject -Property @{TimeoutSeconds = $seconds}
}
##############################################################################
#.SYNOPSIS
# Skips the currently running test. Exits the currently running script.
#
#.EXAMPLE
# Skip-Test
##############################################################################
function Skip-Test() {
New-Object PSObject -Property @{Skipped = $true} | Write-Output
exit
}
##############################################################################
#.SYNOPSIS
# Checks the currrently running platform. Exits if it's the wrong one.
#
#.EXAMPLE
# Require-Platform Win*
##############################################################################
function Require-Platform([string[]] $platforms) {
foreach ($platform in $platforms) {
if ([environment]::OSVersion.Platform -match $platform) {
return
}
}
Skip-Test
}
$junitOutputTemplate = @"
<testsuites failures="" tests="1" time="">
<testsuite id="0" failures="" name="" tests="1" time="">
<testcase classname="runTests" name="runTests" time="">
</testcase>
</testsuite>
</testsuites>
"@
##############################
#.SYNOPSIS
# Composes a junit xml file that reports a build failure, or timeout.
#
#.PARAMETER script
# The path the the test script that failed.
#
#.PARAMETER log
# The output of the test script.
#
#.PARAMETER elapsed
# The time spent running the test script.
#
#.PARAMETER timedOut
# $True when the test scripped timed out rather than failed.
##############################
function Write-FailureXml([string]$script, [string[]] $log,
[System.TimeSpan]$elapsed, [switch]$timedOut)
{
$elapsedSeconds = [string] $elapsed.TotalSeconds
$xml = [xml]$junitOutputTemplate
$xml.testsuites.failures = "1"
$xml.testsuites.time = $elapsedSeconds
$xml.testsuites.testsuite.name = $script
$xml.testsuites.testsuite.time = $elapsedSeconds
$xml.testsuites.testsuite.failures = "1"
$xml.testsuites.testsuite.testcase.time = $elapsedSeconds
$errorMessage = if ($timedOut) { 'TIMED OUT' } else { 'BUILD FAILED' }
$errorXml = [xml]"<error message='$errorMessage' />"
$errorXml.FirstChild.InnerText = ($log -join "`n") + "`n$errorMessage"
$xml.testsuites.testsuite.testcase.AppendChild($xml.ImportNode(
$errorXml.FirstChild, $True)) | Out-Null
$testResultsXml = Join-Path (Split-Path -Parent $script) "TestResults.xml"
$xml.Save($testResultsXml)
}
##############################
#.SYNOPSIS
# Composes a junit test script reporting a skipped test.
#
#.PARAMETER script
# The path the the test script that failed.
#
#.PARAMETER elapsed
# The time spent running the test script.
##############################
function Write-SkippedXml([string]$script, [System.TimeSpan]$elapsed)
{
$elapsedSeconds = [string] $elapsed.TotalSeconds
$xml = [xml]$junitOutputTemplate
$xml.testsuites.failures = "0"
$xml.testsuites.time = $elapsedSeconds
$xml.testsuites.testsuite.name = $script
$xml.testsuites.testsuite.time = $elapsedSeconds
$xml.testsuites.testsuite.failures = "0"
$xml.testsuites.testsuite.testcase.time = $elapsedSeconds
$skippedXml = [xml]'<skipped/>'
$xml.testsuites.testsuite.testcase.AppendChild($xml.ImportNode(
$skippedXml.FirstChild, $True)) | Out-Null
$testResultsXml = Join-Path (Split-Path -Parent $script) "TestResults.xml"
$xml.Save($testResultsXml)
}
##############################
#.SYNOPSIS
# Runs the list of test scripts.
#
#.DESCRIPTION
# Runs each test script once. Records the results in $Results.
#
#.PARAMETER Scripts
# A list of scripts to run. An array of Items.
#
#.PARAMETER TimeoutSeconds
# Give up if a test script takes longer than TimeoutSeconds to run.
#
#.PARAMETER Verb
# Verb to print in output message.
#
#.PARAMETER Results
# Gets filled with the resulting job status and list. For example:
# { 'Failed' = @('.\pubsub\api\PubsubTest\runTest.ps1');
# 'Succeeded' = @('.\trace\api\runTests.ps1', '.\storage\api\runTests.ps1') }
##############################
function Run-TestScriptsOnce([array]$Scripts, [int]$TimeoutSeconds,
[string]$Verb, [hashtable]$Results)
{
foreach ($script in $Scripts) {
$startDate = Get-Date
$relativePath = Resolve-Path -Relative $script
$jobState = 'Failed'
$tempOut = [System.IO.Path]::GetTempFileName()
Write-Output "$verb $relativePath..."
$job = Start-Job -ArgumentList $relativePath, $script.Directory, `
('.\"{0}"' -f $script.Name) {
$ErrorActionPreference = "Stop"
Write-Output ("-" * 79)
Write-Output $args[0]
Set-Location $args[1]
Invoke-Expression $args[2]
if ($LASTEXITCODE) {
throw "FAILED with exit code $LASTEXITCODE"
}
}
# Call Receive-Job every second so the stdout for the job
# streams to my stdout.
while ($true) {
Wait-Job $job -Timeout 1 | Out-Null
$jobState = $job.State
foreach ($line in (Receive-Job $job) | Tee-Object -Append -FilePath $tempOut) {
# Look at the output of the job to see if it requested
# a longer timeout.
if ($line.TimeoutSeconds) {
$TimeoutSeconds = $line.TimeoutSeconds
"Set timeout to $TimeoutSeconds seconds."
} elseif ($line.Skipped) {
Write-Output "SKIPPED"
$jobState = 'Skipped'
break
} else {
$line
}
}
if ($jobState -eq 'Running') {
$deadline = $startDate.AddSeconds($TimeoutSeconds)
if ((Get-Date) -gt $deadline) {
Write-Output "TIME OUT"
$jobState = 'Timed Out'
break
}
} else {
break
}
}
$results[$jobState] += @($relativePath)
# If the script left no TestResults.xml, create one.
$parentDir = (Get-Item $script).Directory
if ($jobState -ne 'Completed' -and -not (Get-ChildItem -Path $parentDir -Recurse -Filter TestResults.xml)) {
$elapsed = (Get-Date) - $startDate
if ($jobState -eq 'Skipped') {
Write-SkippedXml $script $elapsed
} else {
$job.ChildJobs[0].JobStateInfo.Reason.Message | Out-File -Append -FilePath $tempOut
$job.ChildJobs[0].Error | Out-File -Append -FilePath $tempOut
Write-FailureXml $script (Get-Content $tempOut) $elapsed -timedOut:($jobState -eq 'Timed Out')
}
}
Remove-Job -Force $job
}
}
##############################################################################
#.SYNOPSIS
# Runs powershell scripts and prints a summary of successes and errors.
#
#.INPUTS
# Powershell scripts. If empty, recursively searches directories for
# scripts with 'runtests' in their names.
#
#.EXAMPLE
# Run-Tests
##############################################################################
function Run-TestScripts($TimeoutSeconds=300) {
$scripts = When-Empty -ArgList ($input + $args) -ScriptBlock { Find-Files -Masks '*runtests*.ps1' } | Get-Item
# Keep running lists of successes and failures.
$results = @{}
Run-TestScriptsOnce $scripts $TimeoutSeconds 'Starting' $results
# Rename all the test logs to a name Sponge will find.
Get-ChildItem -Recurse TestResults.xml | Rename-Item -Force -NewName 01_sponge_log.xml
# Retry the failures once.
$failed = $results['Failed']
if ($failed) {
$results['Failed'] = @()
Run-TestScriptsOnce ($failed | Get-Item) $TimeoutSeconds `
'Retrying' $results
# Rename all the test logs to a name Sponge will find.
Get-ChildItem -Recurse TestResults.xml | Rename-Item -Force -NewName 02_sponge_log.xml
}
# Print a final summary.
Write-Output ("=" * 79)
foreach ($key in $results.Keys) {
$count = $results[$key].Length
$result = $key.Replace('Completed', 'Succeeded').ToUpper()
Write-Output "$count $result"
Write-Output $results[$key]
}
# Throw an exception to set ERRORLEVEL to 1 in the calling process.
$failureCount = $results['Failed'].Length
if ($failureCount) {
throw "$failureCount FAILED"
}
$timeOutCount = $results['Timed Out'].Length
if ($timeOutCount) {
throw "$timeOutCount TIMED OUT"
}
}
##############################################################################
#.SYNOPSIS
# Runs code formatter on a project or solution.
#
#.INPUTS
# .sln and .csproj files. If empty, recursively searches directories for
# project files.
#
#.EXAMPLE
# Format-Code
##############################################################################
filter Format-Code {
$projects = When-Empty $_ $args { Find-Files -Masks *.csproj }
foreach ($project in $projects) {
Backup-File -Files $project -ScriptBlock {
Convert-2003ProjectToCore $project
"codeformatter.exe $project" | Write-Host
codeformatter.exe /rule:BraceNewLine /rule:ExplicitThis `
/rule-:ExplicitVisibility /rule:FieldNames `
/rule:FormatDocument /rule:ReadonlyFields /rule:UsingLocation `
/nocopyright $project
if ($LASTEXITCODE) {
$project.FullName
throw "codeformatter failed with exit code $LASTEXITCODE."
}
}
}
}
$coreProjectText = @"
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Include="Program.cs" />
</ItemGroup>
</Project>
"@
##############################################################################
#.SYNOPSIS
# Converts .NET Core csproj to MSBuild 2003.
#
#.DESCRIPTION
# Creates the bare minimal project for code-formatter to work.
# If you open the project with Visual Studio everything will be broken.
#
#.PARAMETER csproj
# A project to convert.
#
#.EXAMPLE
# Convert-2003ProjectToCore AuthSample.csproj
##############################################################################
function Convert-2003ProjectToCore($csproj) {
$cspath = (Resolve-Path $csproj).Path
$xml = [xml](Get-Content $csproj)
if (-not $xml.Project.xmlns -eq "http://schemas.microsoft.com/developer/msbuild/2003") {
Write-Host "Converting .NET core $cspath to msbuild/2003..."
$doc = [xml]$coreProjectText
$group = $doc.Project.ItemGroup
$compileTemplate = $group.Compile
$sourceFiles = (Get-ChildItem -Path (Split-Path $cspath) -Filter "*.cs")
foreach ($sourceFile in $sourceFiles) {
$compile = $compileTemplate.Clone()
$compile.Include = $sourceFile.FullName
$group.AppendChild($compile) | Out-Null
}
$group.RemoveChild($compileTemplate) | Out-Null
$doc.save($cspath)
} else {
Write-Host "$cspath looks like a 2003 .csproj to me!"
$doc = [xml] (Get-Content $cspath)
# This one import causes codeformatter to choke. Turn it off.
foreach ($import in $doc.Project.Import | Where-Object `
{$_.Project -like '*\Microsoft.WebApplication.targets'})
{
$import.Condition = 'false'
}
$doc.save($cspath)
}
}
##############################################################################
#.SYNOPSIS
# Runs code formatter on a project or solution.
#
#.DESCRIPTION Throws an exception if code formatter actually changed something.
#
#.INPUTS
# .sln and .csproj files. If empty, recursively searches directories for
# project files.
#
#.EXAMPLE
# Lint-Project
##############################################################################
filter Lint-Code {
$projects = When-Empty $_ $args { Find-Files -Masks *.csproj }
foreach ($project in $projects) {
@($project) | Format-Code
# If git reports a diff, codeformatter changed something, and that's bad.
$diff = git diff
if ($diff) {
$diff
throw "Lint failed for $_"
}
}
$utf16 = Find-Utf16
if ($utf16) {
$utf16
throw "Found UTF-16 encoded source files. Run Find-Utf16 | ConvertTo-Utf8 to fix."
}
}
##############################################################################
#.SYNOPSIS
# Builds the .sln in the current working directory.
#
#.DESCRIPTION
# Invokes nuget first, then msbuild. Throws an exception if nuget or the
# build fails.
##############################################################################
function Build-Solution($solution) {
nuget restore $solution
if ($LASTEXITCODE) {
throw "Nuget failed with error code $LASTEXITCODE"
}
msbuild /p:Configuration=Debug $solution
if ($LASTEXITCODE) {
throw "Msbuild failed with error code $LASTEXITCODE"
}
}
##############################################################################
#.SYNOPSIS
# Gets the port number for an IISExpress web site.
#
#.PARAMETER SiteName
# The name of the website, as listed in applicationhost.config
#
#.PARAMETER ApplicationhostConfig
# The path to applicationhost.config.
#
#.OUTPUTS
# The port number where the web site is specified to run.
##############################################################################
function Get-PortNumber($SiteName, $ApplicationhostConfig) {
$node = Select-Xml -Path $ApplicationhostConfig `
-XPath "/configuration/system.applicationHost/sites/site[@name='$SiteName']/bindings/binding" |
Select-Object -ExpandProperty Node
$chunks = $node.bindingInformation -split ':'
$chunks[1]
}
##############################################################################
#.SYNOPSIS
# Runs IISExpress for a web site.
#
#.PARAMETER SiteName
# The name of the website, as listed in applicationhost.config
#
#.PARAMETER ApplicationhostConfig
# The path to applicationhost.config.
#
#.OUTPUTS
# The process object
##############################################################################
function Run-IISExpress($SiteName, $ApplicationhostConfig) {
if (!$SiteName) {
$SiteName = (get-item -Path ".\").Name
}
if (!$ApplicationhostConfig) {
$ApplicationhostConfig = UpFind-File 'applicationhost.config'
}
$argList = ('/config:"' + $ApplicationhostConfig + '"'), "/site:$SiteName", "/apppool:Clr4IntegratedAppPool"
Start-Process iisexpress.exe -ArgumentList $argList -PassThru
}
##############################################################################
#.SYNOPSIS
# Run the website, then run the test javascript file with casper.
#
#.DESCRIPTION
# Throws an exception if the test fails.
#
#.PARAMETER SiteName
# The name of the website, as listed in applicationhost.config.
#
#.PARAMETER ApplicationhostConfig
# The path to applicationhost.config. If not
# specified, searches parent directories for the file.
#
##############################################################################
function Run-IISExpressTest($SiteName = '', $ApplicationhostConfig = '',
$TestJs = 'test.js', [switch]$LeaveRunning = $false) {
if (!$SiteName) {
$SiteName = (get-item -Path ".\").Name
}
if (!$ApplicationhostConfig) {
$ApplicationhostConfig = UpFind-File 'applicationhost.config'
}
$port = Get-PortNumber $SiteName $ApplicationhostConfig
$webProcess = Run-IISExpress $SiteName $ApplicationhostConfig
Try
{
Start-Sleep -Seconds 4 # Wait for web process to start up.
Run-CasperJs $TestJs http://localhost:$port -v11
if ($LASTEXITCODE) {
throw "Casperjs failed with error code $LASTEXITCODE"
}
}
Finally
{
if (!$LeaveRunning) {
Stop-Process $webProcess
}
}
}
##############################################################################
#.SYNOPSIS
# Run the website.
#
#.PARAMTER url
# The partial url to serve. It should contain the scheme and host. For
# example: https://localhost:2342
#
#.RETURNS
# The job running kestrel.
##############################################################################
function Run-Kestrel([Parameter(mandatory=$true)][string]$url)
{
$kestrelJob = Start-Job -ArgumentList (Get-Location), $url -ScriptBlock {
Set-Location $args[0]
$env:ASPNETCORE_URLS = $args[1]
dotnet run
}
# Wait for Kestrel to come up.
while(-not $started) {
Start-Sleep -Seconds 1
$lines = Receive-Job $kestrelJob
$lines | Write-Host
if (($kestrelJob | Get-Job).State -ne 'Running') {
throw "Kestrel failed to start."
}
foreach ($line in $lines) {
if ($line -like 'Application started.*') {
return $kestrelJob
}
}
$seconds++
if ($seconds -gt 120) {
throw "Kestrel took > 120 seconds to start up."
}
}
}
##############################################################################
#.SYNOPSIS
# Run the website, then run the test javascript file with casper.
#
#.PARAMETER PortNumber
# The port number to run the kestrel server on.
#
#.DESCRIPTION
# Throws an exception if the test fails.
#
##############################################################################
function Run-KestrelTest([Parameter(mandatory=$true)]$PortNumber, $TestJs = 'test.js',
[switch]$LeaveRunning = $false, [switch]$CasperJs11 = $false) {
$url = "http://localhost:$PortNumber"
$job = Run-Kestrel $url
Try
{
Run-CasperJs $TestJs $Url -v11:$CasperJs11
}
Finally
{
if (!$LeaveRunning) {
Stop-Job $job
Receive-Job $job
Remove-Job $job
}
}
}
##############################
#.SYNOPSIS
# Moves TestResults.xml into an output subdirectory.
#
#.PARAMETER OutDir
#The directory to which to move TestResults.xml. This directory will be created
#if it does not already exist.
##############################
function Move-TestResults($OutDir) {
if ($OutDir -and (Test-Path TestResults.xml)) {
New-Item -ItemType Directory -Force -Path $OutDir
Move-Item -Force TestResults.xml $OutDir
}
}
##############################
#.SYNOPSIS
# Runs CasperJs
#
#.PARAMETER TestJs
# The Javascript file to run.
#
#.PARAMETER Url
# The url to pass to the test. Usually points to running website to test.
#
#.PARAMETER v11
# Use CasperJs version 1.1 instead of 1.0.
##############################
function Run-CasperJs($TestJs='test.js', $Url, [switch]$v11 = $false,
[string]$OutDir) {
if ($v11) {
$env:CASPERJS11_URL = $Url
# Casperjs.exe creates a new terminal window, from which we
# cannot capture output. So we use python to invoke it and
# capture output.
$casperOut = python (Join-Path $env:CASPERJS11_BIN "casperjs") `
-- test --xunit=TestResults.xml $TestJs
# Casper 1.1 always returns 0, so inspect the xml output
# to see if a test failed.
[xml]$x = Get-Content TestResults.xml
$LASTEXITCODE = 0
foreach ($suite in $x.testsuites.testsuite) {
$LASTEXITCODE += [int] $suite.failures
}
} else {
$casperOut = casperjs $TestJs $Url
}
if ($LASTEXITCODE -eq 0) {
$casperOut | Write-Host
return
}
$casperOut | Write-Host
throw "Casperjs failed with error code $LASTEXITCODE"
}
##############################################################################
#.SYNOPSIS
# Deploy a dotnet core application to appengine and test it.
#
#.DESCRIPTION
# Assumes the app was already build with "dotnet publish."
# Assumes there is a subdirectory called appengine containing app.yaml and Dockerfile.
#
#.PARAMETER DllName
# The name of the built binary. Defaults to the current directory name.
##############################################################################
function Deploy-CasperJsTest($testJs ='test.js') {
while ($true) {
$yamls = Get-Item .\bin\debug\netcoreapp*\publish\*.yaml | Resolve-Path -Relative
echo "gcloud beta app deploy --quiet --no-promote -v deploytest $yamls"
gcloud beta app deploy --quiet --no-promote -v deploytest $yamls
if ($LASTEXITCODE -eq 0) {
break
}
if (++$deployCount -gt 2) {
throw "gcloud app deploy failed with exit code $LASTEXITCODE"
}
}
gcloud app describe | where {$_ -match 'defaultHostName:\s+(\S+)' }
try {
Run-CasperJs $testJs ("https://deploytest-dot-" + $matches[1])
return
} catch {
# Work around issue 35673193.
Run-CasperJs $testJs ("https://deploytest-dot-" + $matches[1].Replace('appspot.com', 'appspot-preview.com'))
}
}
##############################################################################
#.SYNOPSIS
# Migrate the database.
#
#.DESCRIPTION
# Must be called from a directory with a .csproj and Web.config.
#
#.PARAMETER DllName
# The name of the built binary. Defaults to the current directory name.
##############################################################################
function Migrate-Database($DllName = '') {
if (!$DllName) {
# Default to the name of the current directory + .dll
# For example, if the current directory is 3-binary-data, then the
# dll name will be 3-binary-data.dll.
$DllName = (get-item .).Name + ".dll"
}
# Migrate.exe cannot be run in place. It must be copied to the bin directory
# and run from there.
cp (Join-Path (UpFind-File packages) EntityFramework.*\tools\migrate.exe) bin\.
$originalDir = pwd
Try {
cd bin
.\migrate.exe $dllName /startupConfigurationFile="..\Web.config"
if ($LASTEXITCODE) {
throw "migrate.exe failed with error code $LASTEXITCODE"
}
}
Finally {
cd $originalDir
}
}
##############################################################################
#.SYNOPSIS
# Calls nuget update on all the packages that match the mask.
#
#.PARAMETER Mask
# Which packages should be updated?
#
#.INPUTS
# Paths to .sln files. If empty, recursively searches directories for
# *.sln files.
#
#.EXAMPLE
# Update-Packages Google.*
##############################################################################
filter Update-Packages ([string] $Mask) {
$solutions = When-Empty $_ $args { Find-Files -Masks *.sln }
foreach ($solution in $solutions) {
# Nuget refuses to update without calling restore first.
nuget restore $solution
# Assume all packages.configs in the same directory, or a subdirectory
# as the solution are for projects in the solution.
$packageConfigs = Find-Files (Get-Item $solution).Directory -Masks packages.config
# Inspect each packages.config and find matching Ids.
$packageIds = $packageConfigs `
| ForEach-Object {(Select-Xml -Path $_ -XPath packages/package).Node.Id} `
| Where {$_ -like $Mask}
# Calling nuget update with no packageIds means update *all* packages,
# and that's definitely not what we want.
if ($packageIds) {
nuget update -Prerelease $solution ($packageIds | ForEach-Object {"-Id", $_})
}
}
}
##############################################################################
#.SYNOPSIS