diff --git a/TASKS.md b/TASKS.md index c5d3be8..ea33754 100644 --- a/TASKS.md +++ b/TASKS.md @@ -29,10 +29,10 @@ Complete the core CLI and manual workflow before optional automation or a TUI. ## 3. Implement repository synchronization -- [ ] Persist local repository URL, branch, and selected machine outside Git. -- [ ] Implement fetch and commit resolution with actionable authentication and +- [x] Persist local repository URL, branch, and selected machine outside Git. +- [x] Implement fetch and commit resolution with actionable authentication and network errors; reuse Git credential handling. -- [ ] Detect local edits and refuse destructive updates. +- [x] Detect local edits and refuse destructive updates. - [ ] 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. diff --git a/src/Repository.psm1 b/src/Repository.psm1 new file mode 100644 index 0000000..20ee03e --- /dev/null +++ b/src/Repository.psm1 @@ -0,0 +1,81 @@ +Set-StrictMode -Version Latest + +function Invoke-Git { + param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string[]]$Arguments, [switch]$AllowFailure) + $outputPath = [System.IO.Path]::GetTempFileName() + $errorPath = [System.IO.Path]::GetTempFileName() + try { + $process = Start-Process -FilePath 'git.exe' -WorkingDirectory $RepositoryRoot -ArgumentList $Arguments -Wait -PassThru -NoNewWindow -RedirectStandardOutput $outputPath -RedirectStandardError $errorPath + $output = ((Get-Content -LiteralPath $outputPath -Raw -ErrorAction SilentlyContinue), (Get-Content -LiteralPath $errorPath -Raw -ErrorAction SilentlyContinue) -join [Environment]::NewLine).Trim() + if ($process.ExitCode -ne 0 -and -not $AllowFailure) { throw "git $($Arguments[0]) failed: $output" } + [pscustomobject]@{ exitCode = $process.ExitCode; output = $output } + } + finally { Remove-Item -LiteralPath $outputPath, $errorPath -Force -ErrorAction SilentlyContinue } +} + +function Get-RepositoryRevision { + param([Parameter(Mandatory)][string]$RepositoryRoot) + if (-not (Get-Command git.exe -ErrorAction SilentlyContinue) -and -not (Get-Command git -ErrorAction SilentlyContinue)) { return 'working-tree' } + try { (Invoke-Git -RepositoryRoot $RepositoryRoot -Arguments @('rev-parse', 'HEAD')).output.Trim() } + catch { 'working-tree' } +} + +function Test-RepositoryDirty { + param([Parameter(Mandatory)][string]$RepositoryRoot) + $status = Invoke-Git -RepositoryRoot $RepositoryRoot -Arguments @('status', '--porcelain=v1', '--untracked-files=all') + return -not [string]::IsNullOrWhiteSpace($status.output) +} + +function Resolve-RemoteRevision { + param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Settings) + if (-not $Settings.ContainsKey('branch') -or [string]::IsNullOrWhiteSpace([string]$Settings.branch)) { throw 'No repository branch is configured.' } + $branch = [string]$Settings.branch + if ($branch -notmatch '^[A-Za-z0-9._/-]+$' -or $branch.Contains('..')) { throw "Unsafe branch name '$branch'." } + if (Test-RepositoryDirty -RepositoryRoot $RepositoryRoot) { throw 'Repository has local changes; commit or remove them before sync.' } + try { [void](Invoke-Git -RepositoryRoot $RepositoryRoot -Arguments @('fetch', '--prune', 'origin', $branch)) } + catch { throw "Repository fetch failed. Check network access and Git credentials. $($_.Exception.Message)" } + $revision = (Invoke-Git -RepositoryRoot $RepositoryRoot -Arguments @('rev-parse', '--verify', "refs/remotes/origin/$branch^{commit}")).output.Trim() + if ($revision -notmatch '^[0-9a-f]{40,64}$') { throw "Git returned an invalid revision for origin/$branch." } + return $revision +} + +function New-RepositorySnapshot { + param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Revision, [Parameter(Mandatory)]$Paths) + if ($Revision -notmatch '^[0-9a-f]{40,64}$') { throw "Invalid snapshot revision '$Revision'." } + $snapshot = Join-Path $Paths.Snapshots $Revision + if (Test-Path -LiteralPath (Join-Path $snapshot 'cc.ps1') -PathType Leaf) { return $snapshot } + $temporary = "$snapshot.$([guid]::NewGuid().ToString('N')).tmp" + $archive = Join-Path $Paths.Snapshots "$Revision.$([guid]::NewGuid().ToString('N')).zip" + try { + [void](New-Item -ItemType Directory -Path $temporary -Force) + [void](Invoke-Git -RepositoryRoot $RepositoryRoot -Arguments @('archive', '--format=zip', "--output=$archive", $Revision)) + Expand-Archive -LiteralPath $archive -DestinationPath $temporary -Force + try { [System.IO.Directory]::Move($temporary, $snapshot) } + catch { if (-not (Test-Path -LiteralPath $snapshot)) { throw } } + return $snapshot + } + finally { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $temporary -Recurse -Force -ErrorAction SilentlyContinue + } +} + +function Save-ConfigCentralSettings { + param([Parameter(Mandatory)]$Paths, [Parameter(Mandatory)][string]$RepositoryUrl, [Parameter(Mandatory)][string]$Branch, [Parameter(Mandatory)][string]$Machine) + $settings = [ordered]@{ + repositoryUrl = $RepositoryUrl + branch = $Branch + machine = $Machine + checkout = (Get-Location).Path + userPaths = [ordered]@{ + APPDATA = $env:APPDATA + LOCALAPPDATA = $env:LOCALAPPDATA + USERPROFILE = $env:USERPROFILE + PROGRAMDATA = $env:PROGRAMDATA + } + } + Write-JsonAtomic -Path $Paths.Settings -Value $settings + return $settings +} + +Export-ModuleMember -Function Invoke-Git, Get-RepositoryRevision, Test-RepositoryDirty, Resolve-RemoteRevision, New-RepositorySnapshot, Save-ConfigCentralSettings