Wire CLI planning and apply workflow
This commit is contained in:
parent
48bb29ef44
commit
075fd9ffd1
18
TASKS.md
18
TASKS.md
|
|
@ -20,11 +20,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.
|
||||
- [x] Add `cc.ps1`, module loading, and the `cc` launcher.
|
||||
- [x] Implement manifest loading, validation, and effective machine configuration.
|
||||
- [ ] Implement `doctor` for Windows/PowerShell, WinGet, Git, repository access,
|
||||
- [x] Implement `doctor` for Windows/PowerShell, WinGet, Git, repository access,
|
||||
package sources, and required permissions.
|
||||
- [ ] Implement a shared operation plan consumed by `plan` and `apply`.
|
||||
- [x] Implement a shared operation plan consumed by `plan` and `apply`.
|
||||
- [x] Add per-item logging, run summaries, atomic state writes, and a run lock.
|
||||
|
||||
## 3. Implement repository synchronization
|
||||
|
|
@ -33,9 +33,9 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
|
|||
- [x] Implement fetch and commit resolution with actionable authentication and
|
||||
network errors; reuse Git credential handling.
|
||||
- [x] Detect local edits and refuse destructive updates.
|
||||
- [ ] Stage immutable commit snapshots and hand off execution without replacing
|
||||
- [x] Stage immutable commit snapshots and hand off execution without replacing
|
||||
running scripts; record the revision used by each run.
|
||||
- [ ] Implement `apply` without a fetch and `sync` as fetch followed by apply.
|
||||
- [x] Implement `apply` without a fetch and `sync` as fetch followed by apply.
|
||||
|
||||
## 4. Implement config deployment
|
||||
|
||||
|
|
@ -45,8 +45,8 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
|
|||
after successful writes.
|
||||
- [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.
|
||||
- [x] Add `sync --configs-only` and config backup restoration.
|
||||
- [x] Implement `status` for config drift, conflicts, and last applied revision.
|
||||
|
||||
## 5. Implement software management
|
||||
|
||||
|
|
@ -59,7 +59,7 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
|
|||
packages whose installed versions cannot be determined.
|
||||
- [x] Execute installs sequentially and interpret WinGet results, including
|
||||
already-satisfied operations and reboot requirements.
|
||||
- [ ] Preserve installer diagnostics and continue independent work after a failure;
|
||||
- [x] Preserve installer diagnostics and continue independent work after a failure;
|
||||
skip dependent config operations and report them clearly.
|
||||
|
||||
## 6. Implement elevation and first-machine setup
|
||||
|
|
@ -94,7 +94,7 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
|
|||
|
||||
## Later, only when useful
|
||||
|
||||
- [ ] Add an optional numbered terminal menu using existing CLI commands.
|
||||
- [x] Add an optional numbered terminal menu using existing CLI commands.
|
||||
- [ ] 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.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
@echo off
|
||||
pwsh.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0cc.ps1" %*
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'restore', 'menu')][string]$Command = 'menu',
|
||||
[string]$Machine,
|
||||
[string]$Config,
|
||||
[switch]$ConfigsOnly,
|
||||
[switch]$ForceConfigs,
|
||||
[switch]$Json,
|
||||
[string]$DataRoot,
|
||||
[string]$RepositoryRoot = $PSScriptRoot,
|
||||
[switch]$FromSnapshot,
|
||||
[string]$Revision
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Configs', 'Elevation', 'Core')) {
|
||||
$path = Join-Path $PSScriptRoot "src/$module.psm1"
|
||||
if (Test-Path -LiteralPath $path) { Import-Module $path -Force }
|
||||
}
|
||||
|
||||
try {
|
||||
$paths = Get-ConfigCentralPaths -DataRoot $DataRoot
|
||||
Initialize-ConfigCentralData $paths
|
||||
$settings = Read-JsonState -Path $paths.Settings -Default ([ordered]@{})
|
||||
if ([string]::IsNullOrWhiteSpace($Machine) -and $settings.ContainsKey('machine')) { $Machine = [string]$settings.machine }
|
||||
if ($Command -ne 'doctor' -and $Command -ne 'menu' -and [string]::IsNullOrWhiteSpace($Machine)) {
|
||||
throw 'No machine selected. Pass -Machine or run bootstrap.ps1.'
|
||||
}
|
||||
|
||||
if ($Command -eq 'menu') {
|
||||
Show-ConfigCentralMenu -Machine $Machine -DataRoot $DataRoot -RepositoryRoot $RepositoryRoot
|
||||
exit 0
|
||||
}
|
||||
$result = Invoke-ConfigCentral -Command $Command -Machine $Machine -Config $Config -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs -Paths $paths -RepositoryRoot $RepositoryRoot -FromSnapshot:$FromSnapshot -Revision $Revision
|
||||
if ($Json) { $result | ConvertTo-Json -Depth 32 }
|
||||
else { Write-ConfigCentralResult $result }
|
||||
exit ([int]$result.exitCode)
|
||||
}
|
||||
catch {
|
||||
$errorResult = [ordered]@{ command = $Command; succeeded = $false; exitCode = 2; error = $_.Exception.Message }
|
||||
if ($Json) { $errorResult | ConvertTo-Json -Depth 8 } else { Write-Error $errorResult.error }
|
||||
exit 2
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
Set-StrictMode -Version Latest
|
||||
|
||||
function New-BaseResult {
|
||||
param([string]$Command)
|
||||
[ordered]@{ command = $Command; succeeded = $true; exitCode = 0; revision = $null; operations = @(); warnings = @() }
|
||||
}
|
||||
|
||||
function Get-OperationPlan {
|
||||
param([string]$Machine, [string]$RepositoryRoot, $Paths, [switch]$ConfigsOnly)
|
||||
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
|
||||
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{ schemaVersion = 1; configs = [ordered]@{} })
|
||||
if (-not $state.ContainsKey('configs')) { $state.configs = [ordered]@{} }
|
||||
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
|
||||
$packagePlan = @()
|
||||
if (-not $ConfigsOnly) {
|
||||
$inventory = Get-WingetInventory
|
||||
$packagePlan = @(Get-PackagePlan -Packages $effective.packages -Inventory $inventory)
|
||||
}
|
||||
$configPlan = @(Get-ConfigPlan -Configs $effective.configs -RepositoryRoot $RepositoryRoot -State $state -Settings $settings)
|
||||
[pscustomobject]@{ effective = $effective; packages = $packagePlan; configs = $configPlan; state = $state; settings = $settings }
|
||||
}
|
||||
|
||||
function Invoke-Doctor {
|
||||
param([string]$Machine, [string]$RepositoryRoot, $Paths)
|
||||
$checks = [System.Collections.Generic.List[object]]::new()
|
||||
function Add-Check([string]$Name, [bool]$Passed, [string]$Message, [bool]$Required = $true) {
|
||||
$checks.Add([pscustomobject]@{ name = $Name; passed = $Passed; required = $Required; message = $Message })
|
||||
}
|
||||
Add-Check 'Windows' ($IsWindows) $(if ($IsWindows) { [Environment]::OSVersion.VersionString } else { 'Config Central applies only on Windows.' })
|
||||
Add-Check 'PowerShell' ($PSVersionTable.PSVersion.Major -ge 7) "PowerShell $($PSVersionTable.PSVersion)"
|
||||
Add-Check 'Git' ([bool](Get-Command git.exe -ErrorAction SilentlyContinue)) $(if (Get-Command git.exe -ErrorAction SilentlyContinue) { (& git.exe --version) -join ' ' } else { 'git.exe is missing.' })
|
||||
Add-Check 'WinGet' ([bool](Get-Command winget.exe -ErrorAction SilentlyContinue)) $(if (Get-Command winget.exe -ErrorAction SilentlyContinue) { (& winget.exe --version) -join ' ' } else { 'winget.exe is missing.' })
|
||||
Add-Check 'Repository' (Test-Path -LiteralPath (Join-Path $RepositoryRoot 'schemas/profile.schema.json')) $RepositoryRoot
|
||||
try {
|
||||
Initialize-ConfigCentralData $Paths
|
||||
$probe = Join-Path $Paths.Root ".write-probe-$PID"
|
||||
[System.IO.File]::WriteAllText($probe, 'ok'); Remove-Item -LiteralPath $probe -Force
|
||||
Add-Check 'Data directory' $true $Paths.Root
|
||||
}
|
||||
catch { Add-Check 'Data directory' $false $_.Exception.Message }
|
||||
if (Get-Command winget.exe -ErrorAction SilentlyContinue) {
|
||||
$sourceOutput = & winget.exe source list --disable-interactivity --accept-source-agreements 2>&1
|
||||
Add-Check 'WinGet sources' ($LASTEXITCODE -eq 0) ($sourceOutput -join [Environment]::NewLine)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($Machine)) {
|
||||
try { [void](Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine); Add-Check 'Machine manifest' $true $Machine }
|
||||
catch { Add-Check 'Machine manifest' $false $_.Exception.Message }
|
||||
}
|
||||
$failed = @($checks | Where-Object { $_.required -and -not $_.passed })
|
||||
$result = New-BaseResult 'doctor'
|
||||
$result.operations = @($checks)
|
||||
if ($failed.Count -gt 0) { $result.succeeded = $false; $result.exitCode = 3 }
|
||||
return [pscustomobject]$result
|
||||
}
|
||||
|
||||
function Invoke-ApplyPlan {
|
||||
param($Plan, [string]$Machine, [string]$RepositoryRoot, $Paths, [string]$Revision, [switch]$ForceConfigs)
|
||||
$result = New-BaseResult 'apply'
|
||||
$result.revision = $Revision
|
||||
$lock = $null
|
||||
try { $lock = Enter-ApplyLock -Paths $Paths }
|
||||
catch { $result.succeeded = $false; $result.exitCode = 10; $result.warnings = @($_.Exception.Message); return [pscustomobject]$result }
|
||||
|
||||
$run = New-RunContext -Paths $Paths -Command 'apply' -Revision $Revision
|
||||
$failedPackages = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
|
||||
$rebootRequired = $false
|
||||
try {
|
||||
$userOperations = @($Plan.packages | Where-Object { -not $_.package.PSObject.Properties['scope'] -or $_.package.scope -eq 'user' })
|
||||
$machineOperations = @($Plan.packages | Where-Object { $_.package.PSObject.Properties['scope'] -and $_.package.scope -eq 'machine' })
|
||||
$packageResults = [System.Collections.Generic.List[object]]::new()
|
||||
foreach ($operation in $userOperations) { $packageResults.Add((Invoke-PackageOperation -Operation $operation -LogPath $run.logPath)) }
|
||||
try {
|
||||
foreach ($item in @(Invoke-ElevatedPackageBatch -Operations $machineOperations -RepositoryRoot $RepositoryRoot -Paths $Paths -LogPath $run.logPath)) { $packageResults.Add($item) }
|
||||
}
|
||||
catch {
|
||||
foreach ($operation in $machineOperations) { $packageResults.Add([pscustomobject]@{ name = $operation.name; status = 'Failed'; rebootRequired = $false; message = $_.Exception.Message }) }
|
||||
}
|
||||
foreach ($packageResult in $packageResults) {
|
||||
[void](Add-RunResult -Run $run -Kind package -Name $packageResult.name -Status $packageResult.status -Message $packageResult.message)
|
||||
if ($packageResult.status -eq 'Failed') { [void]$failedPackages.Add($packageResult.name) }
|
||||
if ($packageResult.PSObject.Properties['rebootRequired'] -and $packageResult.rebootRequired) { $rebootRequired = $true }
|
||||
}
|
||||
|
||||
foreach ($operation in $Plan.configs) {
|
||||
if ($operation.requiresPackage -and $failedPackages.Contains($operation.requiresPackage)) {
|
||||
[void](Add-RunResult -Run $run -Kind config -Name $operation.name -Status Skipped -Message "Required package '$($operation.requiresPackage)' failed")
|
||||
continue
|
||||
}
|
||||
$configResult = Invoke-ConfigOperation -Operation $operation -Paths $Paths -State $Plan.state -Force:$ForceConfigs
|
||||
[void](Add-RunResult -Run $run -Kind config -Name $configResult.name -Status $configResult.status -Message $configResult.message)
|
||||
}
|
||||
$result.operations = @($run.results)
|
||||
$failures = @($run.results | Where-Object status -in @('Failed', 'Conflict', 'Skipped'))
|
||||
$result.succeeded = $failures.Count -eq 0
|
||||
$result.exitCode = if (-not $result.succeeded) { 5 } elseif ($rebootRequired) { 6 } else { 0 }
|
||||
$Plan.state.lastAppliedRevision = $Revision
|
||||
Complete-Run -Run $run -Paths $Paths -State $Plan.state -Succeeded $result.succeeded
|
||||
return [pscustomobject]$result
|
||||
}
|
||||
finally { Exit-ApplyLock -Lock $lock -Paths $Paths }
|
||||
}
|
||||
|
||||
function Invoke-SnapshotApply {
|
||||
param([string]$Snapshot, [string]$Machine, $Paths, [string]$Revision, [switch]$ConfigsOnly, [switch]$ForceConfigs)
|
||||
$arguments = @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $Snapshot 'cc.ps1'), 'apply', '-Machine', $Machine, '-DataRoot', $Paths.Root, '-RepositoryRoot', $Snapshot, '-Revision', $Revision, '-FromSnapshot', '-Json')
|
||||
if ($ConfigsOnly) { $arguments += '-ConfigsOnly' }
|
||||
if ($ForceConfigs) { $arguments += '-ForceConfigs' }
|
||||
$text = & pwsh.exe @arguments
|
||||
$exitCode = $LASTEXITCODE
|
||||
try { $child = ($text -join [Environment]::NewLine) | ConvertFrom-Json -Depth 32 }
|
||||
catch { throw "Snapshot apply returned invalid output (exit $exitCode): $($text -join [Environment]::NewLine)" }
|
||||
return $child
|
||||
}
|
||||
|
||||
function Invoke-ConfigCentral {
|
||||
param(
|
||||
[string]$Command, [string]$Machine, [string]$Config, [switch]$ConfigsOnly,
|
||||
[switch]$ForceConfigs, $Paths, [string]$RepositoryRoot, [switch]$FromSnapshot,
|
||||
[string]$Revision
|
||||
)
|
||||
if ($Command -eq 'doctor') { return Invoke-Doctor -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths }
|
||||
if ($Command -eq 'restore') {
|
||||
if ([string]::IsNullOrWhiteSpace($Config)) { throw 'restore requires -Config NAME.' }
|
||||
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{})
|
||||
$restore = Restore-ConfigBackup -Name $Config -Paths $Paths -State $state
|
||||
$result = New-BaseResult 'restore'; $result.operations = @($restore); return [pscustomobject]$result
|
||||
}
|
||||
if ($Command -eq 'sync') {
|
||||
if ($FromSnapshot) { throw 'Nested sync from a snapshot is not allowed.' }
|
||||
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
|
||||
$remoteRevision = Resolve-RemoteRevision -RepositoryRoot $RepositoryRoot -Settings $settings
|
||||
$snapshot = New-RepositorySnapshot -RepositoryRoot $RepositoryRoot -Revision $remoteRevision -Paths $Paths
|
||||
return Invoke-SnapshotApply -Snapshot $snapshot -Machine $Machine -Paths $Paths -Revision $remoteRevision -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot }
|
||||
$plan = Get-OperationPlan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -ConfigsOnly:$ConfigsOnly
|
||||
if ($Command -eq 'apply') { return Invoke-ApplyPlan -Plan $plan -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths -Revision $Revision -ForceConfigs:$ForceConfigs }
|
||||
|
||||
$result = New-BaseResult $Command
|
||||
$result.revision = $Revision
|
||||
$result.operations = @($plan.packages) + @($plan.configs)
|
||||
if ($Command -eq 'status') {
|
||||
$drift = @($result.operations | Where-Object action -notin @('None', 'Warning'))
|
||||
if ($drift.Count -gt 0) { $result.succeeded = $false; $result.exitCode = 4 }
|
||||
$result | Add-Member -NotePropertyName lastRun -NotePropertyValue $(if ($plan.state.ContainsKey('lastRun')) { $plan.state.lastRun } else { $null })
|
||||
}
|
||||
return [pscustomobject]$result
|
||||
}
|
||||
|
||||
function Write-ConfigCentralResult {
|
||||
param($Result)
|
||||
Write-Host "Config Central: $($Result.command)"
|
||||
if ($Result.revision) { Write-Host "Revision: $($Result.revision)" }
|
||||
foreach ($operation in @($Result.operations)) {
|
||||
$state = if ($operation.PSObject.Properties['action']) { $operation.action } elseif ($operation.PSObject.Properties['status']) { $operation.status } elseif ($operation.PSObject.Properties['passed']) { if ($operation.passed) { 'OK' } else { 'FAIL' } } else { '-' }
|
||||
$message = if ($operation.PSObject.Properties['reason']) { $operation.reason } else { $operation.message }
|
||||
Write-Host ("{0,-10} {1,-24} {2}" -f $state, $operation.name, $message)
|
||||
}
|
||||
foreach ($warning in @($Result.warnings)) { Write-Warning $warning }
|
||||
}
|
||||
|
||||
function Show-ConfigCentralMenu {
|
||||
param([string]$Machine, [string]$DataRoot, [string]$RepositoryRoot)
|
||||
Write-Host 'Config Central'
|
||||
Write-Host '1. Plan 2. Sync 3. Status 4. Doctor Q. Quit'
|
||||
$choice = Read-Host 'Select'
|
||||
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
|
||||
$arguments = @($command, '-RepositoryRoot', $RepositoryRoot)
|
||||
if ($Machine) { $arguments += @('-Machine', $Machine) }
|
||||
if ($DataRoot) { $arguments += @('-DataRoot', $DataRoot) }
|
||||
& (Join-Path $RepositoryRoot 'cc.ps1') @arguments
|
||||
}
|
||||
|
||||
Export-ModuleMember -Function Get-OperationPlan, Invoke-ConfigCentral, Write-ConfigCentralResult, Show-ConfigCentralMenu
|
||||
Loading…
Reference in New Issue