forked from GoogleCloudPlatform/dotnet-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuildTools.psm1
851 lines (812 loc) · 28.9 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
# 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") {
When-Empty $Target $ArgList {Find-Files -Masks $Mask} | 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
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
# 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
$rootDir = pwd
# Keep running lists of successes and failures.
# Array of strings: the relative path of the inner script.
$results = @{}
foreach ($script in $scripts) {
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
$relativePath = Resolve-Path -Relative $script.FullName
$verb = "Starting"
$jobState = 'Failed' # Retry once on failure.
for ($try = 0; $try -lt 2 -and $jobState -eq 'Failed'; ++$try) {
echo "$verb $relativePath..."
$verb = "Retrying"
$job = Start-Job -ArgumentList $relativePath, $script.Directory, `
('.\"{0}"' -f $script.Name) {
echo ("-" * 79)
echo $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
Receive-Job $job
$jobState = $job.State
if ($jobState -eq 'Running') {
if ((Get-Date) -gt $deadline) {
echo "TIME OUT"
$jobState = 'Timed Out'
break
}
} else {
break
}
}
Remove-Job -Force $job
}
$results[$jobState] += @($relativePath)
}
# Print a final summary.
echo ("=" * 79)
foreach ($key in $results.Keys) {
$count = $results[$key].Length
$result = $key.Replace('Completed', 'Succeeded').ToUpper()
echo "$count $result"
echo $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
# TODO: Restore after logging API has been fixed.
if ($false -and $timeOutCount) {
throw "$timeOutCount TIMED OUT"
}
}
##############################################################################
#.SYNOPSIS
# Builds and runs .NET core web application in the current directory.
# Runs test using casperjs.
#
#.INPUTS
# Javascript test files to pass to casperjs.
##############################################################################
function BuildAndRun-CoreTest($TestJs = "test.js") {
dnvm use 1.0.0-rc1-update1 -r clr
dnu restore
dnu build
$webProcess = Start-Process dnx web -PassThru
Try
{
Start-Sleep -Seconds 4 # Wait for web process to start up.
casperjs $TestJs http://localhost:5000
}
Finally
{
Stop-Process $webProcess
}
}
##############################################################################
#.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) {
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."
}
}
}
##############################################################################
#.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'
}
# Applicationhost.config expects the environment variable
# DOTNET_DOCS_SAMPLES to point to the same directory containing
# applicationhost.config.
$env:DOTNET_DOCS_SAMPLES = (Get-Item $ApplicationhostConfig).DirectoryName
$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.
casperjs $TestJs http://localhost:$port
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) {
Start-Job -ArgumentList (Get-Location), $url -ScriptBlock {
Set-Location $args[0]
$env:ASPNETCORE_URLS = $args[1]
dotnet run
}
}
##############################################################################
#.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) {
$url = "http://localhost:$PortNumber"
$job = Run-Kestrel($url)
Try
{
Run-CasperJs $TestJs, $Url
}
Finally
{
if (!$LeaveRunning) {
Stop-Job $job
Receive-Job $job
Remove-Job $job
}
}
}
function Run-CasperJs($TestJs='test.js', $Url) {
Start-Sleep -Seconds 2 # Wait for web process to start up.
casperjs $TestJs $Url
if ($LASTEXITCODE) {
# Try again
Start-Sleep -Seconds 2 # Wait for web process to start up.
casperjs $TestJs $Url
if ($LASTEXITCODE) {
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\netcoreapp1.0\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
# Make a backup copy of a file, run the script, and restore the file.
#
#.PARAMETER Files
# A list of files to back up.
#
#.PARAMETER ScriptBlock
# The script to execute.
#
#.EXAMPLE
# Backup-File Program.cs { Build }
##############################################################################
function Backup-File(
[string[]][Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Files,
[scriptblock][Parameter(Mandatory=$true)] $ScriptBlock)
{
$fileMap = @{}
try {
foreach ($file in $files) {
$tempCopy = [System.IO.Path]::GetTempFileName()
Copy-Item -Force $file $tempCopy
$fileMap[$file] = $tempCopy
}
. $ScriptBlock
}
finally {
foreach ($file in $files) {
Copy-Item -Force $fileMap[$file] $file
}
}
}
##############################################################################
#.SYNOPSIS
# Replace text in a text file.
#
#.PARAMETER Files
# A list of files to pack up.
#
#.PARAMETER Replacements.
# A hashtable. Keys are the text to replace. Values are replacements.
#
#.EXAMPLE
# Edit-TextFile Program.cs @{'YOUR-PROJECT-ID', $env:GOOGLE_PROJECT_ID}
##############################################################################
function Edit-TextFile(
[string[]][Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Files,
[hashtable][Parameter(Mandatory=$true)] $Replacements)
{
foreach ($file in $files) {
$content = Get-Content $file | ForEach-Object {
$line = $_
foreach ($key in $Replacements.Keys) {
$line = $line.Replace($key, $Replacements[$key])
}
$line
}
$content | Out-File -Force -Encoding UTF8 $file
}
}
##############################################################################
#.SYNOPSIS
# Make a backup copy of a file, edit the file, run the script, and restore
# the file.
#
#.PARAMETER Files
# A list of files to back up.
#
#.PARAMETER Replacements.
# A hashtable. Keys are the text to replace. Values are replacements.
#
#.PARAMETER ScriptBlock
# The script to execute.
#
#.EXAMPLE
# BackupAndEdit-TextFile "QuickStart\Program.cs" `
# @{"YOUR-PROJECT-ID" = $env:GOOGLE_PROJECT_ID} `
# {
# Build-Solution
# }
##############################################################################
function BackupAndEdit-TextFile(
[string[]][Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Files,
[hashtable][Parameter(Mandatory=$true)] $Replacements,
[scriptblock][Parameter(Mandatory=$true)] $ScriptBlock)
{
Backup-File $Files {
Edit-TextFile $Files $Replacements
. $ScriptBlock
}.GetNewClosure()
}
##############################################################################
#.SYNOPSIS
# Find files that are utf16 encoded.
#
#.PARAMETER Path
# A list of paths or masks for files to check.
#
#.EXAMPLE
# Find-Utf16
##############################################################################
function Find-Utf16($Path=@('*.yaml', '*.cs', '*.xml')) {
foreach ($file in (Get-ChildItem -Recurse -Path $Path)) {
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
if ($bytes[0] -eq 255 -and $bytes[1] -eq 254) {
$file
}
}
}
##############################################################################
#.SYNOPSIS
# Converts a file to utf8 encoding.
#
#.INPUT
# Files that are encoded some other way.
#
#.EXAMPLE
# Find-Utf16 | ConvertTo-Utf8
##############################################################################
filter ConvertTo-Utf8 {
$lines = [System.IO.File]::ReadAllLines($_)
[System.IO.File]::WriteAllLines($_, $lines)
}