-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInstall-NerdFont.ps1
More file actions
345 lines (304 loc) · 14 KB
/
Copy pathInstall-NerdFont.ps1
File metadata and controls
345 lines (304 loc) · 14 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
#Requires -Modules @{ ModuleName = 'Fonts'; RequiredVersion = '1.1.21' }
#Requires -Modules @{ ModuleName = 'Admin'; RequiredVersion = '1.1.6' }
function Install-NerdFont {
<#
.SYNOPSIS
Installs Nerd Fonts to the system.
.DESCRIPTION
Installs Nerd Fonts to the system.
.EXAMPLE
Install-NerdFont -Name 'Fira Code'
Installs the font 'Fira Code' to the current user.
.EXAMPLE
Install-NerdFont -Name 'Ubuntu*'
Installs all fonts that match the pattern 'Ubuntu*' to the current user.
.EXAMPLE
Install-NerdFont -Name 'Fira Code' -Scope AllUsers
Installs the font 'Fira Code' to all users. This requires to be run as administrator.
.EXAMPLE
Install-NerdFont -All
Installs all Nerd Fonts to the current user.
.EXAMPLE
Install-NerdFont -Name 'FiraCode' -Variant Mono
Installs only the monospace variant of the font 'FiraCode' to the current user.
.EXAMPLE
Install-NerdFont -All -Variant Mono
Installs only the monospace variant of all Nerd Fonts to the current user.
.LINK
https://psmodule.io/NerdFonts/Functions/Install-NerdFont
.NOTES
More information about the NerdFonts can be found at:
[NerdFonts](https://www.nerdfonts.com/) | [GitHub](https://github.com/ryanoasis/nerd-fonts)
#>
[CmdletBinding(
DefaultParameterSetName = 'ByName',
SupportsShouldProcess
)]
[Alias('Install-NerdFonts')]
param(
# Specify the name of the NerdFont(s) to install.
[Parameter(
ParameterSetName = 'ByName',
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[SupportsWildcards()]
[string[]] $Name,
# Specify to install all NerdFont(s).
[Parameter(
ParameterSetName = 'All',
Mandatory
)]
[switch] $All,
[Parameter()]
[ValidateSet('CurrentUser', 'AllUsers')]
[string] $Scope = 'CurrentUser',
# Select which variant(s) to install from each archive. Default 'All' preserves current behavior.
[Parameter()]
[ValidateSet('All', 'Standard', 'Mono', 'Propo')]
[string] $Variant = 'All',
# Force will overwrite existing fonts
[Parameter()]
[switch] $Force
)
begin {
if ($Scope -eq 'AllUsers' -and -not (IsAdmin)) {
$errorMessage = @'
Administrator rights are required to install fonts.
Please run the command again with elevated rights (Run as Administrator) or provide '-Scope CurrentUser' to your command."
'@
throw $errorMessage
}
$nerdFontsToInstall = [System.Collections.Generic.List[object]]::new()
$seenNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$guid = (New-Guid).Guid
$tempPath = Join-Path -Path $HOME -ChildPath "NerdFonts-$guid"
if (-not (Test-Path -Path $tempPath -PathType Container)) {
Write-Verbose "Create folder [$tempPath]"
$null = New-Item -Path $tempPath -ItemType Directory
}
}
process {
if ($All) {
foreach ($font in $script:NerdFonts) {
if ($seenNames.Add($font.Name)) { $nerdFontsToInstall.Add($font) }
}
} else {
foreach ($fontName in $Name) {
foreach ($font in $script:NerdFonts) {
if ($font.Name -like $fontName -and $seenNames.Add($font.Name)) {
$nerdFontsToInstall.Add($font)
}
}
}
}
}
end {
Write-Verbose "[$Scope] - Installing [$($nerdFontsToInstall.Count)] fonts"
$cacheRoot = if ($IsWindows) {
Join-Path -Path ([Environment]::GetFolderPath('LocalApplicationData')) -ChildPath 'PSModule/NerdFonts/cache'
} else {
Join-Path -Path $HOME -ChildPath '.cache/PSModule/NerdFonts'
}
$installedFamilies = $null
if (-not $Force) {
$installedNames = @(Get-Font -Scope $Scope -ErrorAction SilentlyContinue | ForEach-Object { $_.Name } | Where-Object { $_ })
$installedFamilies = [System.Collections.Generic.HashSet[string]]::new(
[string[]]$installedNames,
[System.StringComparer]::OrdinalIgnoreCase
)
}
$toProcess = [System.Collections.Generic.List[object]]::new()
foreach ($nerdFont in $nerdFontsToInstall) {
$fontName = $nerdFont.Name
if (-not $Force -and $installedFamilies) {
$alreadyInstalled = $false
foreach ($family in $installedFamilies) {
if ($family -like "$fontName Nerd Font*") { $alreadyInstalled = $true; break }
}
if ($alreadyInstalled) {
Write-Verbose "[$fontName] - already installed, skipping"
continue
}
}
$toProcess.Add($nerdFont)
}
Add-Type -AssemblyName System.Net.Http -ErrorAction SilentlyContinue
$httpClient = [System.Net.Http.HttpClient]::new()
# Keep request lifetime unbounded for large archives on slower links.
$httpClient.Timeout = [System.Threading.Timeout]::InfiniteTimeSpan
$pending = [System.Collections.Generic.List[object]]::new()
$readyToInstall = [System.Collections.Generic.List[object]]::new()
$downloadErrors = [System.Collections.Generic.List[string]]::new()
$throttle = 8
try {
foreach ($nerdFont in $toProcess) {
$URL = $nerdFont.URL
$fontName = $nerdFont.Name
$downloadFileName = Split-Path -Path $URL -Leaf
$downloadPath = Join-Path -Path $tempPath -ChildPath $downloadFileName
$cacheTag = if ($URL -match '/releases/download/([^/]+)/') {
$Matches[1]
} else {
'unknown'
}
$cacheTagDir = Join-Path -Path $cacheRoot -ChildPath $cacheTag
$cachedFile = Join-Path -Path $cacheTagDir -ChildPath $downloadFileName
if ((Test-Path -LiteralPath $cachedFile) -and -not $Force) {
Write-Verbose "[$fontName] - Cache hit at [$cachedFile]"
$cacheHitSuccess = $false
try {
Copy-Item -LiteralPath $cachedFile -Destination $downloadPath -Force -ErrorAction Stop
$cacheHitSuccess = $true
} catch {
Write-Warning "[$fontName] - Cache read failed, falling back to download: $($_.Exception.Message)"
}
if ($cacheHitSuccess) {
$item = [pscustomobject]@{
Name = $fontName
URL = $URL
DownloadPath = $downloadPath
CachedFile = $cachedFile
CacheTagDir = $cacheTagDir
FromCache = $true
}
$pending.Add($item)
$readyToInstall.Add($item)
} else {
$item = [pscustomobject]@{
Name = $fontName
URL = $URL
DownloadPath = $downloadPath
CachedFile = $cachedFile
CacheTagDir = $cacheTagDir
FromCache = $false
}
$pending.Add($item)
}
} else {
Write-Verbose "[$fontName] - Queue download to [$downloadPath]"
$item = [pscustomobject]@{
Name = $fontName
URL = $URL
DownloadPath = $downloadPath
CachedFile = $cachedFile
CacheTagDir = $cacheTagDir
FromCache = $false
}
$pending.Add($item)
}
}
$toDownload = @($pending | Where-Object { -not $_.FromCache })
for ($i = 0; $i -lt $toDownload.Count; $i += $throttle) {
$end = [Math]::Min($i + $throttle - 1, $toDownload.Count - 1)
$chunk = $toDownload[$i..$end]
$tasks = @()
foreach ($q in $chunk) {
$tasks += [pscustomobject]@{ Q = $q; Task = $httpClient.GetByteArrayAsync($q.URL) }
}
foreach ($t in $tasks) {
try {
$bytes = $t.Task.GetAwaiter().GetResult()
[System.IO.File]::WriteAllBytes($t.Q.DownloadPath, $bytes)
$readyToInstall.Add($t.Q)
} catch {
$downloadErrors.Add("[$($t.Q.Name)] - Download failed: $($_.Exception.Message)")
}
}
}
} finally {
$httpClient.Dispose()
}
foreach ($p in $readyToInstall) {
$fontName = $p.Name
$downloadPath = $p.DownloadPath
$extractPath = Join-Path -Path $tempPath -ChildPath $fontName
Write-Verbose "[$fontName] - Extract to [$extractPath]"
if ($PSCmdlet.ShouldProcess("[$fontName] to [$extractPath]", 'Extract')) {
if (-not (Test-Path -LiteralPath $extractPath)) {
$null = New-Item -ItemType Directory -Path $extractPath
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($downloadPath, $extractPath, $true)
if (-not $p.FromCache -and (Test-Path -LiteralPath $downloadPath)) {
try {
if (-not (Test-Path -LiteralPath $p.CacheTagDir)) {
$null = New-Item -ItemType Directory -Path $p.CacheTagDir -Force -ErrorAction Stop
}
$tempCachePath = "$($p.CachedFile).$PID.tmp"
Copy-Item -LiteralPath $downloadPath -Destination $tempCachePath -Force -ErrorAction Stop
Move-Item -LiteralPath $tempCachePath -Destination $p.CachedFile -Force -ErrorAction Stop
} catch {
Write-Warning "[$fontName] - Download succeeded but cache write failed: $($_.Exception.Message)"
if ($tempCachePath -and (Test-Path -LiteralPath $tempCachePath)) {
Remove-Item -LiteralPath $tempCachePath -Force -ErrorAction SilentlyContinue
}
}
}
Remove-Item -Path $downloadPath -Force
}
if ($Variant -ne 'All') {
$allFiles = Get-ChildItem -Path $extractPath -Recurse -File -Include '*.ttf', '*.otf'
$keep = switch ($Variant) {
'Mono' {
$allFiles | Where-Object { $_.Name -like '*NerdFontMono*' }
}
'Propo' {
$allFiles | Where-Object { $_.Name -like '*NerdFontPropo*' }
}
'Standard' {
$allFiles | Where-Object {
$_.Name -like '*NerdFont*' -and
$_.Name -notlike '*NerdFontMono*' -and
$_.Name -notlike '*NerdFontPropo*'
}
}
}
$keepNames = [string[]]@($keep.FullName)
$keepSet = [System.Collections.Generic.HashSet[string]]::new(
$keepNames,
[System.StringComparer]::OrdinalIgnoreCase
)
$removed = 0
foreach ($f in $allFiles) {
if (-not $keepSet.Contains($f.FullName)) {
Remove-Item -LiteralPath $f.FullName -Force -ErrorAction SilentlyContinue
$removed++
}
}
Write-Verbose "[$fontName] - Variant '$Variant': kept $($keep.Count), removed $removed"
}
# Nerd Fonts archives sometimes contain duplicate matching files in
# compatibility subfolders. Keep a single file per filename.
$remaining = @(Get-ChildItem -Path $extractPath -Recurse -File -Include '*.ttf', '*.otf')
$preferred = $remaining | Sort-Object -Property @(
@{ Expression = { if ($_.FullName -match '(?i)[\\/]Windows Compatible[\\/]') { 1 } else { 0 } } }
@{ Expression = { $_.FullName.Length } }
)
$seenFileNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$duplicateRemoved = 0
foreach ($file in $preferred) {
if ($seenFileNames.Add($file.Name)) { continue }
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction SilentlyContinue
$duplicateRemoved++
}
if ($duplicateRemoved -gt 0) {
Write-Verbose "[$fontName] - Deduplicated $duplicateRemoved file(s)"
}
Write-Verbose "[$fontName] - Install to [$Scope]"
if ($PSCmdlet.ShouldProcess("[$fontName] to [$Scope]", 'Install font')) {
Install-Font -Path $extractPath -Scope $Scope -Force:$Force
Remove-Item -Path $extractPath -Force -Recurse
}
}
foreach ($err in $downloadErrors) {
Write-Error $err
}
Write-Verbose "Remove folder [$tempPath]"
}
clean {
if ($tempPath -and (Test-Path -LiteralPath $tempPath)) {
Remove-Item -LiteralPath $tempPath -Force -Recurse -ErrorAction SilentlyContinue
}
}
}