Add manifest resolution and state foundation
This commit is contained in:
parent
6c19178550
commit
7ab78e820e
4
TASKS.md
4
TASKS.md
|
|
@ -21,11 +21,11 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
|
|||
## 2. Build the CLI foundation
|
||||
|
||||
- [ ] Add `cc.ps1`, module loading, and the `cc` launcher.
|
||||
- [ ] Implement manifest loading, validation, and effective machine configuration.
|
||||
- [x] Implement manifest loading, validation, and effective machine configuration.
|
||||
- [ ] Implement `doctor` for Windows/PowerShell, WinGet, Git, repository access,
|
||||
package sources, and required permissions.
|
||||
- [ ] Implement a shared operation plan consumed by `plan` and `apply`.
|
||||
- [ ] Add per-item logging, run summaries, atomic state writes, and a run lock.
|
||||
- [x] Add per-item logging, run summaries, atomic state writes, and a run lock.
|
||||
|
||||
## 3. Implement repository synchronization
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,163 @@
|
|||
Set-StrictMode -Version Latest
|
||||
|
||||
function Assert-JsonHasNoDuplicateKeys {
|
||||
param([Parameter(Mandatory)][string]$Path)
|
||||
|
||||
$document = [System.Text.Json.JsonDocument]::Parse([System.IO.File]::ReadAllText($Path))
|
||||
try {
|
||||
function Test-Element([System.Text.Json.JsonElement]$Element, [string]$Location) {
|
||||
if ($Element.ValueKind -eq [System.Text.Json.JsonValueKind]::Object) {
|
||||
$seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
|
||||
foreach ($property in $Element.EnumerateObject()) {
|
||||
if (-not $seen.Add($property.Name)) {
|
||||
throw "Duplicate JSON key '$($property.Name)' at $Location in '$Path'."
|
||||
}
|
||||
Test-Element $property.Value "$Location.$($property.Name)"
|
||||
}
|
||||
}
|
||||
elseif ($Element.ValueKind -eq [System.Text.Json.JsonValueKind]::Array) {
|
||||
$index = 0
|
||||
foreach ($item in $Element.EnumerateArray()) {
|
||||
Test-Element $item "$Location[$index]"
|
||||
$index++
|
||||
}
|
||||
}
|
||||
}
|
||||
Test-Element $document.RootElement '$'
|
||||
}
|
||||
finally {
|
||||
$document.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-AllowedProperties {
|
||||
param($Object, [string[]]$Allowed, [string]$Location)
|
||||
foreach ($property in $Object.PSObject.Properties.Name) {
|
||||
if ($property -eq '$schema') { continue }
|
||||
if ($property -notin $Allowed) { throw "Unknown field '$property' at $Location." }
|
||||
}
|
||||
}
|
||||
|
||||
function Get-OptionalProperty {
|
||||
param($Object, [string]$Name, $Default = $null)
|
||||
$property = $Object.PSObject.Properties[$Name]
|
||||
if ($null -eq $property) { return $Default }
|
||||
return $property.Value
|
||||
}
|
||||
|
||||
function Assert-ItemList {
|
||||
param($Items, [ValidateSet('package', 'config')][string]$Kind, [string]$Location)
|
||||
if ($null -eq $Items) { return }
|
||||
if ($Items -isnot [System.Array]) { throw "$Location must be an array." }
|
||||
|
||||
$keys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
|
||||
$index = 0
|
||||
foreach ($item in $Items) {
|
||||
if ($Kind -eq 'package') {
|
||||
Assert-AllowedProperties $item @('id', 'source', 'scope', 'version', 'update', 'enabled') "$Location[$index]"
|
||||
if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'id'))) { throw "$Location[$index].id is required." }
|
||||
$source = [string](Get-OptionalProperty $item 'source' 'winget')
|
||||
$key = "$source/$($item.id)"
|
||||
$scope = Get-OptionalProperty $item 'scope'
|
||||
if ($null -ne $scope -and $scope -notin @('user', 'machine')) { throw "Invalid package scope at $Location[$index]." }
|
||||
$update = [string](Get-OptionalProperty $item 'update' 'latest')
|
||||
if ($update -notin @('latest', 'pinned', 'install-only')) { throw "Invalid update policy at $Location[$index]." }
|
||||
if ($update -eq 'pinned' -and [string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'version'))) {
|
||||
throw "Pinned package at $Location[$index] requires a version."
|
||||
}
|
||||
}
|
||||
else {
|
||||
Assert-AllowedProperties $item @('name', 'source', 'target', 'mode', 'requiresPackage', 'enabled') "$Location[$index]"
|
||||
if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $item 'name'))) { throw "$Location[$index].name is required." }
|
||||
$key = [string]$item.name
|
||||
$enabled = [bool](Get-OptionalProperty $item 'enabled' $true)
|
||||
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 (-not $keys.Add($key)) { throw "Duplicate $Kind key '$key' in $Location." }
|
||||
$index++
|
||||
}
|
||||
}
|
||||
|
||||
function Read-ManifestFile {
|
||||
param([Parameter(Mandatory)][string]$Path, [ValidateSet('profile', 'machine')][string]$Kind)
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Missing $Kind manifest '$Path'." }
|
||||
Assert-JsonHasNoDuplicateKeys -Path $Path
|
||||
try { $manifest = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -Depth 32 }
|
||||
catch { throw "Invalid JSON in '$Path': $($_.Exception.Message)" }
|
||||
Assert-AllowedProperties $manifest @('schemaVersion', 'name', 'description', 'profiles', 'packages', 'configs') $Path
|
||||
if ((Get-OptionalProperty $manifest 'schemaVersion') -ne 1) { throw "Unsupported schemaVersion in '$Path'." }
|
||||
if ([string]::IsNullOrWhiteSpace([string](Get-OptionalProperty $manifest 'name'))) { throw "Manifest name is required in '$Path'." }
|
||||
if ($manifest.name -notmatch '^[a-z0-9][a-z0-9-]*$') { throw "Invalid manifest name '$($manifest.name)'." }
|
||||
if ($Kind -eq 'machine') {
|
||||
$profiles = Get-OptionalProperty $manifest 'profiles'
|
||||
if ($profiles -isnot [System.Array] -or $profiles.Count -eq 0) { throw "Machine '$($manifest.name)' requires at least one profile." }
|
||||
$uniqueProfiles = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($profile in $profiles) {
|
||||
if ($profile -notmatch '^[a-z0-9][a-z0-9-]*$' -or -not $uniqueProfiles.Add([string]$profile)) {
|
||||
throw "Invalid or duplicate profile '$profile' in '$Path'."
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert-ItemList (Get-OptionalProperty $manifest 'packages' @()) package "$Path.packages"
|
||||
Assert-ItemList (Get-OptionalProperty $manifest 'configs' @()) config "$Path.configs"
|
||||
return $manifest
|
||||
}
|
||||
|
||||
function Add-ManifestItems {
|
||||
param($Target, $Items, [ValidateSet('package', 'config')][string]$Kind)
|
||||
foreach ($item in @($Items)) {
|
||||
if ($Kind -eq 'package') {
|
||||
$source = [string](Get-OptionalProperty $item 'source' 'winget')
|
||||
$key = "$source/$($item.id)".ToLowerInvariant()
|
||||
}
|
||||
else { $key = ([string]$item.name).ToLowerInvariant() }
|
||||
$enabled = [bool](Get-OptionalProperty $item 'enabled' $true)
|
||||
if (-not $enabled) { $Target.Remove($key); continue }
|
||||
|
||||
if ($Kind -eq 'package') {
|
||||
$normalized = [ordered]@{ id = [string]$item.id; source = $source; update = [string](Get-OptionalProperty $item 'update' 'latest') }
|
||||
foreach ($field in @('scope', 'version')) {
|
||||
$value = Get-OptionalProperty $item $field
|
||||
if ($null -ne $value) { $normalized[$field] = [string]$value }
|
||||
}
|
||||
}
|
||||
else {
|
||||
$normalized = [ordered]@{ name = [string]$item.name; source = [string]$item.source; target = [string]$item.target; mode = 'copy' }
|
||||
$requires = Get-OptionalProperty $item 'requiresPackage'
|
||||
if ($null -ne $requires) { $normalized.requiresPackage = [string]$requires }
|
||||
}
|
||||
$Target[$key] = [pscustomobject]$normalized
|
||||
}
|
||||
}
|
||||
|
||||
function Resolve-MachineManifest {
|
||||
param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Machine)
|
||||
if ($Machine -notmatch '^[a-z0-9][a-z0-9-]*$') { throw "Invalid machine name '$Machine'." }
|
||||
$machinePath = Join-Path $RepositoryRoot "machines/$Machine.json"
|
||||
$machineManifest = Read-ManifestFile $machinePath machine
|
||||
if ($machineManifest.name -ne $Machine) { throw "Machine filename and manifest name do not match." }
|
||||
|
||||
$packages = [ordered]@{}
|
||||
$configs = [ordered]@{}
|
||||
foreach ($profileName in $machineManifest.profiles) {
|
||||
$profilePath = Join-Path $RepositoryRoot "profiles/$profileName.json"
|
||||
$profile = Read-ManifestFile $profilePath profile
|
||||
if ($profile.name -ne $profileName) { throw "Profile filename and manifest name do not match for '$profileName'." }
|
||||
Add-ManifestItems $packages (Get-OptionalProperty $profile 'packages' @()) package
|
||||
Add-ManifestItems $configs (Get-OptionalProperty $profile 'configs' @()) config
|
||||
}
|
||||
Add-ManifestItems $packages (Get-OptionalProperty $machineManifest 'packages' @()) package
|
||||
Add-ManifestItems $configs (Get-OptionalProperty $machineManifest 'configs' @()) config
|
||||
|
||||
$destinations = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($config in $configs.Values) {
|
||||
if (-not $destinations.Add($config.target)) { throw "Config destination collision at '$($config.target)'." }
|
||||
}
|
||||
[pscustomobject]@{ schemaVersion = 1; machine = $Machine; packages = @($packages.Values); configs = @($configs.Values) }
|
||||
}
|
||||
|
||||
Export-ModuleMember -Function Read-ManifestFile, Resolve-MachineManifest
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
Set-StrictMode -Version Latest
|
||||
|
||||
function Get-ConfigCentralPaths {
|
||||
param([string]$DataRoot)
|
||||
if ([string]::IsNullOrWhiteSpace($DataRoot)) {
|
||||
if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { throw 'LOCALAPPDATA is unavailable; pass -DataRoot.' }
|
||||
$DataRoot = Join-Path $env:LOCALAPPDATA 'ConfigCentral'
|
||||
}
|
||||
[pscustomobject]@{
|
||||
Root = $DataRoot
|
||||
State = Join-Path $DataRoot 'state.json'
|
||||
Settings = Join-Path $DataRoot 'settings.json'
|
||||
Logs = Join-Path $DataRoot 'logs'
|
||||
Backups = Join-Path $DataRoot 'backups'
|
||||
Snapshots = Join-Path $DataRoot 'snapshots'
|
||||
Lock = Join-Path $DataRoot 'apply.lock'
|
||||
}
|
||||
}
|
||||
|
||||
function Initialize-ConfigCentralData {
|
||||
param($Paths)
|
||||
foreach ($path in @($Paths.Root, $Paths.Logs, $Paths.Backups, $Paths.Snapshots)) {
|
||||
[void](New-Item -ItemType Directory -Path $path -Force)
|
||||
}
|
||||
}
|
||||
|
||||
function Read-JsonState {
|
||||
param([string]$Path, $Default)
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $Default }
|
||||
try { return Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable -Depth 32 }
|
||||
catch { throw "Cannot read state '$Path': $($_.Exception.Message)" }
|
||||
}
|
||||
|
||||
function Write-JsonAtomic {
|
||||
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)]$Value)
|
||||
$directory = Split-Path -Parent $Path
|
||||
[void](New-Item -ItemType Directory -Path $directory -Force)
|
||||
$temporary = "$Path.$([guid]::NewGuid().ToString('N')).tmp"
|
||||
try {
|
||||
$Value | ConvertTo-Json -Depth 32 | Set-Content -LiteralPath $temporary -Encoding utf8NoBOM
|
||||
[System.IO.File]::Move($temporary, $Path, $true)
|
||||
}
|
||||
finally { if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force } }
|
||||
}
|
||||
|
||||
function Enter-ApplyLock {
|
||||
param($Paths)
|
||||
Initialize-ConfigCentralData $Paths
|
||||
try {
|
||||
$stream = [System.IO.File]::Open($Paths.Lock, 'OpenOrCreate', 'ReadWrite', 'None')
|
||||
$writer = [System.IO.StreamWriter]::new($stream, [System.Text.Encoding]::UTF8, 1024, $true)
|
||||
$stream.SetLength(0)
|
||||
$writer.Write("pid=$PID started=$([DateTimeOffset]::UtcNow.ToString('o'))")
|
||||
$writer.Flush()
|
||||
return $stream
|
||||
}
|
||||
catch { throw "Another Config Central apply appears to be running: $($_.Exception.Message)" }
|
||||
}
|
||||
|
||||
function Exit-ApplyLock {
|
||||
param($Lock, $Paths)
|
||||
if ($null -ne $Lock) { $Lock.Dispose() }
|
||||
Remove-Item -LiteralPath $Paths.Lock -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function New-RunContext {
|
||||
param($Paths, [string]$Command, [string]$Revision)
|
||||
Initialize-ConfigCentralData $Paths
|
||||
$runId = [DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')
|
||||
[pscustomobject]@{
|
||||
id = $runId
|
||||
command = $Command
|
||||
revision = $Revision
|
||||
startedAt = [DateTimeOffset]::UtcNow.ToString('o')
|
||||
logPath = Join-Path $Paths.Logs "$runId.log"
|
||||
results = [System.Collections.Generic.List[object]]::new()
|
||||
}
|
||||
}
|
||||
|
||||
function Add-RunResult {
|
||||
param($Run, [string]$Kind, [string]$Name, [string]$Status, [string]$Message)
|
||||
$result = [pscustomobject]@{ kind = $Kind; name = $Name; status = $Status; message = $Message }
|
||||
$Run.results.Add($result)
|
||||
"[$([DateTimeOffset]::UtcNow.ToString('o'))] $Kind $Name $Status $Message" | Add-Content -LiteralPath $Run.logPath -Encoding utf8
|
||||
return $result
|
||||
}
|
||||
|
||||
function Complete-Run {
|
||||
param($Run, $Paths, $State, [bool]$Succeeded)
|
||||
$Run | Add-Member -NotePropertyName completedAt -NotePropertyValue ([DateTimeOffset]::UtcNow.ToString('o')) -Force
|
||||
$Run | Add-Member -NotePropertyName succeeded -NotePropertyValue $Succeeded -Force
|
||||
$State.lastRun = [ordered]@{ id = $Run.id; command = $Run.command; revision = $Run.revision; completedAt = $Run.completedAt; succeeded = $Succeeded }
|
||||
Write-JsonAtomic -Path $Paths.State -Value $State
|
||||
}
|
||||
|
||||
Export-ModuleMember -Function Get-ConfigCentralPaths, Initialize-ConfigCentralData, Read-JsonState, Write-JsonAtomic, Enter-ApplyLock, Exit-ApplyLock, New-RunContext, Add-RunResult, Complete-Run
|
||||
Loading…
Reference in New Issue