-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.ps1
291 lines (255 loc) · 9.42 KB
/
utils.ps1
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
<#
.DESCRIPTION
Utility methods for common tasks.
#>
function Convert-CustomObjectToHashtable {
param (
[Parameter(Mandatory = $true, Position = 0)]
[AllowEmptyString()]
[PSCustomObject]$CustomObject
)
# Create an empty hashtable
$hashtable = @{}
# Iterate through the properties of the PSCustomObject
$CustomObject.psobject.properties | ForEach-Object {
$hashtable[$_.Name] = $_.Value
}
# Return the hashtable
return $hashtable
}
function Invoke-CommandLine {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Justification = 'Usually this statement must be avoided (https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/avoid-using-invoke-expression?view=powershell-7.3), here it is OK as it does not execute unknown code.')]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$CommandLine,
[Parameter(Mandatory = $false, Position = 1)]
[bool]$StopAtError = $true,
[Parameter(Mandatory = $false, Position = 2)]
[bool]$PrintCommand = $true,
[Parameter(Mandatory = $false, Position = 3)]
[bool]$Silent = $false
)
if ($PrintCommand) {
Write-Output "Executing: $CommandLine"
}
$global:LASTEXITCODE = 0
if ($Silent) {
# Omit information stream (6) and stdout (1)
Invoke-Expression $CommandLine 6>&1 | Out-Null
}
else {
Invoke-Expression $CommandLine
}
if ($global:LASTEXITCODE -ne 0) {
if ($StopAtError) {
Write-Error "Command line call `"$CommandLine`" failed with exit code $global:LASTEXITCODE"
}
else {
Write-Output "Command line call `"$CommandLine`" failed with exit code $global:LASTEXITCODE, continuing ..."
}
}
}
function Convert-ScoopFileJsonToHashTable {
param (
[Parameter(Mandatory = $true)]
[string]$ScoopFileJson
)
$return = @{
"buckets" = @();
"apps" = @()
}
$scoopFileData = ConvertFrom-Json -InputObject $ScoopFileJson
if ($scoopFileData.buckets -is [System.Collections.IEnumerable]) {
foreach ($bucket in $scoopFileData.buckets) {
$return.buckets += @{
"Name" = $bucket.Name
"Source" = $bucket.Source
}
}
}
if ($scoopFileData.apps -is [System.Collections.IEnumerable]) {
foreach ($app in $scoopFileData.apps) {
$return.apps += @{
"Name" = $app.Name
"Source" = $app.Source
"Version" = $app.Version
"Identifier" = if ($app.Version) { "$($app.Source)/$($app.Name)@$($app.Version)" } else { "$($app.Source)/$($app.Name)" }
}
}
}
return $return
}
function Import-ScoopFile {
param (
[Parameter(Mandatory = $true)]
[string]$ScoopFilePath
)
$scoopFileData = Convert-ScoopFileJsonToHashTable -ScoopFileJson (Get-Content -Path $ScoopFilePath -Raw)
# Add the buckets
$scoopFileData.buckets | ForEach-Object {
$bucket = $_
Write-Output "Processing bucket: $($bucket.Name)"
# We try to add each bucket, even if it already exists (we ignore any error here)
Invoke-CommandLine "scoop bucket add $($bucket.Name) $($bucket.Source)" -StopAtError $false
}
# Update buckets only if there are any buckets or apps to process
if ($scoopFileData.buckets.Count -gt 0 -or $scoopFileData.apps.Count -gt 0) {
Invoke-CommandLine "scoop update"
}
# Install the apps
$scoopFileData.apps | ForEach-Object {
$app = $_
Write-Output "Processing app: $($app.Name)"
Invoke-CommandLine "scoop install $($app.Identifier)"
# TODO: Replace this by some scoop env mechanism in the .venv directory
Invoke-CommandLine "scoop reset $($app.Identifier)"
}
}
function Add-ScoopToPath {
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$ScoopFilePath
)
# Read the content of the scoopfile.json
$scoopFileContent = Get-Content -Path $ScoopFilePath -Raw | ConvertFrom-Json
# Iterate over each app in the scoopfile
foreach ($app in $scoopFileContent.apps) {
Write-Output "Processing app: $($app.Name)"
# Extract the app details from the dictionary
$source = $app.Source
$name = $app.Name
$version = $app.Version
# Construct the scoop info command
$appIdentifier = if ($version) { "$source/$name@$version" } else { "$source/$name" }
# Get the scoop info for the app with --verbose flag
$appInfo = scoop info $appIdentifier --verbose
# Check if the appInfo contains 'Path Added'
if ($appInfo.'Path Added') {
$pathAdded = $appInfo.'Path Added'
$env:PATH = "$pathAdded;$env:PATH"
Write-Output "Added $pathAdded to PATH for app $appIdentifier"
}
}
Write-Output "Updated PATH: $env:PATH"
}
# Update/Reload current environment variable PATH with settings from registry
function Initialize-EnvPath {
# workaround for system-wide installations (e.g. in GitHub Actions)
if ($Env:USER_PATH_FIRST) {
$Env:Path = [System.Environment]::GetEnvironmentVariable("Path", "User") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "Machine")
}
else {
$Env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}
}
function Remove-Path {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$path
)
if (Test-Path -Path $path -PathType Container) {
Write-Output "Deleting directory '$path' ..."
Remove-Item $path -Force -Recurse
}
elseif (Test-Path -Path $path -PathType Leaf) {
Write-Output "Deleting file '$path' ..."
Remove-Item $path -Force
}
}
function New-Directory {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$dir
)
if (-Not (Test-Path -Path $dir)) {
Write-Output "Creating directory '$dir' ..."
New-Item -ItemType Directory $dir
}
}
function CloneOrPullGitRepo {
param (
[Parameter(Mandatory = $true)]
[string]$RepoUrl,
[Parameter(Mandatory = $true)]
[string]$TargetDirectory,
[Parameter(Mandatory = $false)]
[string]$Tag,
[Parameter(Mandatory = $false)]
[string]$Branch = "develop"
)
$baselineName = "branch"
$baseline = $Branch
if ($Tag) {
$baselineName = "tag"
$baseline = $Tag
}
if (Test-Path -Path "$TargetDirectory\.git" -PathType Container) {
# When the repository directory exists, fetch the latest changes and checkout the baseline
try {
Push-Location $TargetDirectory
Invoke-CommandLine "git fetch --tags" -Silent $true
if ($Tag) {
Invoke-CommandLine "git checkout $Tag --quiet" -Silent $true
}
else {
Invoke-CommandLine "git checkout -B $Branch origin/$Branch --quiet" -Silent $true
}
Invoke-CommandLine "git reset --hard"
return
}
catch {
Write-Output "Failed to checkout $baselineName '$baseline' in repository '$RepoUrl' at directory '$TargetDirectory'."
}
finally {
Pop-Location
}
}
# Repo directory does not exist, remove any possible leftovers and get a fresh clone
try {
Remove-Path $TargetDirectory
New-Directory $TargetDirectory
Push-Location $TargetDirectory
Invoke-CommandLine "git -c advice.detachedHead=false clone --branch $baseline $RepoUrl ." -Silent $true
Invoke-CommandLine "git config pull.rebase true" -Silent $true -PrintCommand $false
Invoke-CommandLine "git log -1 --pretty='format:%h %B'" -PrintCommand $false
}
catch {
Write-Output "Failed to clone repository '$RepoUrl' at directory '$TargetDirectory'."
}
finally {
Pop-Location
}
}
function Test-RunningInCIorTestEnvironment {
return [Boolean]($Env:JENKINS_URL -or $Env:PYTEST_CURRENT_TEST -or $Env:GITHUB_ACTIONS)
}
function Get-UserConfirmation {
param (
[Parameter(Mandatory = $true)]
[string]$message,
# Default value of the confirmation prompt
[Parameter(Mandatory = $false)]
[bool]$defaultValueForUser = $true,
# Value when running in CI or test environment
[Parameter(Mandatory = $false)]
[bool]$valueForCi = $false
)
if (Test-RunningInCIorTestEnvironment) {
return $valueForCi
}
else {
$defaultText = if ($defaultValueForUser) { "[Y/n]" } else { "[y/N]" }
$userResponse = Read-Host "$message $defaultText"
if ($userResponse -eq '') {
return $defaultValueForUser
}
elseif ($userResponse -match '^[Yy]') {
return $true
}
else {
return $false
}
}
}