Refactor translation handling across scripts

This commit is contained in:
Jeffrey
2026-10-21 19:45:58 +02:00
parent 97f3f805ef
commit 785f134153
12 changed files with 120 additions and 851 deletions
+1 -279
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3 -4
View File
@@ -6,8 +6,7 @@
Iterates over every non-control parameter in $script:Params and emits a Iterates over every non-control parameter in $script:Params and emits a
human-readable line for each change that will be applied. For the human-readable line for each change that will be applied. For the
'RemoveApps' parameter the list of targeted app names is displayed 'RemoveApps' parameter the list of targeted app names is displayed
inline. Feature labels are resolved from Features.json when available; inline. Feature labels are resolved from the language catalogs.
otherwise the raw parameter name is used as a fallback.
After printing the summary the function pauses until the user presses After printing the summary the function pauses until the user presses
Enter, giving them an opportunity to review and cancel via Ctrl+C. Enter, giving them an opportunity to review and cancel via Ctrl+C.
@@ -16,7 +15,7 @@ function Write-PendingChanges {
Write-Output "Win11Debloat will make the following changes:" Write-Output "Win11Debloat will make the following changes:"
if ($script:Params['CreateRestorePoint']) { if ($script:Params['CreateRestorePoint']) {
Write-Output "- $($script:Features['CreateRestorePoint'].Label)" Write-Output "- $(Get-Translation -Key 'CreateRestorePoint' -Field 'Label' -Section 'Features')"
} }
foreach ($parameterName in $script:Params.Keys) { foreach ($parameterName in $script:Params.Keys) {
if ($script:ControlParams -contains $parameterName) { if ($script:ControlParams -contains $parameterName) {
@@ -45,7 +44,7 @@ function Write-PendingChanges {
continue continue
} }
default { default {
$message = $script:Features[$parameterName].Label $message = Get-Translation -Key $parameterName -Field 'Label' -Section 'Features'
Write-Output "- $message" Write-Output "- $message"
continue continue
} }
+3 -5
View File
@@ -20,7 +20,7 @@ function Invoke-FeatureApply {
try { try {
# Resolve feature metadata from Features.json # Resolve feature metadata from Features.json
$feature = $script:Features[$FeatureId] $feature = $script:Features[$FeatureId]
$applyText = $feature.ApplyText $applyText = Get-Translation -Key $FeatureId -Field 'ApplyText' -Section 'Features'
# ---- Registry-backed features: import .reg file, then handle additional tasks ---- # ---- Registry-backed features: import .reg file, then handle additional tasks ----
if ($feature.RegistryKey) { if ($feature.RegistryKey) {
@@ -162,7 +162,7 @@ function Invoke-FeatureUndo {
return $false return $false
} }
$undoText = if ($feature.ApplyUndoText) { $feature.ApplyUndoText } elseif ($feature.UndoLabel) { $feature.UndoLabel } else { $FeatureId } $undoText = Get-Translation -Key $FeatureId -Field 'ApplyUndoText' -Section 'Features'
try { try {
# ---- Registry-backed features: import undo data, then handle additional tasks ---- # ---- Registry-backed features: import undo data, then handle additional tasks ----
@@ -308,9 +308,7 @@ function Invoke-UndoFeatures {
foreach ($featureId in $FeatureIds) { foreach ($featureId in $FeatureIds) {
if ($script:CancelRequested) { return } if ($script:CancelRequested) { return }
$f = if ($script:Features.ContainsKey($featureId)) { $script:Features[$featureId] } else { $null } $undoText = Get-Translation -Key $featureId -Field 'ApplyUndoText' -Section 'Features'
$undoLabel = if ($f -and $f.UndoLabel) { Get-Translation -Key $featureId -Field 'UndoLabel' -Section 'Features' } else { $featureId }
$undoText = if ($f -and $f.ApplyUndoText) { Get-Translation -Key $featureId -Field 'ApplyUndoText' -Section 'Features' } else { $undoLabel }
if ($script:ApplyProgressCallback) { if ($script:ApplyProgressCallback) {
& $script:ApplyProgressCallback $step $TotalSteps $undoText & $script:ApplyProgressCallback $step $TotalSteps $undoText
+3 -5
View File
@@ -291,7 +291,7 @@ function Get-Translation {
<# <#
.SYNOPSIS .SYNOPSIS
Looks up a translated label for one value of a UiGroup, falling back to en-US, then to the raw label. Looks up a translated label for one value of a UiGroup, falling back to en-US, then to the feature ID.
.DESCRIPTION .DESCRIPTION
UiGroups[GroupId].Values in the language files is a FeatureId -> Label map, one level deeper UiGroups[GroupId].Values in the language files is a FeatureId -> Label map, one level deeper
@@ -304,13 +304,11 @@ function Get-GroupValueTranslation {
[string]$GroupId, [string]$GroupId,
[Parameter(Mandatory)] [Parameter(Mandatory)]
[string]$FeatureId, [string]$FeatureId,
[Parameter(Mandatory)]
[string]$FallbackLabel,
[object]$Lang = $script:Lang [object]$Lang = $script:Lang
) )
if (-not $Lang) { if (-not $Lang) {
return $FallbackLabel return $FeatureId
} }
foreach ($candidateLang in (Get-LanguageFallbackChain -Lang $Lang)) { foreach ($candidateLang in (Get-LanguageFallbackChain -Lang $Lang)) {
@@ -325,7 +323,7 @@ function Get-GroupValueTranslation {
} }
} }
return $FallbackLabel return $FeatureId
} }
<# <#
+7 -6
View File
@@ -11,7 +11,7 @@
.PARAMETER Mapping .PARAMETER Mapping
A control mapping with Type and either FeatureId or GroupId and Values. Group values A control mapping with Type and either FeatureId or GroupId and Values. Group values
contain FeatureIds and fallback Label text. contain FeatureIds.
.PARAMETER Features .PARAMETER Features
The feature definitions keyed by FeatureId. Defaults to $script:Features. The feature definitions keyed by FeatureId. Defaults to $script:Features.
@@ -30,7 +30,7 @@ function Get-TweakControlText {
$label = Get-Translation -Key $Mapping.GroupId -Field 'Label' -Section 'UiGroups' $label = Get-Translation -Key $Mapping.GroupId -Field 'Label' -Section 'UiGroups'
$tooltip = Get-Translation -Key $Mapping.GroupId -Field 'ToolTip' -Section 'UiGroups' $tooltip = Get-Translation -Key $Mapping.GroupId -Field 'ToolTip' -Section 'UiGroups'
$options += @($Mapping.Values | ForEach-Object { $options += @($Mapping.Values | ForEach-Object {
Get-GroupValueTranslation -GroupId $Mapping.GroupId -FeatureId $_.FeatureIds[0] -FallbackLabel $_.Label Get-GroupValueTranslation -GroupId $Mapping.GroupId -FeatureId $_.FeatureIds[0]
}) })
} }
else { else {
@@ -66,8 +66,9 @@ function Update-FeatureLabelLookup {
$script:UndoFeatureLabelLookup = @{} $script:UndoFeatureLabelLookup = @{}
foreach ($feature in $Features) { foreach ($feature in $Features) {
$script:FeatureLabelLookup[$feature.FeatureId] = Get-Translation -Key $feature.FeatureId -Field 'Label' -Section 'Features' $script:FeatureLabelLookup[$feature.FeatureId] = Get-Translation -Key $feature.FeatureId -Field 'Label' -Section 'Features'
if ($feature.UndoLabel) { $undoLabel = Get-Translation -Key $feature.FeatureId -Field 'UndoLabel' -Section 'Features'
$script:UndoFeatureLabelLookup[$feature.FeatureId] = Get-Translation -Key $feature.FeatureId -Field 'UndoLabel' -Section 'Features' if ($undoLabel -ne $feature.FeatureId) {
$script:UndoFeatureLabelLookup[$feature.FeatureId] = $undoLabel
} }
} }
} }
@@ -244,7 +245,7 @@ function New-DynamicTweakControls {
$text = Get-TweakControlText -Mapping $mapping -Features $featureMap $text = Get-TweakControlText -Mapping $mapping -Features $featureMap
$controlName = ("Feature_{0}_Combo" -f $feature.FeatureId) -replace '[^a-zA-Z0-9_]', '' $controlName = ("Feature_{0}_Combo" -f $feature.FeatureId) -replace '[^a-zA-Z0-9_]', ''
$control = New-LabeledCombo -parent $parent -labelText $text.Label -comboName $controlName -items $text.Options $control = New-LabeledCombo -parent $parent -labelText $text.Label -comboName $controlName -items $text.Options
if ($feature.ToolTip -or $feature.DisableWhenApplied -eq $true) { if ($text.ToolTip -and $text.ToolTip -ne $feature.FeatureId) {
Set-TweakControlToolTip -control $control -tooltipText $text.ToolTip -ShowOnDisabled Set-TweakControlToolTip -control $control -tooltipText $text.ToolTip -ShowOnDisabled
} }
$script:UiControlMappings[$controlName] = $mapping $script:UiControlMappings[$controlName] = $mapping
@@ -482,7 +483,7 @@ function New-DynamicTweakControls {
$comboName = 'Group_{0}Combo' -f $group.GroupId $comboName = 'Group_{0}Combo' -f $group.GroupId
if (-not $panel) { $panel = Get-OrCreateCategoryCard -categoryObj $categoryObj } if (-not $panel) { $panel = Get-OrCreateCategoryCard -categoryObj $categoryObj }
$combo = New-LabeledCombo -parent $panel -labelText $text.Label -comboName $comboName -items $text.Options $combo = New-LabeledCombo -parent $panel -labelText $text.Label -comboName $comboName -items $text.Options
if ($group.ToolTip) { if ($text.ToolTip -and $text.ToolTip -ne $group.GroupId) {
Set-TweakControlToolTip -control $combo -tooltipText $text.ToolTip Set-TweakControlToolTip -control $combo -tooltipText $text.ToolTip
} }
$script:UiControlMappings[$comboName] = $mapping $script:UiControlMappings[$comboName] = $mapping
+3 -3
View File
@@ -13,9 +13,9 @@ function Get-RebootFeatureLabels {
foreach ($paramKey in $candidateParamKeys) { foreach ($paramKey in $candidateParamKeys) {
if ($script:Features.ContainsKey($paramKey) -and $script:Features[$paramKey].RequiresReboot -eq $true) { if ($script:Features.ContainsKey($paramKey) -and $script:Features[$paramKey].RequiresReboot -eq $true) {
$feature = $script:Features[$paramKey]
$isUndo = $script:UndoParams.ContainsKey($paramKey) $isUndo = $script:UndoParams.ContainsKey($paramKey)
$displayLabel = if ($isUndo -and $feature.UndoLabel) { Get-Translation -Key $paramKey -Field 'UndoLabel' -Section 'Features' } else { Get-Translation -Key $paramKey -Field 'Label' -Section 'Features' } $undoLabel = Get-Translation -Key $paramKey -Field 'UndoLabel' -Section 'Features'
$displayLabel = if ($isUndo -and $undoLabel -ne $paramKey) { $undoLabel } else { Get-Translation -Key $paramKey -Field 'Label' -Section 'Features' }
if (-not [string]::IsNullOrWhiteSpace([string]$displayLabel)) { if (-not [string]::IsNullOrWhiteSpace([string]$displayLabel)) {
[void]$rebootFeatureLabels.Add([string]$displayLabel) [void]$rebootFeatureLabels.Add([string]$displayLabel)
@@ -24,4 +24,4 @@ function Get-RebootFeatureLabels {
} }
return $rebootFeatureLabels return $rebootFeatureLabels
} }
+13
View File
@@ -63,6 +63,19 @@ Describe 'Get-RebootFeatureLabels' {
$result | Should -Contain 'Apply feature' $result | Should -Contain 'Apply feature'
} }
It 'resolves undo labels when feature metadata contains no display text' {
$script:Features = @{
ApplyFeature = [PSCustomObject]@{ RequiresReboot = $true }
UndoFeature = [PSCustomObject]@{ RequiresReboot = $true }
}
$result = @(Get-RebootFeatureLabels)
$result | Should -HaveCount 2
$result | Should -Contain 'Undo apply feature'
$result | Should -Contain 'Undo feature'
}
It 'falls back to the regular label when an undo selection has no undo label' { It 'falls back to the regular label when an undo selection has no undo label' {
$script:Params = @{} $script:Params = @{}
$script:UndoParams = @{ ApplyFeature = $true } $script:UndoParams = @{ ApplyFeature = $true }
+71
View File
@@ -11,6 +11,7 @@ BeforeAll {
. (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-LanguageFile.ps1') . (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-LanguageFile.ps1')
$script:LanguagesPath = Join-Path $PSScriptRoot '..\Config\Languages' $script:LanguagesPath = Join-Path $PSScriptRoot '..\Config\Languages'
$featureConfig = Import-JsonFile -filePath (Join-Path $PSScriptRoot '..\Config\Features.json') $featureConfig = Import-JsonFile -filePath (Join-Path $PSScriptRoot '..\Config\Features.json')
$appConfig = Import-JsonFile -filePath (Join-Path $PSScriptRoot '..\Config\Apps.json')
function Add-CatalogValues { function Add-CatalogValues {
param($Catalog, [string]$Prefix, [hashtable]$Values) param($Catalog, [string]$Prefix, [hashtable]$Values)
@@ -32,6 +33,76 @@ BeforeAll {
ConvertFrom-Json -ErrorAction Stop ConvertFrom-Json -ErrorAction Stop
Add-CatalogValues -Catalog $content -Prefix $catalog -Values $baselineValues Add-CatalogValues -Catalog $content -Prefix $catalog -Values $baselineValues
} }
function Assert-EnglishText {
param([string]$Key)
# Inspect the English catalog directly: translation fallback can hide missing keys.
$baselineValues.ContainsKey($Key) | Should -BeTrue -Because "en-US/$Key must exist"
$baselineValues[$Key] | Should -BeOfType ([string]) -Because "en-US/$Key must be text"
[string]::IsNullOrWhiteSpace($baselineValues[$Key]) |
Should -BeFalse -Because "en-US/$Key must not be blank"
}
}
Describe 'English catalog coverage for shipped definitions' {
It 'has a label and apply text for every feature, including CLI-only features' {
foreach ($feature in $featureConfig.Features) {
foreach ($field in 'Label', 'ApplyText') {
Assert-EnglishText -Key "Features.Features.$($feature.FeatureId).$field"
}
}
}
It 'has undo labels and apply text for every registry or custom undo operation' {
# These operations implement undo in Invoke-FeatureUndo without a RegistryUndoKey.
$customUndoIds = @('DisableStoreSearchSuggestions', 'EnableWindowsSandbox', 'EnableWindowsSubsystemForLinux')
foreach ($feature in $featureConfig.Features) {
if ($feature.RegistryUndoKey -or $feature.FeatureId -in $customUndoIds) {
foreach ($field in 'UndoLabel', 'ApplyUndoText') {
Assert-EnglishText -Key "Features.Features.$($feature.FeatureId).$field"
}
}
}
}
It 'has a tooltip for every feature displayed outside a UI group' {
$groupedFeatureIds = @($featureConfig.UiGroups | ForEach-Object {
$_.Values | ForEach-Object { $_.FeatureIds }
})
foreach ($feature in $featureConfig.Features) {
if ($feature.Category -and $feature.FeatureId -notin $groupedFeatureIds) {
Assert-EnglishText -Key "Features.Features.$($feature.FeatureId).ToolTip"
}
}
}
It 'has a label, tooltip, and every option label for each UI group' {
foreach ($group in $featureConfig.UiGroups) {
foreach ($field in 'Label', 'ToolTip') {
Assert-EnglishText -Key "Features.UiGroups.$($group.GroupId).$field"
}
foreach ($option in $group.Values) {
Assert-EnglishText -Key "Features.UiGroups.$($group.GroupId).Values.$($option.FeatureIds[0])"
}
}
}
It 'has a label for every feature category' {
foreach ($category in $featureConfig.Categories) {
Assert-EnglishText -Key "Categories.$($category.CategoryId).Label"
}
}
It 'has a friendly name and description for every app using its primary ID' {
foreach ($app in $appConfig.Apps) {
# Array entries are aliases of the first ID, as in Import-AppDetailsFromJson.
$primaryAppId = @($app.AppId)[0]
foreach ($field in 'FriendlyName', 'Description') {
Assert-EnglishText -Key "Apps.$primaryAppId.$field"
}
}
}
} }
Describe 'Shipped language catalogs: <LanguageCode>' -ForEach $languageCases { Describe 'Shipped language catalogs: <LanguageCode>' -ForEach $languageCases {
+1 -1
View File
@@ -151,7 +151,7 @@ Describe 'Language changes on existing controls' {
$disabled.ToolTip.Text | Should -Be (Get-Translation -Key 'TweaksAlreadyAppliedTooltip') $disabled.ToolTip.Text | Should -Be (Get-Translation -Key 'TweaksAlreadyAppliedTooltip')
[object]::ReferenceEquals($group.SelectedItem, $selectedItem) | Should -BeTrue [object]::ReferenceEquals($group.SelectedItem, $selectedItem) | Should -BeTrue
$group.SelectedIndex | Should -Be 2 $group.SelectedIndex | Should -Be 2
$selectedItem.Content | Should -Be (Get-GroupValueTranslation -GroupId 'SearchIcon' -FeatureId $script:UiControlMappings['Group_SearchIconCombo'].Values[1].FeatureIds[0] -FallbackLabel 'fallback') $selectedItem.Content | Should -Be (Get-GroupValueTranslation -GroupId 'SearchIcon' -FeatureId $script:UiControlMappings['Group_SearchIconCombo'].Values[1].FeatureIds[0])
@(Get-PendingTweakActions -Window $window -ShowAppliedTweaksMode $true | ForEach-Object { "$($_.Action):$($_.FeatureId)" } | Sort-Object) | Should -Be $before @(Get-PendingTweakActions -Window $window -ShowAppliedTweaksMode $true | ForEach-Object { "$($_.Action):$($_.FeatureId)" } | Sort-Object) | Should -Be $before
$script:FeatureLabelLookup['DisableTelemetry'] | Should -Be $checkbox.Content $script:FeatureLabelLookup['DisableTelemetry'] | Should -Be $checkbox.Content
foreach ($category in $script:CategoryLanguageControls) { foreach ($category in $script:CategoryLanguageControls) {
+8 -1
View File
@@ -7,6 +7,10 @@ BeforeAll {
function Wait-ForKeyPress {} function Wait-ForKeyPress {}
function Show-AppSelectionWindow { $false } function Show-AppSelectionWindow { $false }
. (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-JsonFile.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-LanguageFile.ps1')
$script:Lang = Import-LanguageFile -LanguageCode 'en-US' -LanguagesPath (Join-Path $PSScriptRoot '..\Config\Languages')
. (Join-Path $PSScriptRoot '..\Scripts\CLI\Write-CliHeader.ps1') . (Join-Path $PSScriptRoot '..\Scripts\CLI\Write-CliHeader.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\CLI\Write-PendingChanges.ps1') . (Join-Path $PSScriptRoot '..\Scripts\CLI\Write-PendingChanges.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\CLI\Show-CliAppRemoval.ps1') . (Join-Path $PSScriptRoot '..\Scripts\CLI\Show-CliAppRemoval.ps1')
@@ -20,7 +24,7 @@ Describe 'Show-CliMenuOptions' {
BeforeEach { BeforeEach {
$script:Params = @{} $script:Params = @{}
$script:ControlParams = @('WhatIf', 'Silent') $script:ControlParams = @('WhatIf', 'Silent')
$script:Features = @{ DisableTelemetry = [PSCustomObject]@{ Label = 'Disable telemetry' }; CreateRestorePoint = [PSCustomObject]@{ Label = 'Create restore point' } } $script:Features = @{ DisableTelemetry = [PSCustomObject]@{ FeatureId = 'DisableTelemetry' }; CreateRestorePoint = [PSCustomObject]@{ FeatureId = 'CreateRestorePoint' } }
$script:SelectedApps = @('One.App', 'Two.App') $script:SelectedApps = @('One.App', 'Two.App')
$script:SavedSettingsFilePath = 'C:\Settings\LastUsedSettings.json' $script:SavedSettingsFilePath = 'C:\Settings\LastUsedSettings.json'
$script:DefaultSettingsFilePath = 'C:\Settings\DefaultSettings.json' $script:DefaultSettingsFilePath = 'C:\Settings\DefaultSettings.json'
@@ -62,6 +66,9 @@ Describe 'Show-CliMenuOptions' {
Should -Invoke Generate-AppsList -Times 1 -Exactly Should -Invoke Generate-AppsList -Times 1 -Exactly
Should -Invoke Read-Host -Times 1 -Exactly Should -Invoke Read-Host -Times 1 -Exactly
Should -Invoke Write-Output -Times 2 -ParameterFilter { $InputObject -like '- *' } Should -Invoke Write-Output -Times 2 -ParameterFilter { $InputObject -like '- *' }
Should -Invoke Write-Output -Times 1 -Exactly -ParameterFilter {
$InputObject -eq "- $(Get-Translation -Key 'DisableTelemetry' -Field 'Label' -Section 'Features')"
}
} }
It 'returns the saved-settings menu option only when the file is available' { It 'returns the saved-settings menu option only when the file is available' {
+7 -4
View File
@@ -315,8 +315,8 @@ $script:Features = @{}
try { try {
$featuresData = Get-Content -Path $script:FeaturesFilePath -Raw | ConvertFrom-Json $featuresData = Get-Content -Path $script:FeaturesFilePath -Raw | ConvertFrom-Json
foreach ($feature in $featuresData.Features) { foreach ($feature in $featuresData.Features) {
if ([string]::IsNullOrWhiteSpace([string]$feature.FeatureId) -or [string]::IsNullOrWhiteSpace([string]$feature.Label) -or [string]::IsNullOrWhiteSpace([string]$feature.ApplyText)) { if ([string]::IsNullOrWhiteSpace([string]$feature.FeatureId)) {
Write-Warning "Feature '$($feature.FeatureId)' is missing a FeatureId, Label, or ApplyText in Features.json and will be skipped." Write-Warning "Feature '$($feature.FeatureId)' is missing a FeatureId in Features.json and will be skipped."
continue continue
} }
$script:Features[$feature.FeatureId] = $feature $script:Features[$feature.FeatureId] = $feature
@@ -469,8 +469,8 @@ $WinVersion = Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\Current
# Check if the machine supports Modern Standby, this is used to determine if the DisableModernStandbyNetworking option can be used # Check if the machine supports Modern Standby, this is used to determine if the DisableModernStandbyNetworking option can be used
$script:ModernStandbySupported = Test-ModernStandbySupport $script:ModernStandbySupported = Test-ModernStandbySupport
# Explicit -Language takes precedence over saved UI preferences and the system culture. # Keep CLI output in English until the console interface is fully localized.
Initialize-UiPreferences -Language $Language $script:Lang = Import-LanguageFile -LanguageCode 'en-US'
$script:Params = $PSBoundParameters $script:Params = $PSBoundParameters
$script:UndoParams = @{} $script:UndoParams = @{}
@@ -567,6 +567,8 @@ if ((-not $script:Params.Count) -or $RunDefaults -or $RunDefaultsLite -or $RunSa
} }
else { else {
try { try {
# Explicit -Language takes precedence over saved UI preferences and the system culture.
Initialize-UiPreferences -Language $Language
$result = Show-MainWindow $result = Show-MainWindow
try { try {
@@ -577,6 +579,7 @@ if ((-not $script:Params.Count) -or $RunDefaults -or $RunDefaultsLite -or $RunSa
Exit Exit
} }
catch { catch {
$script:Lang = Import-LanguageFile -LanguageCode 'en-US'
Write-Warning "The graphical interface could not start: $($_.Exception.Message)" Write-Warning "The graphical interface could not start: $($_.Exception.Message)"
Write-Verbose "GUI Failure details: $($_.Exception.ToString())" Write-Verbose "GUI Failure details: $($_.Exception.ToString())"
if (-not $Silent) { if (-not $Silent) {