Files
CollabTable/shared/scripts/sync-consumers.ps1
T
Gabriel20xx fdf415cc8b
Docker / Docker Build & Push (push) Successful in 3m15s
Sync shared snapshot from d1a02a8
2026-09-07 15:08:58 +02:00

388 lines
16 KiB
PowerShell

[CmdletBinding()]
param(
[string]$SourceRepository,
[switch]$Force,
[switch]$Commit,
[switch]$Push
)
$ErrorActionPreference = 'Stop'
if ($Push -and -not $Commit) {
throw 'The -Push switch requires -Commit so that only generated synchronization changes are pushed.'
}
function New-ConsumerProject {
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[string]$Destination = 'shared'
)
return [pscustomobject]@{ Path = $Path; Destination = $Destination }
}
# Destination defaults to 'shared' (the snapshot folder name most consumers
# use). The engine/media-backend family below mounts the same snapshot at
# 'engine' instead - historically a git submodule, converted to this same
# vendored-copy pattern for consistency and to drop the private-submodule
# checkout auth dependency in CI.
$consumerProjects = @(
New-ConsumerProject 'Original/MediaDesktop'
New-ConsumerProject 'Original/AutoCode'
New-ConsumerProject 'Original/SimpleCollection'
New-ConsumerProject 'Original/CollabTable'
New-ConsumerProject 'Original/GameStream'
New-ConsumerProject 'Original/SyncServer'
New-ConsumerProject 'Original/UnraidMonitor'
New-ConsumerProject 'Original/PubliSafe'
New-ConsumerProject 'Forks/Bitmagnet'
New-ConsumerProject 'Forks/Heretic'
New-ConsumerProject 'Original/InfiniteVideo'
New-ConsumerProject 'Forks/MegaBasterd'
New-ConsumerProject 'Forks/HordeWorker'
New-ConsumerProject 'Original/OutdoorGames'
New-ConsumerProject 'Original/KioskDisplay'
New-ConsumerProject 'Original/CraftStudio'
New-ConsumerProject 'Original/MediaViewer'
New-ConsumerProject 'Central/CarrierNode'
New-ConsumerProject 'Central/ContentScanner'
New-ConsumerProject 'Central/ModerationHub'
New-ConsumerProject 'Central/ProjectConfigurator'
New-ConsumerProject 'Central/AuthGuard'
)
function Invoke-GitText {
param(
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory,
[Parameter(Mandatory = $true)]
[string[]]$Arguments
)
$output = & git -C $WorkingDirectory @Arguments 2>&1
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
$diagnostics = @($output | ForEach-Object { [string]$_ } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
$blockingDiagnostics = @($diagnostics | Where-Object { $_ -notmatch '^\s*(warning|hint):' })
if ($blockingDiagnostics.Count -eq 0) {
$diagnostics | ForEach-Object { Write-Warning $_ }
}
else {
$details = $diagnostics -join [Environment]::NewLine
throw "git $($Arguments -join ' ') failed in '$WorkingDirectory'. $details"
}
}
return @($output | ForEach-Object { [string]$_ })
}
function Resolve-FullPath {
param(
[Parameter(Mandatory = $true)]
[string]$Path
)
return (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path
}
function Get-RelativePath {
param(
[Parameter(Mandatory = $true)]
[string]$BasePath,
[Parameter(Mandatory = $true)]
[string]$TargetPath
)
$base = (Resolve-FullPath $BasePath).TrimEnd('\') + '\'
$target = Resolve-FullPath $TargetPath
if (-not $target.StartsWith($base, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "'$TargetPath' is not inside '$BasePath'."
}
return $target.Substring($base.Length).Replace('\', '/')
}
function Write-Utf8NoBom {
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Content
)
$encoding = New-Object System.Text.UTF8Encoding($false)
$normalizedContent = $Content.Replace("`r`n", "`n").Replace("`r", "`n")
[System.IO.File]::WriteAllText($Path, $normalizedContent, $encoding)
}
function Convert-ToConsumerWebUiPackage {
param(
[Parameter(Mandatory = $true)]
[string]$PackagePath
)
$manifest = Get-Content -LiteralPath $PackagePath -Raw | ConvertFrom-Json
$manifest.files = @('src', 'README.md')
if ($null -ne $manifest.dependencies) {
$designTokensDependency = $manifest.dependencies.PSObject.Properties['@gabriel20xx/design-tokens']
if ($null -ne $designTokensDependency) {
$manifest.dependencies.PSObject.Properties.Remove('@gabriel20xx/design-tokens')
}
}
$manifest.svelte = './src/index.ts'
$manifest.types = './src/index.ts'
$rootExport = $manifest.exports.PSObject.Properties | Where-Object { $_.Name -eq '.' }
if ($null -ne $rootExport) {
$rootExport.Value.types = './src/index.ts'
$rootExport.Value.svelte = './src/index.ts'
$rootExport.Value.import = './src/index.ts'
}
$stylesExport = $manifest.exports.PSObject.Properties | Where-Object { $_.Name -eq './styles.css' }
if ($null -ne $stylesExport) {
$stylesExport.Value = './src/lib/styles.css'
}
$json = $manifest | ConvertTo-Json -Depth 20
Write-Utf8NoBom -Path $PackagePath -Content ($json + [Environment]::NewLine)
}
function Convert-ToConsumerWebUiSources {
param(
[Parameter(Mandatory = $true)]
[string]$WebUiRoot
)
$stylesPath = Join-Path $WebUiRoot 'src/lib/styles.css'
if (Test-Path -LiteralPath $stylesPath) {
$styles = Get-Content -LiteralPath $stylesPath -Raw
$styles = $styles.Replace("@import '@gabriel20xx/design-tokens/theme.css';", "@import '../../../design-tokens/theme.css';")
$styles = $styles.Replace('@import "@gabriel20xx/design-tokens/theme.css";', "@import '../../../design-tokens/theme.css';")
Write-Utf8NoBom -Path $stylesPath -Content $styles
}
$svelteConfigPath = Join-Path $WebUiRoot 'svelte.config.js'
if (Test-Path -LiteralPath $svelteConfigPath) {
Write-Utf8NoBom -Path $svelteConfigPath -Content "export default {};`n"
}
}
function Test-LocalSharedDependency {
param(
[Parameter(Mandatory = $true)]
$PackageManifest
)
$localPackageNames = @(
'@gabriel20xx/web-ui',
'@gabriel20xx/node-backend'
)
foreach ($sectionName in @('dependencies', 'devDependencies', 'optionalDependencies')) {
$sectionProperty = $PackageManifest.PSObject.Properties[$sectionName]
if ($null -eq $sectionProperty -or $null -eq $sectionProperty.Value) {
continue
}
foreach ($dependency in $sectionProperty.Value.PSObject.Properties) {
if ($dependency.Name -in $localPackageNames -and ([string]$dependency.Value).StartsWith('file:')) {
return $true
}
}
}
return $false
}
if ([string]::IsNullOrWhiteSpace($SourceRepository)) {
$scriptParent = Resolve-FullPath (Join-Path $PSScriptRoot '..')
$scriptParentGitRoot = (Invoke-GitText -WorkingDirectory $scriptParent -Arguments @('rev-parse', '--show-toplevel') | Select-Object -First 1).Trim()
$scriptParentGitRoot = Resolve-FullPath $scriptParentGitRoot
if ($scriptParentGitRoot -ieq $scriptParent) {
$SourceRepository = $scriptParent
}
else {
$workspaceRoot = Split-Path -Parent (Split-Path -Parent $scriptParentGitRoot)
$SourceRepository = Join-Path $workspaceRoot 'shared'
}
}
$sourceRoot = Resolve-FullPath $SourceRepository
$sourceRepositoryRoot = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--show-toplevel') | Select-Object -First 1).Trim()
$sourceRoot = Resolve-FullPath $sourceRepositoryRoot
# The workspace root is the ancestor directory that contains both 'Original'
# and 'Forks' (every consumer project lives under one of those). Walk up from
# the shared repo instead of assuming a fixed nesting depth, since shared/ has
# moved before (e.g. Web/shared -> Web/Central/shared) and may move again.
$workspaceRoot = Split-Path -Parent $sourceRoot
while ($workspaceRoot -and -not ((Test-Path -LiteralPath (Join-Path $workspaceRoot 'Original') -PathType Container) -and (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Forks') -PathType Container))) {
$parent = Split-Path -Parent $workspaceRoot
if (-not $parent -or $parent -eq $workspaceRoot) {
throw "Could not locate the workspace root (a directory containing both 'Original' and 'Forks') above $sourceRoot."
}
$workspaceRoot = $parent
}
$sourceCommit = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('rev-parse', '--short', 'HEAD') | Select-Object -First 1).Trim()
$sourceFiles = @(Invoke-GitText -WorkingDirectory $sourceRoot -Arguments @('ls-files') | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
$sourceFileSet = @{}
foreach ($sourceFile in $sourceFiles) {
$sourceFileSet[$sourceFile.Replace('\', '/')] = $true
}
Write-Host "Synchronizing $($sourceFiles.Count) tracked shared files from $sourceCommit."
$failures = New-Object 'System.Collections.Generic.List[string]'
foreach ($consumerProject in $consumerProjects) {
$relativeProject = $consumerProject.Path
$destination = $consumerProject.Destination
$projectRoot = Join-Path $workspaceRoot ($relativeProject -replace '/', '\')
if (-not (Test-Path -LiteralPath $projectRoot -PathType Container)) {
$failures.Add("${relativeProject}: project directory not found")
continue
}
try {
$projectRoot = Resolve-FullPath $projectRoot
$destinationRoot = Join-Path $projectRoot $destination
$isLegacyEligible = $destination -eq 'shared'
$legacyDirectoryName = ('Shared' + 'Code')
$projectDirectories = @(Get-ChildItem -LiteralPath $projectRoot -Directory -Force)
$destinationEntry = $projectDirectories | Where-Object { $_.Name -ceq $destination }
$legacyEntry = if ($isLegacyEligible) { $projectDirectories | Where-Object { $_.Name -ceq $legacyDirectoryName } } else { $null }
if ($null -ne $destinationEntry -and $null -ne $legacyEntry) {
throw "Both $destination and the legacy shared snapshot directory exist. Remove the legacy directory before synchronizing."
}
$dirtyDestination = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $destination))
$dirtyLegacy = if ($isLegacyEligible) { @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $legacyDirectoryName)) } else { @() }
if (($dirtyDestination.Count -gt 0 -or $dirtyLegacy.Count -gt 0) -and -not $Force) {
throw "$destination has local changes. Commit them or rerun with -Force."
}
if ($null -ne $legacyEntry) {
$temporaryRenamePath = Join-Path $projectRoot ('.shared-sync-rename-' + [Guid]::NewGuid().ToString('N'))
Move-Item -LiteralPath $legacyEntry.FullName -Destination $temporaryRenamePath
Move-Item -LiteralPath $temporaryRenamePath -Destination $destinationRoot
}
New-Item -ItemType Directory -Force -Path $destinationRoot | Out-Null
$existingDestinationFiles = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', $destination) | Where-Object { $_ -like "$destination/*" })
foreach ($existingDestinationFile in $existingDestinationFiles) {
$relativeDestinationFile = $existingDestinationFile.Substring("$destination/".Length).Replace('\', '/')
if (-not $sourceFileSet.ContainsKey($relativeDestinationFile)) {
$stalePath = Join-Path $destinationRoot ($relativeDestinationFile -replace '/', '\')
if (Test-Path -LiteralPath $stalePath -PathType Leaf) {
Remove-Item -LiteralPath $stalePath -Force
}
}
}
foreach ($sourceFile in $sourceFiles) {
$sourcePath = Join-Path $sourceRoot ($sourceFile -replace '/', '\')
$destinationPath = Join-Path $destinationRoot ($sourceFile -replace '/', '\')
$destinationDirectory = Split-Path -Parent $destinationPath
New-Item -ItemType Directory -Force -Path $destinationDirectory | Out-Null
Copy-Item -LiteralPath $sourcePath -Destination $destinationPath -Force
}
$webUiPackagePath = Join-Path $destinationRoot 'packages/web-ui/package.json'
if (Test-Path -LiteralPath $webUiPackagePath) {
Convert-ToConsumerWebUiPackage -PackagePath $webUiPackagePath
Convert-ToConsumerWebUiSources -WebUiRoot (Join-Path $destinationRoot 'packages/web-ui')
}
$lockFiles = @()
$sharedPrefix = ((Resolve-FullPath $destinationRoot).TrimEnd('\') + '\')
$packageFiles = @(Get-ChildItem -LiteralPath $projectRoot -Recurse -File -Filter 'package.json' -Force |
Where-Object {
$_.FullName -notlike "$sharedPrefix*" -and
$_.FullName -notmatch '\\node_modules\\'
})
foreach ($packageFile in $packageFiles) {
$packageManifest = Get-Content -LiteralPath $packageFile.FullName -Raw | ConvertFrom-Json
if (-not (Test-LocalSharedDependency -PackageManifest $packageManifest)) {
continue
}
$lockPath = Join-Path $packageFile.DirectoryName 'package-lock.json'
if (-not (Test-Path -LiteralPath $lockPath -PathType Leaf)) {
continue
}
$relativeLockPath = Get-RelativePath -BasePath $projectRoot -TargetPath $lockPath
$trackedLock = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', $relativeLockPath))
$shouldStageLock = $trackedLock.Count -gt 0
Write-Host " Updating $relativeProject/$(Get-RelativePath -BasePath $projectRoot -TargetPath $lockPath)"
Push-Location -LiteralPath $packageFile.DirectoryName
try {
& npm install --package-lock-only --ignore-scripts --prefer-offline
if ($LASTEXITCODE -ne 0) {
throw "npm install --package-lock-only failed with exit code $LASTEXITCODE."
}
}
finally {
Pop-Location
}
if ($shouldStageLock -and $lockFiles -notcontains $relativeLockPath) {
$lockFiles += $relativeLockPath
}
elseif (-not $shouldStageLock) {
Write-Host " Leaving untracked/ignored lockfile out of the generated commit: $relativeLockPath"
}
}
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $destination)
foreach ($lockFile in $lockFiles) {
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $lockFile)
}
$targetPaths = @($destination) + $lockFiles
$stagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($Commit -and $stagedChanges.Count -gt 0) {
$commitMessage = "Sync $destination snapshot from $sourceCommit"
$commitArguments = @('commit', '--only', '-m', $commitMessage, '--') + $targetPaths
$commitOutput = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments $commitArguments)
$commitOutput | ForEach-Object { Write-Host " $_" }
$remainingStagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($remainingStagedChanges.Count -gt 0) {
throw 'The generated synchronization changes remain staged after the commit.'
}
}
if ($Push) {
$pushOutput = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('push', 'origin', 'main'))
$pushOutput | ForEach-Object { Write-Host " $_" }
}
if ($stagedChanges.Count -gt 0) {
Write-Host "Synced $relativeProject."
}
else {
Write-Host "$relativeProject is already synchronized."
}
}
catch {
$message = "${relativeProject}: $($_.Exception.Message)"
$failures.Add($message)
Write-Warning $message
}
}
if ($failures.Count -gt 0) {
throw "shared synchronization failed for $($failures.Count) project(s): $($failures -join '; ')"
}
Write-Host 'shared synchronization completed.'