Private/Copy.ps1
|
# Bringing a source in: every file copied as it is, text searched for anything that looks like a key, a token or a password # and masked where one is found, and a text file too large for one file cut into segments by whole lines. # A segment that is finished never changes again, so a session that only grows adds only what is new. $script:PCContinuityTextExtensions = '.jsonl', '.json', '.md', '.txt', '.log', '.yaml', '.yml', '.toml', '.csv', '.xml', '.html', '.ini', '.cfg', '.ps1', '.py', '.sh' $script:PCContinuityHardLimit = 95MB # a single file larger than 100 MB is refused by GitHub function Get-PCContinuityMaskRule { param([string]$Path) if (-not $Path) { $Path = Join-Path $script:PCContinuityRoot 'defaults' 'mask-rules.psd1' } if (-not (Test-Path -LiteralPath $Path)) { throw "No mask rules at '$Path'." } $data = if ($Path -match '\.json$') { Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable } else { Import-PowerShellDataFile -LiteralPath $Path } foreach ($rule in @($data['Rules'])) { $replace = if ($rule['Replace']) { $rule['Replace'] } else { "[masked:$($rule['Name'])]" } @{ Name = $rule['Name']; Replace = $replace; Regex = [regex]::new($rule['Pattern'], 'Compiled, CultureInvariant') } } } function Invoke-PCContinuityMask { param([string]$Text, $Rules) $counts = [ordered]@{}; $total = 0 foreach ($rule in $Rules) { $n = $rule.Regex.Matches($Text).Count if ($n) { $Text = $rule.Regex.Replace($Text, $rule.Replace); $counts[$rule.Name] = $n; $total += $n } } @{ Text = $Text; Counts = $counts; Total = $total } } function Merge-PCContinuityMask { # Counts by rule added together, in the order of the rules' names. param($Counts) $sum = @{} foreach ($c in @($Counts)) { if ($c) { foreach ($k in @($c.Keys)) { $sum[$k] = [int]$sum[$k] + [int]$c[$k] } } } $out = [ordered]@{} foreach ($k in ($sum.Keys | Sort-Object)) { $out[$k] = $sum[$k] } $out } function Read-PCContinuityByte { # Read a file another program may still be writing. param([string]$Path) $stream = [IO.File]::Open($Path, 'Open', 'Read', 'ReadWrite') try { $memory = [IO.MemoryStream]::new(); $stream.CopyTo($memory); , $memory.ToArray() } finally { $stream.Dispose() } } function New-PCContinuityEntry { # One file of a source, as the manifest records it. Built the same way whether new or carried over, so the keys keep their order. param([string]$Path, [string]$Mode, [long]$Bytes, [long]$ModifiedMs, $Masks, $Segments, [string]$Why, [bool]$Gone) $e = [ordered]@{ path = $Path; mode = $Mode; bytes = $Bytes; modified_ms = $ModifiedMs } $m = Merge-PCContinuityMask $Masks if ($m.Count) { $e.masks = $m } if ($Segments) { $e.segments = @($Segments | ForEach-Object { $s = [ordered]@{ file = $_['file']; bytes = [long]$_['bytes']; open = [bool]$_['open'] } $sm = Merge-PCContinuityMask $_['masks']; if ($sm.Count) { $s.masks = $sm } $s }) } if ($Why) { $e.why = $Why } if ($Gone) { $e.gone = $true } $e } function ConvertTo-PCContinuityEntry { param($Previous, [switch]$Gone) New-PCContinuityEntry -Path $Previous['path'] -Mode $Previous['mode'] -Bytes $Previous['bytes'] -ModifiedMs $Previous['modified_ms'] -Masks $Previous['masks'] ` -Segments $Previous['segments'] -Why $Previous['why'] -Gone:([bool]$Gone -or [bool]$Previous['gone']) } function Test-PCContinuityTarget { param($Entry, [string]$Target) if ($Entry['mode'] -eq 'segmented') { foreach ($s in @($Entry['segments'])) { if (-not (Test-Path -LiteralPath (Join-Path "$Target.segments" $s['file']))) { return $false } } return [bool]@($Entry['segments']).Count } if ($Entry['mode'] -eq 'skipped') { return $false } Test-Path -LiteralPath $Target } function Close-PCContinuitySegment { param($State, [IO.MemoryStream]$Segment, [bool]$Open) $bytes = $Segment.ToArray(); $Segment.SetLength(0) $State.Index++ $name = '{0:d6}{1}' -f $State.Index, $State.Extension $out = $bytes; $masks = $null if ($State.Rules -and @($State.Rules).Count) { $r = Invoke-PCContinuityMask -Text $State.Utf8.GetString($bytes) -Rules $State.Rules if ($r.Total) { $out = $State.Utf8.GetBytes($r.Text); $masks = $r.Counts } } [IO.File]::WriteAllBytes((Join-Path $State.Directory $name), $out) if ($bytes.Length -gt $script:PCContinuityHardLimit) { $State.Oversize = $true } $State.Segments.Add(@{ file = $name; bytes = [long]$bytes.Length; open = $Open; masks = $masks }) $State.Written++ $State.Bytes += $bytes.Length } function Write-PCContinuitySegment { # Cut a text file into segments of whole lines. Filled from the start, each segment takes lines until the next would not fit, # so the same file always gives the same segments, and a file that has only grown leaves its finished segments as they are. param([IO.FileInfo]$File, [string]$Directory, $Rules, [long]$SegmentBytes, $Previous, [switch]$Full) $kept = [Collections.Generic.List[object]]::new(); [long]$offset = 0 if (-not $Full -and $Previous -and $Previous['mode'] -eq 'segmented' -and $File.Length -ge [long]$Previous['bytes']) { $closed = @(@($Previous['segments']) | Where-Object { $_ -and -not $_['open'] }) $present = $true foreach ($s in $closed) { if (-not (Test-Path -LiteralPath (Join-Path $Directory $s['file']))) { $present = $false } } if ($present) { foreach ($s in $closed) { $kept.Add($s); $offset += [long]$s['bytes'] } } } New-Item -ItemType Directory -Path $Directory -Force | Out-Null $state = @{ Index = $kept.Count; Segments = [Collections.Generic.List[object]]::new(); Written = 0; Bytes = $offset; Oversize = $false Directory = $Directory; Extension = $File.Extension; Rules = $Rules; Utf8 = [Text.UTF8Encoding]::new($false) } foreach ($s in $kept) { $state.Segments.Add($s) } $segment = [IO.MemoryStream]::new(); $pending = [IO.MemoryStream]::new(); $buffer = [byte[]]::new(4MB) $stream = [IO.File]::Open($File.FullName, 'Open', 'Read', 'ReadWrite') try { $stream.Position = $offset while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { $start = 0 while ($start -lt $read) { $newline = [Array]::IndexOf($buffer, [byte]10, $start, $read - $start) if ($newline -lt 0) { $pending.Write($buffer, $start, $read - $start); break } $lineLength = $pending.Length + ($newline - $start + 1) if ($segment.Length -gt 0 -and ($segment.Length + $lineLength) -gt $SegmentBytes) { Close-PCContinuitySegment $state $segment $false } if ($pending.Length -gt 0) { $pending.WriteTo($segment); $pending.SetLength(0) } $segment.Write($buffer, $start, $newline - $start + 1) $start = $newline + 1 } } } finally { $stream.Dispose() } if ($pending.Length -gt 0) { if ($segment.Length -gt 0 -and ($segment.Length + $pending.Length) -gt $SegmentBytes) { Close-PCContinuitySegment $state $segment $false } $pending.WriteTo($segment) } if ($segment.Length -gt 0) { Close-PCContinuitySegment $state $segment $true } $names = @($state.Segments | ForEach-Object { $_['file'] }) Get-ChildItem -LiteralPath $Directory -File | Where-Object { $_.Name -match '^\d{6}' -and $_.Name -notin $names } | Remove-Item -Force @{ Bytes = [long]$state.Bytes; Segments = $state.Segments; Written = $state.Written; Oversize = $state.Oversize } } function Copy-PCContinuitySource { # One source into its place under the machine's folder. Nothing already kept is removed: a file gone from the source stays, marked gone. param([string]$SourcePath, [string]$TargetPath, [hashtable]$Previous, $Rules, [long]$SegmentBytes, [switch]$Full) $utf8 = [Text.UTF8Encoding]::new($false) $entries = [Collections.Generic.List[object]]::new() $stats = @{ Copied = 0; Unchanged = 0; SegmentsWritten = 0; Skipped = 0; Gone = 0; Warnings = [Collections.Generic.List[string]]::new() } $seen = @{} foreach ($file in @(Get-ChildItem -LiteralPath $SourcePath -Recurse -File -Force | Sort-Object FullName)) { $rel = [IO.Path]::GetRelativePath($SourcePath, $file.FullName) -replace '\\', '/' $seen[$rel] = $true $modified = [DateTimeOffset]::new($file.LastWriteTimeUtc).ToUnixTimeMilliseconds() $prev = if ($Previous) { $Previous[$rel] } $target = Join-Path $TargetPath $rel if (-not $Full -and $prev -and -not $prev['gone'] -and [long]$prev['bytes'] -eq $file.Length -and [long]$prev['modified_ms'] -eq $modified -and (Test-PCContinuityTarget $prev $target)) { $entries.Add((ConvertTo-PCContinuityEntry $prev)); $stats.Unchanged++; continue } $isText = $script:PCContinuityTextExtensions -contains $file.Extension.ToLowerInvariant() New-Item -ItemType Directory -Path (Split-Path $target -Parent) -Force | Out-Null if ($isText -and $file.Length -gt $SegmentBytes) { if (Test-Path -LiteralPath $target -PathType Leaf) { Remove-Item -LiteralPath $target -Force } $r = Write-PCContinuitySegment -File $file -Directory "$target.segments" -Rules $Rules -SegmentBytes $SegmentBytes -Previous $prev -Full:$Full if ($r.Oversize) { $stats.Warnings.Add("$rel has a single line larger than a file may be on GitHub; that segment cannot be pushed.") } $entries.Add((New-PCContinuityEntry -Path $rel -Mode 'segmented' -Bytes $r.Bytes -ModifiedMs $modified -Masks @($r.Segments | ForEach-Object { $_['masks'] }) -Segments $r.Segments)) $stats.Copied++; $stats.SegmentsWritten += $r.Written continue } if ($file.Length -gt $script:PCContinuityHardLimit) { $entries.Add((New-PCContinuityEntry -Path $rel -Mode 'skipped' -Bytes $file.Length -ModifiedMs $modified -Why 'larger than a single file may be on GitHub, and not text that can be cut by lines')) $stats.Skipped++; $stats.Warnings.Add("$rel was not kept: it is $(Format-PCContinuitySize $file.Length) and cannot be cut by lines.") continue } $bytes = Read-PCContinuityByte $file.FullName $out = $bytes; $mode = 'copy'; $masks = $null if ($isText -and $Rules -and @($Rules).Count -and $bytes.Length) { $r = Invoke-PCContinuityMask -Text $utf8.GetString($bytes) -Rules $Rules if ($r.Total) { $out = $utf8.GetBytes($r.Text); $mode = 'masked'; $masks = $r.Counts } } if (Test-Path -LiteralPath "$target.segments") { Remove-Item -LiteralPath "$target.segments" -Recurse -Force } [IO.File]::WriteAllBytes($target, $out) $entries.Add((New-PCContinuityEntry -Path $rel -Mode $mode -Bytes $bytes.Length -ModifiedMs $modified -Masks $masks)) $stats.Copied++ } if ($Previous) { foreach ($rel in $Previous.Keys) { if ($seen.ContainsKey($rel)) { continue } $prev = $Previous[$rel] if ($prev['mode'] -eq 'skipped') { continue } $entries.Add((ConvertTo-PCContinuityEntry $prev -Gone)); $stats.Gone++ } } @{ Entries = @($entries | Sort-Object { $_.path }); Stats = $stats } } |