[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.' } $consumerProjects = @( 'Original/AutoCode', 'Original/SimpleCollection', 'Original/CollabTable', 'Original/GameStream', 'Original/SyncServer', 'Original/UnraidMonitor', 'Original/PubliSafe', 'Original/MediaCollection', 'Forks/Bitmagnet', 'Forks/Heretic', 'Original/InfiniteVideo', 'Forks/MegaBasterd', 'Forks/HordeWorker', 'Original/OutdoorGames' ) 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 $workspaceRoot = Split-Path -Parent $sourceRoot $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 ($relativeProject in $consumerProjects) { $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 'shared' $legacyDirectoryName = ('Shared' + 'Code') $projectDirectories = @(Get-ChildItem -LiteralPath $projectRoot -Directory -Force) $destinationEntry = $projectDirectories | Where-Object { $_.Name -ceq 'shared' } $legacyEntry = $projectDirectories | Where-Object { $_.Name -ceq $legacyDirectoryName } if ($null -ne $destinationEntry -and $null -ne $legacyEntry) { throw "Both shared and the legacy shared snapshot directory exist. Remove the legacy directory before synchronizing." } $dirtyshared = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', 'shared')) $dirtyLegacy = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $legacyDirectoryName)) if (($dirtyshared.Count -gt 0 -or $dirtyLegacy.Count -gt 0) -and -not $Force) { throw "shared 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 $existingSharedFiles = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', 'shared') | Where-Object { $_ -like 'shared/*' }) foreach ($existingSharedFile in $existingSharedFiles) { $relativeSharedFile = $existingSharedFile.Substring('shared/'.Length).Replace('\', '/') if (-not $sourceFileSet.ContainsKey($relativeSharedFile)) { $stalePath = Join-Path $destinationRoot ($relativeSharedFile -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', '--', 'shared') foreach ($lockFile in $lockFiles) { $null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $lockFile) } $targetPaths = @('shared') + $lockFiles $stagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths)) if ($Commit -and $stagedChanges.Count -gt 0) { $commitMessage = "Sync shared 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.'