Add application configuration adapters
This commit is contained in:
parent
2fa46d3cff
commit
8b80de6d9b
4
TASKS.md
4
TASKS.md
|
|
@ -97,13 +97,13 @@ open until it is run on disposable machines with the required account setups.
|
|||
- [x] Add an optional numbered terminal menu using existing CLI commands.
|
||||
- [x] Add opt-in scheduled user-context sync with a defined policy for operations
|
||||
requiring elevation.
|
||||
- [ ] Add targeted application adapters or registry settings for concrete needs.
|
||||
- [x] Add targeted application adapters or registry settings for concrete needs.
|
||||
- [ ] Add explicit package removal or managed-file cleanup if requested.
|
||||
|
||||
## Requested desktop configuration
|
||||
|
||||
- [x] Add WinGet packages for MPC-HC, Ontime, XnView MP, and Nextcloud Desktop.
|
||||
- [ ] Add a safe registry-value adapter for MPC-HC settings.
|
||||
- [x] Add a safe registry-value adapter for MPC-HC settings.
|
||||
- [ ] Manage Ontime user settings without treating projects, uploads, or logs as config.
|
||||
- [ ] Manage XnView MP preferences without committing its catalog or thumbnails.
|
||||
- [ ] Add safe Nextcloud preconfiguration without committing account credentials.
|
||||
|
|
|
|||
2
cc.ps1
2
cc.ps1
|
|
@ -15,7 +15,7 @@ param(
|
|||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Configs', 'Elevation', 'Scheduling', 'Core')) {
|
||||
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Adapters', 'Configs', 'Elevation', 'Scheduling', 'Core')) {
|
||||
$path = Join-Path $PSScriptRoot "src/$module.psm1"
|
||||
if (Test-Path -LiteralPath $path) { Import-Module $path -Force }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@
|
|||
"name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" },
|
||||
"source": { "type": "string", "minLength": 1 },
|
||||
"target": { "type": "string", "minLength": 1 },
|
||||
"mode": { "const": "copy", "default": "copy" },
|
||||
"mode": { "enum": ["copy", "ini-overlay", "registry", "hosts-block"], "default": "copy" },
|
||||
"requiresPackage": { "type": "string", "minLength": 1 },
|
||||
"enabled": { "type": "boolean", "default": true }
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,229 @@
|
|||
Set-StrictMode -Version Latest
|
||||
|
||||
function Get-TextHash {
|
||||
param([AllowEmptyString()][string]$Text)
|
||||
$bytes = [Text.Encoding]::UTF8.GetBytes($Text)
|
||||
$hash = [Security.Cryptography.SHA256]::HashData($bytes)
|
||||
[Convert]::ToHexString($hash).ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Get-ObjectHash {
|
||||
param($Value)
|
||||
Get-TextHash -Text ($Value | ConvertTo-Json -Depth 16 -Compress)
|
||||
}
|
||||
|
||||
function Read-IniValues {
|
||||
param([Parameter(Mandatory)][string]$Path)
|
||||
$result = [ordered]@{}
|
||||
$section = ''
|
||||
foreach ($line in @(Get-Content -LiteralPath $Path -ErrorAction Stop)) {
|
||||
$trimmed = $line.Trim()
|
||||
if (-not $trimmed -or $trimmed.StartsWith(';') -or $trimmed.StartsWith('#')) { continue }
|
||||
if ($trimmed -match '^\[(.+)\]$') {
|
||||
$section = $Matches[1]
|
||||
if (-not $result.Contains($section)) { $result[$section] = [ordered]@{} }
|
||||
continue
|
||||
}
|
||||
$separator = $line.IndexOf('=')
|
||||
if ($separator -lt 1) { throw "Invalid INI line in '$Path': $line" }
|
||||
$key = $line.Substring(0, $separator).Trim()
|
||||
$value = $line.Substring($separator + 1).Trim()
|
||||
if (-not $result.Contains($section)) { $result[$section] = [ordered]@{} }
|
||||
if ($result[$section].Contains($key)) { throw "Duplicate INI key '$section/$key' in '$Path'." }
|
||||
$result[$section][$key] = $value
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
function Get-IniSnapshot {
|
||||
param([string]$Path, $Desired)
|
||||
$actual = if (Test-Path -LiteralPath $Path -PathType Leaf) { Read-IniValues -Path $Path } else { [ordered]@{} }
|
||||
$snapshot = [ordered]@{}
|
||||
$present = 0
|
||||
foreach ($section in $Desired.Keys) {
|
||||
$snapshot[$section] = [ordered]@{}
|
||||
foreach ($key in $Desired[$section].Keys) {
|
||||
if ($actual.Contains($section) -and $actual[$section].Contains($key)) {
|
||||
$snapshot[$section][$key] = [string]$actual[$section][$key]
|
||||
$present++
|
||||
}
|
||||
else { $snapshot[$section][$key] = $null }
|
||||
}
|
||||
}
|
||||
[pscustomobject]@{ values = $snapshot; hash = Get-ObjectHash $snapshot; present = $present }
|
||||
}
|
||||
|
||||
function Merge-IniFile {
|
||||
param([string]$Target, $Desired)
|
||||
$lines = [Collections.Generic.List[string]]::new()
|
||||
if (Test-Path -LiteralPath $Target -PathType Leaf) {
|
||||
foreach ($line in @(Get-Content -LiteralPath $Target)) { $lines.Add($line) }
|
||||
}
|
||||
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||
$section = ''
|
||||
for ($index = 0; $index -lt $lines.Count; $index++) {
|
||||
$trimmed = $lines[$index].Trim()
|
||||
if ($trimmed -match '^\[(.+)\]$') { $section = $Matches[1]; continue }
|
||||
$separator = $lines[$index].IndexOf('=')
|
||||
if ($separator -lt 1) { continue }
|
||||
$key = $lines[$index].Substring(0, $separator).Trim()
|
||||
if ($Desired.Contains($section) -and $Desired[$section].Contains($key)) {
|
||||
$lines[$index] = "$key=$($Desired[$section][$key])"
|
||||
[void]$seen.Add("$section`0$key")
|
||||
}
|
||||
}
|
||||
foreach ($desiredSection in $Desired.Keys) {
|
||||
$missing = @($Desired[$desiredSection].Keys | Where-Object { -not $seen.Contains("$desiredSection`0$_") })
|
||||
if ($missing.Count -eq 0) { continue }
|
||||
if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -ne '') { $lines.Add('') }
|
||||
if ($desiredSection) { $lines.Add("[$desiredSection]") }
|
||||
foreach ($key in $missing) { $lines.Add("$key=$($Desired[$desiredSection][$key])") }
|
||||
}
|
||||
return (($lines -join [Environment]::NewLine) + [Environment]::NewLine)
|
||||
}
|
||||
|
||||
function Read-RegistryDeclaration {
|
||||
param([string]$Path)
|
||||
$declaration = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -Depth 16
|
||||
if ($declaration.schemaVersion -ne 1 -or $declaration.values -isnot [System.Array]) { throw "Invalid registry declaration '$Path'." }
|
||||
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($value in $declaration.values) {
|
||||
foreach ($required in @('path', 'name', 'type', 'value')) {
|
||||
if ($null -eq $value.PSObject.Properties[$required]) { throw "Registry declaration '$Path' is missing '$required'." }
|
||||
}
|
||||
if ($value.path -match '(^|\\)\.\.?($|\\)' -or [IO.Path]::IsPathFullyQualified([string]$value.path)) { throw "Unsafe registry subpath '$($value.path)'." }
|
||||
if ($value.name -notmatch '^[^\\/]+$') { throw "Unsafe registry value name '$($value.name)'." }
|
||||
if ($value.type -notin @('String', 'ExpandString', 'DWord', 'QWord', 'MultiString', 'Binary')) { throw "Unsupported registry type '$($value.type)'." }
|
||||
if (-not $seen.Add("$($value.path)\$($value.name)")) { throw "Duplicate registry value '$($value.path)\$($value.name)'." }
|
||||
}
|
||||
return $declaration
|
||||
}
|
||||
|
||||
function Get-RegistrySnapshot {
|
||||
param([string]$Root, $Declaration)
|
||||
$snapshot = [ordered]@{}
|
||||
$present = 0
|
||||
foreach ($entry in $Declaration.values) {
|
||||
$key = "$($entry.path)\$($entry.name)"
|
||||
$registryPath = if ([string]::IsNullOrWhiteSpace([string]$entry.path)) { $Root } else { Join-Path $Root $entry.path }
|
||||
try {
|
||||
$property = Get-ItemProperty -LiteralPath $registryPath -Name $entry.name -ErrorAction Stop
|
||||
$snapshot[$key] = $property.($entry.name)
|
||||
$present++
|
||||
}
|
||||
catch { $snapshot[$key] = $null }
|
||||
}
|
||||
[pscustomobject]@{ values = $snapshot; hash = Get-ObjectHash $snapshot; present = $present }
|
||||
}
|
||||
|
||||
function Get-HostsDeclaration {
|
||||
param([string]$Path)
|
||||
$lines = [Collections.Generic.List[string]]::new()
|
||||
foreach ($line in @(Get-Content -LiteralPath $Path)) {
|
||||
$trimmed = $line.Trim()
|
||||
if (-not $trimmed -or $trimmed.StartsWith('#')) { continue }
|
||||
$parts = @($trimmed -split '\s+')
|
||||
$address = $null
|
||||
if ($parts.Count -lt 2 -or -not [Net.IPAddress]::TryParse($parts[0], [ref]$address)) { throw "Invalid hosts entry in '$Path': $line" }
|
||||
foreach ($hostName in $parts[1..($parts.Count - 1)]) {
|
||||
if ($hostName.StartsWith('#')) { break }
|
||||
if ($hostName -notmatch '^[A-Za-z0-9._-]+$') { throw "Invalid host name '$hostName' in '$Path'." }
|
||||
}
|
||||
$lines.Add($trimmed)
|
||||
}
|
||||
return @($lines)
|
||||
}
|
||||
|
||||
function Get-HostsBlock {
|
||||
param([string]$Path, [string]$Name)
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $null }
|
||||
$begin = "# BEGIN CONFIG CENTRAL: $Name"
|
||||
$end = "# END CONFIG CENTRAL: $Name"
|
||||
$inside = $false
|
||||
$found = $false
|
||||
$lines = [Collections.Generic.List[string]]::new()
|
||||
foreach ($line in @(Get-Content -LiteralPath $Path)) {
|
||||
if ($line.Trim() -eq $begin) { if ($found -or $inside) { throw "Duplicate hosts block '$Name'." }; $inside = $true; $found = $true; continue }
|
||||
if ($line.Trim() -eq $end) { if (-not $inside) { throw "Unmatched hosts block end '$Name'." }; $inside = $false; continue }
|
||||
if ($inside) { $lines.Add($line.Trim()) }
|
||||
}
|
||||
if ($inside) { throw "Unclosed hosts block '$Name'." }
|
||||
if (-not $found) { return $null }
|
||||
return @($lines)
|
||||
}
|
||||
|
||||
function Get-AdapterPlan {
|
||||
param($Config, [string]$Source, [string]$Target, $Record)
|
||||
if ($Config.mode -eq 'ini-overlay') {
|
||||
$desired = Read-IniValues -Path $Source
|
||||
$count = @($desired.Keys | ForEach-Object { $desired[$_].Count } | Measure-Object -Sum).Sum
|
||||
if (-not $count) { return [pscustomobject]@{ action = 'None'; reason = 'INI overlay has no active keys'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $false } }
|
||||
$current = Get-IniSnapshot -Path $Target -Desired $desired
|
||||
$desiredHash = Get-ObjectHash $desired
|
||||
}
|
||||
elseif ($Config.mode -eq 'registry') {
|
||||
if (-not $IsWindows) { throw 'Registry configs can only be planned on Windows.' }
|
||||
if ($Target -notmatch '^HKCU:\\Software\\MPC-HC\\MPC-HC(?:\\.*)?$') { throw "Registry target is outside the allowed MPC-HC key: '$Target'." }
|
||||
$desired = Read-RegistryDeclaration -Path $Source
|
||||
if ($desired.values.Count -eq 0) { return [pscustomobject]@{ action = 'None'; reason = 'Registry declaration has no values'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $false } }
|
||||
$current = Get-RegistrySnapshot -Root $Target -Declaration $desired
|
||||
$desiredValues = [ordered]@{}
|
||||
foreach ($entry in $desired.values) { $desiredValues["$($entry.path)\$($entry.name)"] = $entry.value }
|
||||
$desiredHash = Get-ObjectHash $desiredValues
|
||||
}
|
||||
elseif ($Config.mode -eq 'hosts-block') {
|
||||
$desired = @(Get-HostsDeclaration -Path $Source)
|
||||
if ($desired.Count -eq 0) { return [pscustomobject]@{ action = 'None'; reason = 'Hosts declaration has no active entries'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $true } }
|
||||
$currentBlock = Get-HostsBlock -Path $Target -Name $Config.name
|
||||
$current = [pscustomobject]@{ values = $currentBlock; hash = if ($null -eq $currentBlock) { $null } else { Get-ObjectHash @($currentBlock) }; present = if ($null -eq $currentBlock) { 0 } else { @($currentBlock).Count } }
|
||||
$desiredHash = Get-ObjectHash $desired
|
||||
}
|
||||
else { throw "Unknown adapter mode '$($Config.mode)'." }
|
||||
|
||||
$lastHash = if ($null -ne $Record -and $Record.Contains('deployedHash')) { [string]$Record.deployedHash } else { $null }
|
||||
if ($null -eq $Record -and $current.present -eq 0) { $action = 'Create'; $reason = 'Managed values are absent' }
|
||||
elseif ($null -eq $Record -and $current.hash -eq $desiredHash) { $action = 'Adopt'; $reason = 'Managed values already match' }
|
||||
elseif ($null -eq $Record) { $action = 'Conflict'; $reason = 'Existing managed values are not owned by Config Central' }
|
||||
elseif ($current.hash -ne $lastHash) { $action = 'Conflict'; $reason = 'Managed values were edited locally' }
|
||||
elseif ($current.hash -eq $desiredHash) { $action = 'None'; $reason = 'Managed values are current' }
|
||||
else { $action = 'Update'; $reason = 'Repository values changed' }
|
||||
[pscustomobject]@{ action = $action; reason = $reason; desired = $desired; desiredHash = $desiredHash; currentHash = $current.hash; requiresAdmin = ($Config.mode -eq 'hosts-block') }
|
||||
}
|
||||
|
||||
function Set-RegistryDeclaration {
|
||||
param([string]$Root, $Declaration)
|
||||
foreach ($entry in $Declaration.values) {
|
||||
$path = if ([string]::IsNullOrWhiteSpace([string]$entry.path)) { $Root } else { Join-Path $Root $entry.path }
|
||||
[void](New-Item -Path $path -Force)
|
||||
$value = switch ($entry.type) {
|
||||
'DWord' { [uint32]$entry.value }
|
||||
'QWord' { [uint64]$entry.value }
|
||||
'Binary' { [byte[]]@($entry.value) }
|
||||
'MultiString' { [string[]]@($entry.value) }
|
||||
default { [string]$entry.value }
|
||||
}
|
||||
[void](New-ItemProperty -LiteralPath $path -Name $entry.name -PropertyType $entry.type -Value $value -Force)
|
||||
}
|
||||
}
|
||||
|
||||
function Set-HostsBlockContent {
|
||||
param([string]$Target, [string]$Name, [string[]]$Lines)
|
||||
$begin = "# BEGIN CONFIG CENTRAL: $Name"
|
||||
$end = "# END CONFIG CENTRAL: $Name"
|
||||
$existing = if (Test-Path -LiteralPath $Target -PathType Leaf) { [Collections.Generic.List[string]]@(Get-Content -LiteralPath $Target) } else { [Collections.Generic.List[string]]::new() }
|
||||
$output = [Collections.Generic.List[string]]::new()
|
||||
$inside = $false
|
||||
foreach ($line in $existing) {
|
||||
if ($line.Trim() -eq $begin) { $inside = $true; continue }
|
||||
if ($line.Trim() -eq $end) { $inside = $false; continue }
|
||||
if (-not $inside) { $output.Add($line) }
|
||||
}
|
||||
while ($output.Count -gt 0 -and -not $output[$output.Count - 1].Trim()) { $output.RemoveAt($output.Count - 1) }
|
||||
if ($output.Count -gt 0) { $output.Add('') }
|
||||
$output.Add($begin)
|
||||
foreach ($line in $Lines) { $output.Add($line) }
|
||||
$output.Add($end)
|
||||
(($output -join [Environment]::NewLine) + [Environment]::NewLine)
|
||||
}
|
||||
|
||||
Export-ModuleMember -Function Get-ObjectHash, Read-IniValues, Get-IniSnapshot, Merge-IniFile, Read-RegistryDeclaration, Get-RegistrySnapshot, Get-HostsDeclaration, Get-HostsBlock, Get-AdapterPlan, Set-RegistryDeclaration, Set-HostsBlockContent
|
||||
|
|
@ -4,10 +4,9 @@ function Get-UserPathMap {
|
|||
param($Settings)
|
||||
$map = [ordered]@{}
|
||||
$stored = if ($null -ne $Settings -and $Settings.Contains('userPaths')) { $Settings.userPaths } else { @{} }
|
||||
foreach ($name in @('APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA')) {
|
||||
foreach ($name in @('APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA', 'SYSTEMROOT')) {
|
||||
$value = if ($stored.Contains($name)) { [string]$stored[$name] } else { [Environment]::GetEnvironmentVariable($name) }
|
||||
if ([string]::IsNullOrWhiteSpace($value)) { throw "Required path variable %$name% is unavailable." }
|
||||
$map[$name] = $value
|
||||
if (-not [string]::IsNullOrWhiteSpace($value)) { $map[$name] = $value }
|
||||
}
|
||||
return $map
|
||||
}
|
||||
|
|
@ -47,23 +46,36 @@ function Get-ConfigPlan {
|
|||
$plan = [System.Collections.Generic.List[object]]::new()
|
||||
foreach ($config in @($Configs)) {
|
||||
$source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source
|
||||
$target = Resolve-ConfigTarget -Target $config.target -PathMap $pathMap
|
||||
$target = if ($config.mode -eq 'registry') { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap }
|
||||
if (-not $destinations.Add($target)) { throw "Multiple configs resolve to '$target'." }
|
||||
$sourceHash = Get-FileHashValue -Path $source
|
||||
$record = if ($State.configs.Contains($config.name)) { $State.configs[$config.name] } else { $null }
|
||||
$targetExists = Test-Path -LiteralPath $target -PathType Leaf
|
||||
$targetHash = if ($targetExists) { Get-FileHashValue -Path $target } else { $null }
|
||||
|
||||
if (-not $targetExists -and $null -eq $record) { $action = 'Create'; $reason = 'Destination is absent' }
|
||||
elseif ($null -eq $record) { $action = 'Conflict'; $reason = 'Existing destination is not managed' }
|
||||
elseif (-not $targetExists) { $action = 'Conflict'; $reason = 'Managed destination was deleted locally' }
|
||||
elseif ($targetHash -ne [string]$record.deployedHash) { $action = 'Conflict'; $reason = 'Managed destination was edited locally' }
|
||||
elseif ($targetHash -eq $sourceHash) { $action = 'None'; $reason = 'Content is current' }
|
||||
else { $action = 'Update'; $reason = 'Repository content changed' }
|
||||
if ($config.mode -eq 'copy') {
|
||||
$sourceHash = Get-FileHashValue -Path $source
|
||||
$targetExists = Test-Path -LiteralPath $target -PathType Leaf
|
||||
$targetHash = if ($targetExists) { Get-FileHashValue -Path $target } else { $null }
|
||||
if (-not $targetExists -and $null -eq $record) { $action = 'Create'; $reason = 'Destination is absent' }
|
||||
elseif ($null -eq $record) { $action = 'Conflict'; $reason = 'Existing destination is not managed' }
|
||||
elseif (-not $targetExists) { $action = 'Conflict'; $reason = 'Managed destination was deleted locally' }
|
||||
elseif ($targetHash -ne [string]$record.deployedHash) { $action = 'Conflict'; $reason = 'Managed destination was edited locally' }
|
||||
elseif ($targetHash -eq $sourceHash) { $action = 'None'; $reason = 'Content is current' }
|
||||
else { $action = 'Update'; $reason = 'Repository content changed' }
|
||||
$desired = $null
|
||||
$requiresAdmin = $false
|
||||
}
|
||||
else {
|
||||
$adapterPlan = Get-AdapterPlan -Config $config -Source $source -Target $target -Record $record
|
||||
$sourceHash = $adapterPlan.desiredHash
|
||||
$targetHash = $adapterPlan.currentHash
|
||||
$action = $adapterPlan.action
|
||||
$reason = $adapterPlan.reason
|
||||
$desired = $adapterPlan.desired
|
||||
$requiresAdmin = [bool]$adapterPlan.requiresAdmin
|
||||
}
|
||||
|
||||
$plan.Add([pscustomobject]@{
|
||||
kind = 'config'; name = $config.name; action = $action; reason = $reason
|
||||
source = $source; target = $target; sourceHash = $sourceHash; targetHash = $targetHash
|
||||
mode = $config.mode; desired = $desired; requiresAdmin = $requiresAdmin
|
||||
requiresPackage = if ($config.PSObject.Properties['requiresPackage']) { [string]$config.requiresPackage } else { $null }
|
||||
})
|
||||
}
|
||||
|
|
@ -88,23 +100,40 @@ function Invoke-ConfigOperation {
|
|||
if ($Operation.action -eq 'Conflict' -and -not $Force) {
|
||||
return [pscustomobject]@{ name = $Operation.name; status = 'Conflict'; message = "$($Operation.reason); use -ForceConfigs to back up and replace it" }
|
||||
}
|
||||
$backup = Backup-ConfigTarget -Operation $Operation -Paths $Paths
|
||||
$directory = Split-Path -Parent $Operation.target
|
||||
[void](New-Item -ItemType Directory -Path $directory -Force)
|
||||
$temporary = Join-Path $directory ".$([System.IO.Path]::GetFileName($Operation.target)).$([guid]::NewGuid().ToString('N')).tmp"
|
||||
$backup = $null
|
||||
$temporary = $null
|
||||
try {
|
||||
Copy-Item -LiteralPath $Operation.source -Destination $temporary -Force
|
||||
[System.IO.File]::Move($temporary, $Operation.target, $true)
|
||||
if ($Operation.action -ne 'Adopt') {
|
||||
if ($Operation.mode -eq 'registry') {
|
||||
$folder = Join-Path $Paths.Backups $Operation.name
|
||||
[void](New-Item -ItemType Directory -Path $folder -Force)
|
||||
$backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json"
|
||||
(Get-RegistrySnapshot -Root $Operation.target -Declaration $Operation.desired).values | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $backup -Encoding utf8NoBOM
|
||||
Set-RegistryDeclaration -Root $Operation.target -Declaration $Operation.desired
|
||||
}
|
||||
else {
|
||||
$backup = Backup-ConfigTarget -Operation $Operation -Paths $Paths
|
||||
$directory = Split-Path -Parent $Operation.target
|
||||
[void](New-Item -ItemType Directory -Path $directory -Force)
|
||||
$temporary = Join-Path $directory ".$([System.IO.Path]::GetFileName($Operation.target)).$([guid]::NewGuid().ToString('N')).tmp"
|
||||
if ($Operation.mode -eq 'copy') { Copy-Item -LiteralPath $Operation.source -Destination $temporary -Force }
|
||||
elseif ($Operation.mode -eq 'ini-overlay') { [IO.File]::WriteAllText($temporary, (Merge-IniFile -Target $Operation.target -Desired $Operation.desired), [Text.UTF8Encoding]::new($false)) }
|
||||
elseif ($Operation.mode -eq 'hosts-block') { [IO.File]::WriteAllText($temporary, (Set-HostsBlockContent -Target $Operation.target -Name $Operation.name -Lines $Operation.desired), [Text.UTF8Encoding]::new($false)) }
|
||||
else { throw "Unsupported config mode '$($Operation.mode)'." }
|
||||
[System.IO.File]::Move($temporary, $Operation.target, $true)
|
||||
}
|
||||
}
|
||||
if (-not $State.Contains('configs')) { $State.configs = [ordered]@{} }
|
||||
$State.configs[$Operation.name] = [ordered]@{
|
||||
target = $Operation.target
|
||||
deployedHash = $Operation.sourceHash
|
||||
sourceHash = $Operation.sourceHash
|
||||
mode = $Operation.mode
|
||||
deployedAt = [DateTimeOffset]::UtcNow.ToString('o')
|
||||
lastBackup = $backup
|
||||
}
|
||||
Write-JsonAtomic -Path $Paths.State -Value $State
|
||||
return [pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; message = if ($backup) { "Deployed; backup: $backup" } else { 'Deployed' } }
|
||||
return [pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; message = if ($Operation.action -eq 'Adopt') { 'Adopted matching managed values' } elseif ($backup) { "Deployed; backup: $backup" } else { 'Deployed' } }
|
||||
}
|
||||
catch {
|
||||
return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; message = $_.Exception.Message }
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ function Assert-ItemList {
|
|||
if ($enabled) {
|
||||
if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'source'))) { throw "$Location[$index].source is required." }
|
||||
if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'target'))) { throw "$Location[$index].target is required." }
|
||||
if ((Get-OptionalProperty $item 'mode' 'copy') -ne 'copy') { throw "Only copy mode is supported at $Location[$index]." }
|
||||
if ((Get-OptionalProperty $item 'mode' 'copy') -notin @('copy', 'ini-overlay', 'registry', 'hosts-block')) { throw "Unsupported config mode at $Location[$index]." }
|
||||
}
|
||||
}
|
||||
if (-not $keys.Add($key)) { throw "Duplicate $Kind key '$key' in $Location." }
|
||||
|
|
@ -131,7 +131,7 @@ function Add-ManifestItems {
|
|||
}
|
||||
}
|
||||
else {
|
||||
$normalized = [ordered]@{ name = [string]$item.name; source = [string]$item.source; target = [string]$item.target; mode = 'copy' }
|
||||
$normalized = [ordered]@{ name = [string]$item.name; source = [string]$item.source; target = [string]$item.target; mode = [string](Get-OptionalProperty $item 'mode' 'copy') }
|
||||
$requires = Get-OptionalProperty $item 'requiresPackage'
|
||||
if ($null -ne $requires) { $normalized.requiresPackage = [string]$requires }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
BeforeAll {
|
||||
Import-Module "$PSScriptRoot/../src/Adapters.psm1" -Force
|
||||
}
|
||||
|
||||
Describe 'Application configuration adapters' {
|
||||
It 'merges only declared INI keys and preserves other values' {
|
||||
$target = Join-Path $TestDrive 'nextcloud.cfg'
|
||||
$overlay = Join-Path $TestDrive 'overlay.ini'
|
||||
"[General]`nexisting=keep`nchunkSize=10`n`n[Account0]`nauthToken=secret" | Set-Content $target
|
||||
"[General]`nchunkSize=20`nnewValue=yes" | Set-Content $overlay
|
||||
$desired = Read-IniValues -Path $overlay
|
||||
$merged = Merge-IniFile -Target $target -Desired $desired
|
||||
$merged | Should -Match 'existing=keep'
|
||||
$merged | Should -Match 'chunkSize=20'
|
||||
$merged | Should -Match 'newValue=yes'
|
||||
$merged | Should -Match 'authToken=secret'
|
||||
}
|
||||
|
||||
It 'treats a comment-only INI overlay as a no-op' {
|
||||
$source = Join-Path $TestDrive 'empty.ini'
|
||||
'# Add managed keys here.' | Set-Content $source
|
||||
$config = [pscustomobject]@{ name = 'safe'; mode = 'ini-overlay' }
|
||||
(Get-AdapterPlan -Config $config -Source $source -Target (Join-Path $TestDrive 'target.ini') -Record $null).action | Should -Be 'None'
|
||||
}
|
||||
|
||||
It 'validates hosts entries and replaces only its named block' {
|
||||
$source = Join-Path $TestDrive 'hosts.entries'
|
||||
$target = Join-Path $TestDrive 'hosts'
|
||||
"127.0.0.1 before.example`n# ignored" | Set-Content $source
|
||||
"10.0.0.1 outside.example`n`n# BEGIN CONFIG CENTRAL: managed-hosts`n127.0.0.1 old.example`n# END CONFIG CENTRAL: managed-hosts" | Set-Content $target
|
||||
$lines = Get-HostsDeclaration -Path $source
|
||||
$content = Set-HostsBlockContent -Target $target -Name managed-hosts -Lines $lines
|
||||
$content | Should -Match '10.0.0.1 outside.example'
|
||||
$content | Should -Match '127.0.0.1 before.example'
|
||||
$content | Should -Not -Match 'old.example'
|
||||
}
|
||||
|
||||
It 'rejects invalid hosts addresses' {
|
||||
$source = Join-Path $TestDrive 'bad-hosts.entries'
|
||||
'not-an-address example.test' | Set-Content $source
|
||||
{ Get-HostsDeclaration -Path $source } | Should -Throw '*Invalid hosts entry*'
|
||||
}
|
||||
|
||||
It 'accepts constrained registry declarations and rejects escaping paths' {
|
||||
$valid = Join-Path $TestDrive 'registry.json'
|
||||
'{"schemaVersion":1,"values":[{"path":"Settings","name":"RememberFilePos","type":"DWord","value":1}]}' | Set-Content $valid
|
||||
(Read-RegistryDeclaration -Path $valid).values.Count | Should -Be 1
|
||||
$invalid = Join-Path $TestDrive 'invalid-registry.json'
|
||||
'{"schemaVersion":1,"values":[{"path":"..\\Other","name":"Value","type":"String","value":"x"}]}' | Set-Content $invalid
|
||||
{ Read-RegistryDeclaration -Path $invalid } | Should -Throw '*Unsafe registry subpath*'
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ BeforeAll {
|
|||
Describe 'Manifest resolution' {
|
||||
It 'resolves the checked-in example in profile order' {
|
||||
$result = Resolve-MachineManifest -RepositoryRoot "$PSScriptRoot/.." -Machine 'example-desktop'
|
||||
$result.packages.Count | Should -Be 3
|
||||
$result.packages.Count | Should -Be 7
|
||||
$result.configs.Count | Should -Be 2
|
||||
$result.packages[0].id | Should -Be 'Git.Git'
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue