Private/Get-GhostThemeFingerprint.ps1
|
function Get-GhostThemeFingerprint { <# .SYNOPSIS Works out the fingerprint of a theme package and writes that fingerprint into the package. .DESCRIPTION Ghost does not let an integration ask which themes a site has, let alone which version. Sync-GhostTheme still has to know whether the site already has the theme it is about to upload. So the package carries a small file with its own fingerprint, assets/ghost-theme-fingerprint.txt, which the site serves like any other file of the theme: reading that address tells which package is live. The fingerprint is a hash of the names and the content of the files in the package. Neither the order of the files nor the dates in the archive count, and the fingerprint file itself is left out, so the same theme gives the same fingerprint wherever and whenever it was packed. The package is a zip archive, as bytes. An archive that has the theme in a single folder, as a download from a repository has, gets the file in that folder. .EXAMPLE Get-GhostThemeFingerprint -Archive ([System.IO.File]::ReadAllBytes('./dist/my-theme.zip')) Returns the fingerprint, the name and the version in package.json, and the archive with the fingerprint file in it. #> [CmdletBinding()] [OutputType([pscustomobject])] param( # The zip archive of the theme. [Parameter(Mandatory)] [byte[]] $Archive ) $marker = 'assets/ghost-theme-fingerprint.txt' # Windows PowerShell does not load these by itself. Add-Type -AssemblyName 'System.IO.Compression' # Every file of the archive: its path with forward slashes, its content and its date. Paths that only differ # in case are different files. $files = [System.Collections.Generic.Dictionary[string, hashtable]]::new([System.StringComparer]::Ordinal) $source = [System.IO.MemoryStream]::new($Archive, $false) try { $zip = [System.IO.Compression.ZipArchive]::new($source, [System.IO.Compression.ZipArchiveMode]::Read) try { foreach ($entry in $zip.Entries) { $name = $entry.FullName.Replace('\', '/') if ($name.EndsWith('/')) { continue } $buffer = [System.IO.MemoryStream]::new() $stream = $entry.Open() try { $stream.CopyTo($buffer) } finally { $stream.Dispose() } $files[$name] = @{ Content = $buffer.ToArray(); Date = $entry.LastWriteTime } $buffer.Dispose() } } finally { $zip.Dispose() } } catch { throw "The theme package is not a zip archive that can be read: $($_.Exception.Message)" } finally { $source.Dispose() } # In an order that is the same on every machine, whatever its language. $names = [string[]] @($files.Keys) [System.Array]::Sort($names, [System.StringComparer]::Ordinal) # The folder the theme is in: none, or the one folder that holds everything. $prefix = '' if ($names -cnotcontains 'package.json') { $folders = @($names | ForEach-Object { ($_ -split '/')[0] } | Select-Object -Unique) if ($folders.Count -eq 1 -and $names -ccontains "$($folders[0])/package.json") { $prefix = "$($folders[0])/" } else { throw 'The theme package has no package.json, so it is not a Ghost theme.' } } $markerName = $prefix + $marker # Without the byte order mark that some editors write. $packageText = [System.Text.Encoding]::UTF8.GetString($files["${prefix}package.json"].Content) $package = ConvertFrom-Json -InputObject $packageText.TrimStart([char] 0xFEFF) $themeName = $package.PSObject.Properties['name'] $themeVersion = $package.PSObject.Properties['version'] # A hash of a line per file: the path within the theme and the hash of the content. $algorithm = [System.Security.Cryptography.SHA256]::Create() try { $lines = foreach ($name in $names) { if ($name -ceq $markerName) { continue } $hash = ($algorithm.ComputeHash($files[$name].Content) | ForEach-Object { $_.ToString('x2') }) -join '' '{0}:{1}' -f $name.Substring($prefix.Length), $hash } $summary = [System.Text.Encoding]::UTF8.GetBytes(($lines -join "`n")) $fingerprint = ($algorithm.ComputeHash($summary) | ForEach-Object { $_.ToString('x2') }) -join '' } finally { $algorithm.Dispose() } # The same archive, with the fingerprint file in it. $files[$markerName] = @{ Content = [System.Text.Encoding]::ASCII.GetBytes($fingerprint) Date = [datetimeoffset]::new(2000, 1, 1, 0, 0, 0, [timespan]::Zero) } $target = [System.IO.MemoryStream]::new() try { $mode = [System.IO.Compression.ZipArchiveMode]::Create $zip = [System.IO.Compression.ZipArchive]::new($target, $mode, $true) try { $names = [string[]] @($files.Keys) [System.Array]::Sort($names, [System.StringComparer]::Ordinal) foreach ($name in $names) { $entry = $zip.CreateEntry($name, [System.IO.Compression.CompressionLevel]::Optimal) $entry.LastWriteTime = $files[$name].Date $stream = $entry.Open() try { $stream.Write($files[$name].Content, 0, $files[$name].Content.Length) } finally { $stream.Dispose() } } } finally { # Closing the archive writes its directory to the stream. $zip.Dispose() } $content = $target.ToArray() } finally { $target.Dispose() } # Outside the hash literal: Windows PowerShell cannot parse an if statement as a value in one. $name = if ($themeName) { [string] $themeName.Value } $version = if ($themeVersion) { [string] $themeVersion.Value } [pscustomobject]@{ Fingerprint = $fingerprint MarkerPath = $marker Name = $name Version = $version Archive = $content } } |