Add safe configuration deployment

This commit is contained in:
Dandaedre 2026-10-16 13:46:49 +02:00
parent 2865d3a07e
commit ccf1fbf14c
2 changed files with 139 additions and 5 deletions

View File

@ -39,12 +39,12 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
## 4. Implement config deployment
- [ ] Expand destination paths in the original user's context and validate paths.
- [ ] Compute file hashes and classify new, unchanged, changed, and conflicted files.
- [ ] Back up existing files and deploy replacements safely; record state only
- [x] Expand destination paths in the original user's context and validate paths.
- [x] Compute file hashes and classify new, unchanged, changed, and conflicted files.
- [x] Back up existing files and deploy replacements safely; record state only
after successful writes.
- [ ] Detect local edits using the last deployed hash, including local deletions.
- [ ] Add `--force-configs` with mandatory backup before replacement.
- [x] Detect local edits using the last deployed hash, including local deletions.
- [x] Add `--force-configs` with mandatory backup before replacement.
- [ ] Add `sync --configs-only` and config backup restoration.
- [ ] Implement `status` for config drift, conflicts, and last applied revision.

134
src/Configs.psm1 Normal file
View File

@ -0,0 +1,134 @@
Set-StrictMode -Version Latest
function Get-UserPathMap {
param($Settings)
$map = [ordered]@{}
$stored = if ($null -ne $Settings -and $Settings.ContainsKey('userPaths')) { $Settings.userPaths } else { @{} }
foreach ($name in @('APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA')) {
$value = if ($stored.ContainsKey($name)) { [string]$stored[$name] } else { [Environment]::GetEnvironmentVariable($name) }
if ([string]::IsNullOrWhiteSpace($value)) { throw "Required path variable %$name% is unavailable." }
$map[$name] = $value
}
return $map
}
function Resolve-ConfigTarget {
param([Parameter(Mandatory)][string]$Target, [Parameter(Mandatory)]$PathMap)
$unknown = [regex]::Matches($Target, '%([^%]+)%') | ForEach-Object { $_.Groups[1].Value } | Where-Object { $_ -notin $PathMap.Keys }
if ($unknown) { throw "Unsupported path variable(s) in '$Target': $($unknown -join ', ')." }
$resolved = $Target
foreach ($name in $PathMap.Keys) { $resolved = $resolved.Replace("%$name%", [string]$PathMap[$name], [System.StringComparison]::OrdinalIgnoreCase) }
$full = [System.IO.Path]::GetFullPath($resolved)
if (-not [System.IO.Path]::IsPathFullyQualified($full)) { throw "Config target must be absolute: '$Target'." }
return $full
}
function Resolve-ConfigSource {
param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Source)
if ([System.IO.Path]::IsPathFullyQualified($Source)) { throw "Config source must be repository-relative: '$Source'." }
$configRoot = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot 'configs'))
$candidate = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot $Source))
$prefix = $configRoot.TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) + [System.IO.Path]::DirectorySeparatorChar
if (-not $candidate.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { throw "Config source escapes configs/: '$Source'." }
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Config source does not exist: '$Source'." }
return $candidate
}
function Get-FileHashValue {
param([Parameter(Mandatory)][string]$Path)
(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Get-ConfigPlan {
param([Parameter(Mandatory)]$Configs, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$State, [Parameter(Mandatory)]$Settings)
if (-not $State.ContainsKey('configs')) { $State.configs = [ordered]@{} }
$pathMap = Get-UserPathMap -Settings $Settings
$destinations = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$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
if (-not $destinations.Add($target)) { throw "Multiple configs resolve to '$target'." }
$sourceHash = Get-FileHashValue -Path $source
$record = if ($State.configs.ContainsKey($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' }
$plan.Add([pscustomobject]@{
kind = 'config'; name = $config.name; action = $action; reason = $reason
source = $source; target = $target; sourceHash = $sourceHash; targetHash = $targetHash
requiresPackage = if ($config.PSObject.Properties['requiresPackage']) { [string]$config.requiresPackage } else { $null }
})
}
return @($plan)
}
function Backup-ConfigTarget {
param($Operation, $Paths)
if (-not (Test-Path -LiteralPath $Operation.target -PathType Leaf)) { return $null }
$folder = Join-Path $Paths.Backups $Operation.name
[void](New-Item -ItemType Directory -Path $folder -Force)
$backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).bak"
Copy-Item -LiteralPath $Operation.target -Destination $backup -Force
return $backup
}
function Invoke-ConfigOperation {
param([Parameter(Mandatory)]$Operation, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State, [switch]$Force)
if ($Operation.action -eq 'None') {
return [pscustomobject]@{ name = $Operation.name; status = 'Unchanged'; message = $Operation.reason }
}
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"
try {
Copy-Item -LiteralPath $Operation.source -Destination $temporary -Force
[System.IO.File]::Move($temporary, $Operation.target, $true)
if (-not $State.ContainsKey('configs')) { $State.configs = [ordered]@{} }
$State.configs[$Operation.name] = [ordered]@{
target = $Operation.target
deployedHash = $Operation.sourceHash
sourceHash = $Operation.sourceHash
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' } }
}
catch {
return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; message = $_.Exception.Message }
}
finally { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue }
}
function Restore-ConfigBackup {
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State)
$folder = Join-Path $Paths.Backups $Name
$backup = Get-ChildItem -LiteralPath $folder -Filter '*.bak' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
if ($null -eq $backup) { throw "No backup exists for config '$Name'." }
if (-not $State.ContainsKey('configs') -or -not $State.configs.ContainsKey($Name)) { throw "No managed state exists for config '$Name'." }
$target = [string]$State.configs[$Name].target
$current = [pscustomobject]@{ name = $Name; target = $target }
[void](Backup-ConfigTarget -Operation $current -Paths $Paths)
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force)
Copy-Item -LiteralPath $backup.FullName -Destination $target -Force
$hash = Get-FileHashValue -Path $target
$State.configs[$Name].deployedHash = $hash
$State.configs[$Name].sourceHash = $hash
$State.configs[$Name].deployedAt = [DateTimeOffset]::UtcNow.ToString('o')
Write-JsonAtomic -Path $Paths.State -Value $State
[pscustomobject]@{ name = $Name; status = 'Restored'; message = "Restored $($backup.FullName)" }
}
Export-ModuleMember -Function Get-UserPathMap, Resolve-ConfigTarget, Resolve-ConfigSource, Get-FileHashValue, Get-ConfigPlan, Invoke-ConfigOperation, Restore-ConfigBackup