forked from PowerShell/PSReadLine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper.psm1
More file actions
362 lines (310 loc) · 11.8 KB
/
Copy pathhelper.psm1
File metadata and controls
362 lines (310 loc) · 11.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
$MinimalSDKVersion = '6.0.425'
$IsWindowsEnv = [System.Environment]::OSVersion.Platform -eq "Win32NT"
$RepoRoot = (Resolve-Path "$PSScriptRoot/..").Path
$LocalDotnetDirPath = if ($IsWindowsEnv) { "$env:LocalAppData\Microsoft\dotnet" } else { "$env:HOME/.dotnet" }
<#
.SYNOPSIS
Get the path of the currently running powershell executable.
#>
function Get-PSExePath
{
if (-not $Script:PSExePath) {
$Script:PSExePath = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
}
return $Script:PSExePath
}
<#
.SYNOPSIS
Find the dotnet SDK that meets the minimal version requirement.
#>
function Find-Dotnet
{
$dotnetFile = if ($IsWindowsEnv) { "dotnet.exe" } else { "dotnet" }
$dotnetExePath = Join-Path -Path $LocalDotnetDirPath -ChildPath $dotnetFile
# If dotnet is already in the PATH, check to see if that version of dotnet can find the required SDK.
# This is "typically" the globally installed dotnet.
$foundDotnetWithRightVersion = $false
$dotnetInPath = Get-Command 'dotnet' -ErrorAction Ignore
if ($dotnetInPath) {
$foundDotnetWithRightVersion = Test-DotnetSDK $dotnetInPath.Source
}
if (-not $foundDotnetWithRightVersion) {
if (Test-DotnetSDK $dotnetExePath) {
Write-Warning "Can't find the dotnet SDK version $MinimalSDKVersion or higher, prepending '$LocalDotnetDirPath' to PATH."
$env:PATH = $LocalDotnetDirPath + [IO.Path]::PathSeparator + $env:PATH
}
else {
throw "Cannot find the dotnet SDK with the version $MinimalSDKVersion or higher. Please specify '-Bootstrap' to install build dependencies."
}
}
}
<#
.SYNOPSIS
Check if the dotnet SDK meets the minimal version requirement.
#>
function Test-DotnetSDK
{
param($dotnetExePath)
if (Test-Path $dotnetExePath) {
$installedVersion = & $dotnetExePath --version
return $installedVersion -ge $MinimalSDKVersion
}
return $false
}
<#
.SYNOPSIS
Install the dotnet SDK if we cannot find an existing one.
#>
function Install-Dotnet
{
[CmdletBinding()]
param(
[string]$Channel = 'release',
[string]$Version = $MinimalSDKVersion
)
try {
Find-Dotnet
return # Simply return if we find dotnet SDk with the correct version
} catch { }
$logMsg = if (Get-Command 'dotnet' -ErrorAction Ignore) {
"dotnet SDK out of date. Require '$MinimalSDKVersion' but found '$dotnetSDKVersion'. Updating dotnet."
} else {
"dotent SDK is not present. Installing dotnet SDK."
}
Write-Log $logMsg -Warning
$obtainUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain"
try {
Remove-Item $LocalDotnetDirPath -Recurse -Force -ErrorAction Ignore
$installScript = if ($IsWindowsEnv) { "dotnet-install.ps1" } else { "dotnet-install.sh" }
Invoke-WebRequest -Uri $obtainUrl/$installScript -OutFile $installScript
if ($IsWindowsEnv) {
& .\$installScript -Channel $Channel -Version $Version
} else {
bash ./$installScript -c $Channel -v $Version
}
}
finally {
Remove-Item $installScript -Force -ErrorAction Ignore
}
}
<#
.SYNOPSIS
Write log message for the build.
#>
function Write-Log
{
param(
[string] $Message,
[switch] $Warning,
[switch] $Indent
)
$foregroundColor = if ($Warning) { "Yellow" } else { "Green" }
$indentPrefix = if ($Indent) { " " } else { "" }
Write-Host -ForegroundColor $foregroundColor "${indentPrefix}${Message}"
}
$KeyboardLayoutHelperCode = @'
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
public class KeyboardLayoutHelper
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetKeyboardLayout(uint idThread);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetKeyboardLayoutList(int nBuff, [Out] IntPtr[] lpList);
// Used when setting the layout.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
// Used for getting the layout.
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
// Used in both getting and setting the layout
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetForegroundWindow();
const int WM_INPUTLANGCHANGEREQUEST = 0x0050;
private static string GetLayoutNameFromHKL(IntPtr hkl)
{
var lcid = (int)((uint)hkl & 0xffff);
return (new CultureInfo(lcid)).Name;
}
public static IEnumerable<string> GetKeyboardLayouts()
{
int cnt = GetKeyboardLayoutList(0, null);
var list = new IntPtr[cnt];
GetKeyboardLayoutList(list.Length, list);
foreach (var layout in list)
{
yield return GetLayoutNameFromHKL(layout);
}
}
public static string GetCurrentKeyboardLayout()
{
uint processId;
IntPtr layout = GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), out processId));
return GetLayoutNameFromHKL(layout);
}
public static IntPtr SetKeyboardLayout(string lang)
{
var layoutId = (new CultureInfo(lang)).KeyboardLayoutId;
var layout = LoadKeyboardLayout(layoutId.ToString("x8"), 0x80);
// Hacky, but tests are probably running in a console app and the layout change
// is ignored, so post the layout change to the foreground window.
PostMessage(GetForegroundWindow(), WM_INPUTLANGCHANGEREQUEST, 0, layoutId);
// Wait a bit until the layout has been changed.
do {
Thread.Sleep(100);
} while (GetCurrentKeyboardLayout() != lang);
return layout;
}
}
'@
<#
.SYNOPSIS
Start to run the xUnit tests.
#>
function Start-TestRun
{
param(
[string]
$Configuration,
[string]
$Framework
)
$testResultFolder = 'TestResults'
function RunXunitTestsInNewProcess ([string] $Layout, [string] $OperatingSystem)
{
$filter = "FullyQualifiedName~Test.{0}_{1}" -f ($Layout -replace '-','_'), $OperatingSystem
$testResultFile = "xUnitTestResults.{0}.xml" -f $Layout
$testResultFile = Join-Path $testResultFolder $testResultFile
$stdOutput, $stdError = @(New-TemporaryFile; New-TemporaryFile)
$arguments = 'test', '--no-build', '-c', $Configuration, '-f', $Framework, '--filter', $filter, '--logger', "xunit;LogFilePath=$testResultFile", '--logger', 'console;verbosity=normal'
Start-Process -FilePath dotnet -Wait -RedirectStandardOutput $stdOutput -RedirectStandardError $stdError -ArgumentList $arguments
Get-Content $stdOutput, $stdError
Remove-Item $stdOutput, $stdError
}
try
{
Push-Location "$RepoRoot/test"
$xUnitTestExecuted = $true
if ($IsWindowsEnv)
{
if ($env:GITHUB_ACTIONS -or $env:TF_BUILD)
{
# GitHub Actions CI builder only has en-US keyboard layout installed.
# We have to run tests from a new process because `GetCurrentKeyboardLayout` simply fails when called from
# the `pwsh` process started by AppVeyor. Our xUnit tests depends on `GetCurrentKeyboardLayout` to tell if
# a test case should run.
RunXunitTestsInNewProcess -Layout 'en-US' -OperatingSystem 'Windows'
}
else
{
if (-not ("KeyboardLayoutHelper" -as [type]))
{
Add-Type $KeyboardLayoutHelperCode
}
try
{
$xUnitTestExecuted = $false
# Remember the current keyboard layout, changes are system wide and restoring
# is the nice thing to do.
$savedLayout = [KeyboardLayoutHelper]::GetCurrentKeyboardLayout()
# We want to run tests in as many layouts as possible. We have key info
# data for layouts that might not be installed, and tests would fail
# if we don't set the system wide layout to match the key data we'll use.
$layouts = [KeyboardLayoutHelper]::GetKeyboardLayouts()
Write-Log "Available layouts: $layouts"
foreach ($layout in $layouts)
{
if (Test-Path "KeyInfo-${layout}-windows.json")
{
Write-Log "Testing $layout ..."
$null = [KeyboardLayoutHelper]::SetKeyboardLayout($layout)
# We have to use Start-Process so it creates a new window, because the keyboard
# layout change won't be picked up by any processes running in the current conhost.
RunXunitTestsInNewProcess -Layout $layout -OperatingSystem 'Windows'
$xUnitTestExecuted = $true
}
else
{
Write-Log "Testing not supported for the keyboard layout '$layout'."
}
}
}
finally
{
# Restore the original keyboard layout
$null = [KeyboardLayoutHelper]::SetKeyboardLayout($savedLayout)
}
}
}
else
{
RunXunitTestsInNewProcess -Layout 'en-US' -OperatingSystem 'Linux'
}
if ($xUnitTestExecuted)
{
# Check to see if there were any failures in xUnit tests, and throw exception to fail the build if so.
Get-ChildItem $testResultFolder | Test-XUnitTestResults > $null
}
}
finally
{
Pop-Location
}
}
<#
.SYNOPSIS
Check to see if the xUnit test run was successful.
#>
function Test-XUnitTestResults
{
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string] $TestResultsFile
)
Process
{
if (-not (Test-Path $TestResultsFile))
{
throw "File not found $TestResultsFile"
}
try
{
$results = [xml] (Get-Content $TestResultsFile)
}
catch
{
throw "Cannot convert $TestResultsFile to xml : $($_.message)"
}
$failedTests = $results.assemblies.assembly.collection | Where-Object failed -gt 0
if (-not $failedTests)
{
return $true
}
throw "$($failedTests.failed) tests failed"
}
}
<#
.SYNOPSIS
Run 'dotnet restore' for all the target runtime that we are interested in to
update packages on the CFS feed.
This needs to be run on a MS employee's dev machine whenever there is update
to the NuGet packages used in PSReadLine repo, so that the package and all its
dependencies can be pull into the CFS feed from upstream feed.
#>
function Update-CFSFeed
{
$rids = @('win-x64', 'win-arm64', 'linux-x64', 'linux-arm', 'linux-arm64', 'osx-x64', 'osx-arm64')
Write-Host "1. clear all NuGet caches on the local machine." -ForegroundColor Green
dotnet nuget locals all -c
Write-Host "2. restore for target runtimes." -ForegroundColor Green
foreach ($rid in $rids) {
Write-Host " - $rid" -ForegroundColor Green
dotnet restore -r $rid ../test/PSReadLine.Tests.csproj
dotnet restore -r $rid ../MockPSConsole/MockPSConsole.csproj
}
}