Files
CollabTable/shared/scripts/sync-consumers.ps1
T
Gabriel20xx 08ec03b6ec
Security / Secrets (gitleaks) (push) Successful in 57s
Security / Code (Semgrep) (push) Successful in 1m30s
Security / Dependencies (Trivy) (push) Successful in 1m16s
Docker / Docker Build & Push (push) Successful in 5m46s
feat: discover shared sync consumers dynamically
- Scan workspace repositories for vendored snapshots
- Verify tag suggestions count only library media
2026-11-15 13:18:42 +01:00

466 lines
19 KiB
PowerShell

<#
.SYNOPSIS
Copies this shared repository's tracked files into every consumer project's vendored snapshot.
.DESCRIPTION
Consumers are found by scanning the workspace, so the folder names do not matter. A consumer is a
git repository, at most three folders below the workspace root, that has a 'shared' folder (or the
legacy snapshot folder). The workspace root defaults to the folder that contains this repository.
Without -Commit the changes are only staged in each consumer. -Commit commits them, and -Push pushes
each committed consumer's main branch.
.PARAMETER Consumers
Consumer paths relative to the workspace root, for example 'Central/ProjectConfigurator'.
.PARAMETER ConsumersFile
A JSON file of the form {"consumers": ["Central/ProjectConfigurator", ...]}.
#>
[CmdletBinding()]
param(
[string]$SourceRepository,
[string]$WorkspaceRoot,
[string[]]$Consumers,
[string]$ConsumersFile,
[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.'
}
if ($Consumers -and $ConsumersFile) {
throw 'Pass either -Consumers or -ConsumersFile, not both.'
}
# The snapshot folder every consumer vendors, and the name older consumers used before it was renamed.
$snapshotFolder = 'shared'
$legacySnapshotFolder = ('Shared' + 'Code')
# How many folders below the workspace root a consumer may sit (Central/ProjectConfigurator is two).
$maxConsumerDepth = 3
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
}
# Joins a relative path written with '/' onto a base path, using the platform's separator.
function Join-RelativePath {
param(
[Parameter(Mandatory = $true)]
[string]$BasePath,
[Parameter(Mandatory = $true)]
[string]$RelativePath
)
return [IO.Path]::Combine($BasePath, $RelativePath.Replace('/', [IO.Path]::DirectorySeparatorChar))
}
function Get-RelativePath {
param(
[Parameter(Mandatory = $true)]
[string]$BasePath,
[Parameter(Mandatory = $true)]
[string]$TargetPath
)
$separator = [IO.Path]::DirectorySeparatorChar
$base = (Resolve-FullPath $BasePath).TrimEnd($separator) + $separator
$target = Resolve-FullPath $TargetPath
if (-not $target.StartsWith($base, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "'$TargetPath' is not inside '$BasePath'."
}
return $target.Substring($base.Length).Replace($separator, '/')
}
# Lists consumers as paths relative to $Root. Repositories are not searched inside, and the source
# repository is skipped.
function Find-ConsumerProjects {
param(
[Parameter(Mandatory = $true)]
[string]$Root,
[Parameter(Mandatory = $true)]
[string]$SourceRoot
)
$found = New-Object 'System.Collections.Generic.List[string]'
$pending = New-Object 'System.Collections.Generic.Queue[object]'
$pending.Enqueue([pscustomobject]@{ Path = $Root; Depth = 0 })
while ($pending.Count -gt 0) {
$current = $pending.Dequeue()
$children = @(Get-ChildItem -LiteralPath $current.Path -Directory -Force -ErrorAction SilentlyContinue)
foreach ($child in $children) {
if ($child.Name.StartsWith('.') -or $child.Name -eq 'node_modules') {
continue
}
if ($child.FullName -ieq $SourceRoot) {
continue
}
if (Test-Path -LiteralPath (Join-Path $child.FullName '.git')) {
$hasSnapshot = (Test-Path -LiteralPath (Join-RelativePath $child.FullName $snapshotFolder) -PathType Container) -or
(Test-Path -LiteralPath (Join-RelativePath $child.FullName $legacySnapshotFolder) -PathType Container)
if ($hasSnapshot) {
$found.Add((Get-RelativePath -BasePath $Root -TargetPath $child.FullName))
}
continue
}
if ($current.Depth + 1 -lt $maxConsumerDepth) {
$pending.Enqueue([pscustomobject]@{ Path = $child.FullName; Depth = $current.Depth + 1 })
}
}
}
return @($found | Sort-Object)
}
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-RelativePath $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-RelativePath $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
}
# The source must be the root of its own git repository. A consumer's snapshot is copied from this
# repository and has no .git folder, so running the script from inside a snapshot fails here.
if ([string]::IsNullOrWhiteSpace($SourceRepository)) {
$SourceRepository = Join-Path $PSScriptRoot '..'
}
$sourceRoot = Resolve-FullPath $SourceRepository
if (-not (Test-Path -LiteralPath (Join-Path $sourceRoot '.git'))) {
throw "'$sourceRoot' is not the root of a git repository. Pass -SourceRepository with the root of the shared repository."
}
# By default the workspace is the folder that holds the shared repository.
if ([string]::IsNullOrWhiteSpace($WorkspaceRoot)) {
$WorkspaceRoot = Split-Path -Parent $sourceRoot
}
$workspaceRoot = Resolve-FullPath $WorkspaceRoot
$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
}
$discoveredConsumers = @(Find-ConsumerProjects -Root $workspaceRoot -SourceRoot $sourceRoot)
if ($discoveredConsumers.Count -eq 0) {
throw "No consumer repositories with a '$snapshotFolder' folder were found under '$workspaceRoot' (searched $maxConsumerDepth folders deep)."
}
$requestedConsumers = $null
if ($ConsumersFile) {
$targetFile = Get-Content -LiteralPath $ConsumersFile -Raw | ConvertFrom-Json
if ($null -eq $targetFile.consumers) {
throw "'$ConsumersFile' has no 'consumers' array."
}
$requestedConsumers = @($targetFile.consumers)
}
elseif ($Consumers) {
$requestedConsumers = @($Consumers)
}
$selectedConsumers = $discoveredConsumers
if ($null -ne $requestedConsumers) {
$requestedConsumers = @($requestedConsumers | ForEach-Object { ([string]$_).Replace('\', '/').Trim('/') })
$unknownConsumers = @($requestedConsumers | Where-Object { $discoveredConsumers -notcontains $_ })
if ($unknownConsumers.Count -gt 0) {
throw "Unknown consumer(s): $($unknownConsumers -join ', '). Found: $($discoveredConsumers -join ', ')."
}
$selectedConsumers = @($discoveredConsumers | Where-Object { $requestedConsumers -contains $_ })
if ($selectedConsumers.Count -eq 0) {
throw 'No consumers selected; nothing to synchronize.'
}
}
Write-Host "Workspace: $workspaceRoot"
Write-Host "Synchronizing $($sourceFiles.Count) tracked shared files from $sourceCommit into $($selectedConsumers.Count) consumer(s):"
$selectedConsumers | ForEach-Object { Write-Host " $_" }
$failures = New-Object 'System.Collections.Generic.List[string]'
$changedConsumers = New-Object 'System.Collections.Generic.List[string]'
$unchangedConsumers = New-Object 'System.Collections.Generic.List[string]'
foreach ($relativeProject in $selectedConsumers) {
try {
$projectRoot = Resolve-FullPath (Join-RelativePath $workspaceRoot $relativeProject)
$destinationRoot = Join-RelativePath $projectRoot $snapshotFolder
$projectDirectories = @(Get-ChildItem -LiteralPath $projectRoot -Directory -Force)
$destinationEntry = $projectDirectories | Where-Object { $_.Name -ceq $snapshotFolder }
$legacyEntry = $projectDirectories | Where-Object { $_.Name -ceq $legacySnapshotFolder }
if ($null -ne $destinationEntry -and $null -ne $legacyEntry) {
throw "Both $snapshotFolder and the legacy snapshot directory exist. Remove the legacy directory before synchronizing."
}
$dirtyDestination = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $snapshotFolder))
$dirtyLegacy = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('status', '--porcelain', '--', $legacySnapshotFolder))
$hasLocalChanges = $dirtyDestination.Count -gt 0 -or $dirtyLegacy.Count -gt 0
if ($hasLocalChanges -and -not $Force) {
throw "$snapshotFolder has local changes. Commit them or rerun with -Force."
}
if ($hasLocalChanges) {
# -Force replaces the snapshot, so keep a copy of what it replaces first.
$backupRoot = Join-Path ([IO.Path]::GetTempPath()) ('shared-sync-backup-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Force -Path $backupRoot | Out-Null
foreach ($existingEntry in @($destinationEntry, $legacyEntry) | Where-Object { $null -ne $_ }) {
Copy-Item -LiteralPath $existingEntry.FullName -Destination (Join-Path $backupRoot $existingEntry.Name) -Recurse -Force
}
Write-Host " Backed up the local $snapshotFolder changes in $relativeProject to $backupRoot before overwriting."
}
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', '--', $snapshotFolder) |
Where-Object { $_.StartsWith("$snapshotFolder/", [System.StringComparison]::Ordinal) })
foreach ($existingDestinationFile in $existingDestinationFiles) {
$relativeDestinationFile = $existingDestinationFile.Substring($snapshotFolder.Length + 1).Replace('\', '/')
if (-not $sourceFileSet.ContainsKey($relativeDestinationFile)) {
$stalePath = Join-RelativePath $destinationRoot $relativeDestinationFile
if (Test-Path -LiteralPath $stalePath -PathType Leaf) {
Remove-Item -LiteralPath $stalePath -Force
}
}
}
foreach ($sourceFile in $sourceFiles) {
$sourcePath = Join-RelativePath $sourceRoot $sourceFile
$destinationPath = Join-RelativePath $destinationRoot $sourceFile
$destinationDirectory = Split-Path -Parent $destinationPath
New-Item -ItemType Directory -Force -Path $destinationDirectory | Out-Null
Copy-Item -LiteralPath $sourcePath -Destination $destinationPath -Force
}
$webUiPackagePath = Join-RelativePath $destinationRoot 'packages/web-ui/package.json'
if (Test-Path -LiteralPath $webUiPackagePath) {
Convert-ToConsumerWebUiPackage -PackagePath $webUiPackagePath
Convert-ToConsumerWebUiSources -WebUiRoot (Join-RelativePath $destinationRoot 'packages/web-ui')
}
$lockFiles = @()
$separator = [IO.Path]::DirectorySeparatorChar
$sharedPrefix = (Resolve-FullPath $destinationRoot).TrimEnd($separator) + $separator
$packageFiles = @(Get-ChildItem -LiteralPath $projectRoot -Recurse -File -Filter 'package.json' -Force |
Where-Object {
-not $_.FullName.StartsWith($sharedPrefix, [System.StringComparison]::OrdinalIgnoreCase) -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/$relativeLockPath"
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', '--', $snapshotFolder)
foreach ($lockFile in $lockFiles) {
$null = Invoke-GitText -WorkingDirectory $projectRoot -Arguments @('add', '--', $lockFile)
}
$targetPaths = @($snapshotFolder) + $lockFiles
$stagedChanges = @(Invoke-GitText -WorkingDirectory $projectRoot -Arguments (@('diff', '--cached', '--name-only', '--') + $targetPaths))
if ($Commit -and $stagedChanges.Count -gt 0) {
$commitMessage = "Sync $snapshotFolder 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) {
$changedConsumers.Add($relativeProject)
Write-Host "Synced $relativeProject."
}
else {
$unchangedConsumers.Add($relativeProject)
Write-Host "$relativeProject is already synchronized."
}
}
catch {
$message = "${relativeProject}: $($_.Exception.Message)"
$failures.Add($message)
Write-Warning $message
}
}
Write-Host ''
Write-Host "Changed: $($changedConsumers.Count); already synchronized: $($unchangedConsumers.Count); failed: $($failures.Count)."
if ($failures.Count -gt 0) {
throw "shared synchronization failed for $($failures.Count) project(s): $($failures -join '; ')"
}
Write-Host 'shared synchronization completed.'