Files
CollabTable/SharedCode/scripts/sync-consumers.ps1
T

307 lines
11 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.'
}
$consumerProjects = @(
'Original/SimpleCollection',
'Original/CollabTable',
'Original/GameStream',
'Original/SyncServer',
'Original/UnraidMonitor',
'Original/PubliSafe',
'Original/MediaCollection',
'Forks/Bitmagnet',
'Forks/Heretic',
'Original/InfiniteVideo',
'Forks/MegaBasterd',
'Forks/HordeWorkerReGen',
'Original/OutdoorGames'
)
function Invoke-GitText {
param(
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory,
[Parameter(Mandatory = $true)]
[string[]]$Arguments
)
$output = @(& git -C $WorkingDirectory @Arguments 2>&1)
if ($LASTEXITCODE -ne 0) {
$details = ($output | ForEach-Object { [string]$_ }) -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)
[System.IO.File]::WriteAllText($Path, $Content, $encoding)
}
function Convert-ToConsumerWebUiPackage {
param(
[Parameter(Mandatory = $true)]
[string]$PackagePath
)
$manifest = Get-Content -LiteralPath $PackagePath -Raw | ConvertFrom-Json
$manifest.files = @('src', 'README.md')
$manifest.dependencies = [pscustomobject]@{}
$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';")
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 '..')
if ((Split-Path -Leaf $scriptParent) -ieq 'shared') {
$SourceRepository = $scriptParent
}
else {
$consumerRoot = Resolve-FullPath (Join-Path $PSScriptRoot '..\..')
$SourceRepository = Join-Path $consumerRoot '..\..\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 SharedCode 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 'SharedCode'
$dirtySharedCode = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', 'SharedCode'))
if ($dirtySharedCode.Count -gt 0 -and -not $Force) {
throw "SharedCode has local changes. Commit them or rerun with -Force."
}
New-Item -ItemType Directory -Force -Path $destinationRoot | Out-Null
$existingSharedFiles = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('ls-files', '--', 'SharedCode') | Where-Object { $_ -like 'SharedCode/*' })
foreach ($existingSharedFile in $existingSharedFiles) {
$relativeSharedFile = $existingSharedFile.Substring('SharedCode/'.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 = @()
$sharedCodePrefix = ((Resolve-FullPath $destinationRoot).TrimEnd('\') + '\')
$packageFiles = @(Get-ChildItem -LiteralPath $projectRoot -Recurse -File -Filter 'package.json' -Force |
Where-Object {
$_.FullName -notlike "$sharedCodePrefix*" -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
}
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
}
$relativeLockPath = Get-RelativePath -BasePath $projectRoot -TargetPath $lockPath
if ($lockFiles -notcontains $relativeLockPath) {
$lockFiles += $relativeLockPath
}
}
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', 'SharedCode')
foreach ($lockFile in $lockFiles) {
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $lockFile)
}
$targetPaths = @('SharedCode') + $lockFiles
$stagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($Commit -and $stagedChanges.Count -gt 0) {
$commitMessage = "Sync SharedCode snapshot from $sourceCommit"
$commitArguments = @('commit', '--only', '-m', $commitMessage, '--') + $targetPaths
$commitOutput = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments $commitArguments)
$commitOutput | ForEach-Object { Write-Host " $_" }
}
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 "SharedCode synchronization failed for $($failures.Count) project(s): $($failures -join '; ')"
}
Write-Host 'SharedCode synchronization completed.'