TaffarelJr.FileText.psm1
|
#Requires -Version 7.6 using namespace System.Collections.Generic using namespace System.Diagnostics.CodeAnalysis using namespace System.IO using namespace System.Management.Automation using namespace System.Text Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' #region Private/Assert-TokenPair.ps1 function Assert-TokenPair { <# .SYNOPSIS Refuses a replacement that cannot be a file name, or that a re-run would apply again. .DESCRIPTION Not exported. A replacement holding a character no file name can hold is refused, because every name it made would be unusable. One that contains the token is refused unless -Force says to go ahead: the next run would find the token inside every name the last one wrote and rename those too. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. .PARAMETER Force Allows a replacement that contains the token. #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [string]$To, [switch]$Force ) if ($To.IndexOfAny([Path]::GetInvalidFileNameChars()) -ge 0) { throw "Cannot rename '$From' to '$To': not a legal file name." } if ($To.Contains($From) -and -not $Force) { $reason = 'the new name contains the old one,' + ' so a re-run would rename it again.' throw "Cannot rename '$From' to '$To': $reason" + ' Pass -Force to go ahead anyway.' } } #endregion Private/Assert-TokenPair.ps1 #region Private/Edit-ContentToken.ps1 function Edit-ContentToken { <# .SYNOPSIS Replaces a token in the content of every eligible file. .DESCRIPTION Not exported. A file that cannot be read or written is recorded and stepped over, so the caller can name every gap at once. A folder, a symbolic link, and a junction are stepped over without being read: a link stands for a file that is either elsewhere in the tree and handled on its own, or outside it and none of this pass's business. A hard link is an ordinary file with a second name, and is edited like any other. A file whose approval prompt cannot be answered stops the pass instead, since no other file can be answered either. .PARAMETER Item The candidates, as Get-TokenCandidate returns them. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. .PARAMETER SkipExtension Extensions, each with its dot, of files not worth reading. .PARAMETER Cmdlet The public caller's $PSCmdlet, handed to Edit-TextFileToken for each file. A file its ShouldProcess declines is neither edited nor counted. .OUTPUTS A PSCustomObject with Edited, how many files were rewritten; Warning, one line for each file skipped as binary; and Failed, one "<path> - <reason>" line for each file that could not be updated. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Item, [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [string]$To, [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]]$SkipExtension, [Parameter(Mandatory)] [PSCmdlet]$Cmdlet ) $edited = 0 $warnings = [List[string]]::new() $failed = [List[string]]::new() $files = @($Item | Where-Object { -not $_.PSIsContainer -and $_.LinkType -notin 'Junction', 'SymbolicLink' -and $_.Extension -notin $SkipExtension }) foreach ($file in $files) { try { $status = Edit-TextFileToken -Path $file.FullName -From $From ` -To $To -Cmdlet $Cmdlet } catch { if ($_.FullyQualifiedErrorId -eq 'TextFileApprovalFailed') { throw } $reason = $_.Exception.GetBaseException().Message $failed.Add("$($file.FullName) - $reason") continue } if ($status -eq 'Edited') { $edited++ } elseif ($status -eq 'Binary') { $warnings.Add("Skipped binary content: $($file.FullName)") } } return [PSCustomObject]@{ Edited = $edited Warning = $warnings.ToArray() Failed = $failed.ToArray() } } #endregion Private/Edit-ContentToken.ps1 #region Private/Edit-TextFileToken.ps1 function Edit-TextFileToken { <# .SYNOPSIS Replaces a token in one file, and says what happened. .DESCRIPTION Not exported. The file is read once and written once, in the encoding it was read in; its line endings survive because the whole text is written as it was. The caller's ShouldProcess is asked, with the file's full path, only once the file is known to need rewriting, so -WhatIf and -Confirm name only such files. .PARAMETER Path The file to edit. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. May be empty. .PARAMETER Cmdlet The public caller's $PSCmdlet. .OUTPUTS 'Edited'; 'NoToken', when the token is absent or replacing it would change nothing; 'Binary', when the content has a NUL and holds the token; or 'Declined', when ShouldProcess said no. Throws for text that is not valid in its encoding. When ShouldProcess cannot ask, because no one can answer a -Confirm prompt, its error is thrown with the error ID TextFileApprovalFailed, so a caller that steps over a file's failure can tell it apart and stop. #> [CmdletBinding()] [SuppressMessageAttribute( 'PSShouldProcess', '', Justification = 'Asks the public caller''s ShouldProcess, passed in as -Cmdlet.')] [OutputType([string])] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [AllowEmptyString()] [string]$To, [Parameter(Mandatory)] [PSCmdlet]$Cmdlet ) $full = Resolve-TextFilePath -Path $Path -MustExist $edit = Get-TokenEdit -Path $full -From $From -To $To if ($edit.Status -ne 'Edit') { return $edit.Status } try { $approved = $Cmdlet.ShouldProcess($full, "Replace '$From'") } catch { throw [ErrorRecord]::new( $_.Exception, 'TextFileApprovalFailed', [ErrorCategory]::OperationStopped, $full) } if (-not $approved) { return 'Declined' } Write-TextFile ` -Path $full ` -Content $edit.Content ` -Encoding $edit.Encoding ` -Confirm:$false return 'Edited' } #endregion Private/Edit-TextFileToken.ps1 #region Private/Find-UnusableName.ps1 function Find-UnusableName { <# .SYNOPSIS Lists the items whose new name, once the token is replaced, would be unusable on Windows. .DESCRIPTION Not exported. Run before anything is changed, so an unusable name cannot leave a tree whose contents are renamed and whose paths are not. Older Windows and many Windows tools treat a name whose part before the first dot is a device name as that device, whatever its case or extension: CON, PRN, AUX, NUL, COM0 to COM9, LPT0 to LPT9, and COM or LPT with a superscript digit. And Windows quietly drops a trailing dot or space, so the name on disk would not be the name asked for. .PARAMETER Item The candidates, as Get-TokenCandidate returns them. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. .OUTPUTS One "<path> -> <new name> - <reason>" line for each unusable name. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Item, [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [string]$To ) $device = '^(CON|PRN|AUX|NUL|COM[0-9\u00B9\u00B2\u00B3]|LPT[0-9\u00B9\u00B2\u00B3])$' foreach ($entry in $Item) { if (-not $entry.Name.Contains($From)) { continue } $newName = $entry.Name.Replace($From, $To) $stem = $newName.Split('.')[0].TrimEnd(' ') $prefix = "$($entry.FullName) -> $newName -" if ($stem -match $device) { "$prefix older Windows and many Windows tools treat it as a device." } elseif ($newName.EndsWith('.', 'Ordinal') -or $newName.EndsWith(' ', 'Ordinal')) { "$prefix Windows drops a trailing dot or space," + ' so the name on disk would not be the one asked for.' } } } #endregion Private/Find-UnusableName.ps1 #region Private/Format-TextBody.ps1 function Format-TextBody { <# .SYNOPSIS Joins lines into the text a file is written with. .DESCRIPTION Not exported. The lines are joined with the line ending and the text ends with exactly one. A line break inside a line - CRLF, LF or a lone CR - becomes the line ending too, so the text never holds two kinds. One break at the very end of the last line is dropped, since the ending that closes the text stands in for it. No lines make empty text, not one bare line ending. .PARAMETER Line The lines. .PARAMETER LineEnding The line ending to use, CRLF or LF. .OUTPUTS The text. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [AllowEmptyString()] [string[]]$Line, [Parameter(Mandatory)] [string]$LineEnding ) if ($Line.Count -eq 0) { return '' } $all = [string[]]$Line.Clone() $all[-1] = $all[-1] -replace '(\r\n|\r|\n)\z', '' $joined = $all -join "`n" return ($joined -replace '\r\n|\r|\n', $LineEnding) + $LineEnding } #endregion Private/Format-TextBody.ps1 #region Private/Get-BomEncoding.ps1 function Get-BomEncoding { <# .SYNOPSIS Reads the byte order mark at the start of some bytes, and returns the encoding it names and how many bytes it takes up. .DESCRIPTION Not exported. UTF-32 is checked before UTF-16, since a UTF-32 little endian mark begins with the whole of a UTF-16 one, so UTF-16 little endian text whose first character is U+0000 is taken for UTF-32 - the marks alone cannot tell the two apart. Bytes with no mark are UTF-8 without one, which is also what .NET assumes when it decodes. Every encoding returned throws on bytes or characters it cannot map, rather than substituting one and corrupting the text. .PARAMETER Byte The start of the file; only the first four bytes are looked at. .OUTPUTS A PSCustomObject with Encoding and PreambleLength. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [byte[]]$Byte ) $head = [BitConverter]::ToString($Byte, 0, [Math]::Min(4, $Byte.Count)) $encoding = [UTF8Encoding]::new($false, $true) $length = 0 if ($head.StartsWith('EF-BB-BF')) { $encoding = [UTF8Encoding]::new($true, $true) $length = 3 } elseif ($head.StartsWith('FF-FE-00-00')) { $encoding = [UTF32Encoding]::new($false, $true, $true) $length = 4 } elseif ($head.StartsWith('00-00-FE-FF')) { $encoding = [UTF32Encoding]::new($true, $true, $true) $length = 4 } elseif ($head.StartsWith('FF-FE')) { $encoding = [UnicodeEncoding]::new($false, $true, $true) $length = 2 } elseif ($head.StartsWith('FE-FF')) { $encoding = [UnicodeEncoding]::new($true, $true, $true) $length = 2 } return [PSCustomObject]@{ Encoding = $encoding PreambleLength = $length } } #endregion Private/Get-BomEncoding.ps1 #region Private/Get-ByteTokenPattern.ps1 function Get-ByteTokenPattern { <# .SYNOPSIS Returns a token as the bytes it would be in each Unicode encoding, each written as a Latin-1 string. .DESCRIPTION Not exported. Latin-1 maps every byte to exactly one character, so searching a file's bytes read as Latin-1 for one of these strings is searching the file for the token. The encodings are UTF-16 and UTF-32 in both byte orders, and UTF-8. .PARAMETER Token The text to look for. .OUTPUTS One string for each encoding. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$Token ) $encodings = @( [UnicodeEncoding]::new($false, $false) [UnicodeEncoding]::new($true, $false) [UTF32Encoding]::new($false, $false) [UTF32Encoding]::new($true, $false) [UTF8Encoding]::new($false) ) foreach ($encoding in $encodings) { [Encoding]::Latin1.GetString($encoding.GetBytes($Token)) } } #endregion Private/Get-ByteTokenPattern.ps1 #region Private/Get-LinkWarning.ps1 function Get-LinkWarning { <# .SYNOPSIS Names each link whose target path holds the token. .DESCRIPTION Not exported. Nothing in a token pass rewrites a link's target, and renaming what a link points at leaves the link dangling, so a link whose target says the token is named for the caller to re-point by hand. Only symbolic links and junctions are links here. A hard link is an ordinary file with a second name. .PARAMETER Item The candidates, as Get-TokenCandidate returns them. .PARAMETER From The token to look for in each target. .OUTPUTS One "Link target still says ..." line for each such link. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Item, [Parameter(Mandatory)] [string]$From ) $links = @($Item | Where-Object { $_.LinkType -in 'Junction', 'SymbolicLink' }) foreach ($link in $links) { if ($link.LinkTarget -and $link.LinkTarget.Contains($From)) { "Link target still says '$From': $($link.FullName) -> $($link.LinkTarget)" } } } #endregion Private/Get-LinkWarning.ps1 #region Private/Get-StrictEncoding.ps1 function Get-StrictEncoding { <# .SYNOPSIS Returns a copy of an encoding that throws on bytes or characters it cannot map, instead of substituting one. .DESCRIPTION Not exported. Every built-in encoding object - Encoding.ASCII, Encoding.UTF8, Encoding.GetEncoding(1252) - quietly replaces what it cannot map with '?' or U+FFFD, and a rewrite makes that loss permanent. A copy is made because the built-in objects are read-only. .PARAMETER Encoding The encoding to copy. .PARAMETER WithoutPreamble Returns a copy with no byte order mark, for a file that was read without one: Encoding.UTF8, Unicode, BigEndianUnicode, and UTF32 all carry a mark, and writing the file back with one would add a mark it never had. .OUTPUTS The strict copy. #> [CmdletBinding()] [OutputType('System.Text.Encoding')] param( [Parameter(Mandatory)] [Encoding]$Encoding, [switch]$WithoutPreamble ) [Encoding]$strict = $null if ($WithoutPreamble) { $strict = switch ($Encoding.CodePage) { 65001 { [UTF8Encoding]::new($false, $true) } 1200 { [UnicodeEncoding]::new($false, $false, $true) } 1201 { [UnicodeEncoding]::new($true, $false, $true) } 12000 { [UTF32Encoding]::new($false, $false, $true) } 12001 { [UTF32Encoding]::new($true, $false, $true) } } } if ($null -eq $strict) { $strict = $Encoding.Clone() $strict.EncoderFallback = [EncoderFallback]::ExceptionFallback $strict.DecoderFallback = [DecoderFallback]::ExceptionFallback } return $strict } #endregion Private/Get-StrictEncoding.ps1 #region Private/Get-TokenCandidate.ps1 function Get-TokenCandidate { <# .SYNOPSIS Returns every item under a folder that a token pass is allowed to touch. .DESCRIPTION Not exported. A folder named in -Exclude is neither listed nor entered, wherever it sits in the tree, so what is in it costs nothing and cannot raise a warning. A link to a folder is listed, because its own name can be renamed, but not entered, so the walk never leaves the tree or goes round a loop. A folder that cannot be listed is recorded rather than dropped, so a partial pass cannot pass for a complete one. Hidden items are included. .PARAMETER Path The full path of the folder to search. .PARAMETER Exclude File and folder names to skip, each compared with the whole of an item's name, without regard to case and without wildcards. .OUTPUTS A PSCustomObject with Item, the candidates, and Warning, one line for each folder that could not be listed. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]]$Exclude ) $items = [List[object]]::new() $warnings = [List[string]]::new() $pending = [Stack[string]]::new() $pending.Push($Path) while ($pending.Count -gt 0) { $folder = $pending.Pop() try { $entries = @(Get-ChildItem -LiteralPath $folder -Force) } catch { $reason = $_.Exception.GetBaseException().Message $warnings.Add("Not searched: $folder - $reason") continue } foreach ($entry in $entries) { if ($entry.Name -in $Exclude) { continue } $items.Add($entry) if ($entry.PSIsContainer -and -not $entry.LinkType) { $pending.Push($entry.FullName) } } } return [PSCustomObject]@{ Item = $items.ToArray() Warning = $warnings.ToArray() } } #endregion Private/Get-TokenCandidate.ps1 #region Private/Get-TokenEdit.ps1 function Get-TokenEdit { <# .SYNOPSIS Works out what replacing a token in one file would do, without changing the file. .DESCRIPTION Not exported. The file is read once. A file whose first 8 KB hold a NUL is binary content, and is never decoded: its bytes are searched for the token in each Unicode encoding instead. That is also how UTF-16 or UTF-32 text with no byte order mark is caught, as Binary rather than as a file without the token. A file without the token is left alone whatever it holds. Text that has the token but is not valid in its encoding throws, because rewriting it would replace each such character for good. .PARAMETER Path The full path of the file, as Resolve-TextFilePath returns it. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. May be empty. .OUTPUTS A PSCustomObject whose Status is 'Edit', with the new Content and the Encoding to write it in; 'NoToken', for a file without the token or where replacing it would change nothing; or 'Binary', for content with a NUL that holds the token. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [AllowEmptyString()] [string]$To ) if (Test-BinaryHead -Path $Path) { if (Test-ByteToken -Path $Path -Token $From) { return [PSCustomObject]@{ Status = 'Binary' } } return [PSCustomObject]@{ Status = 'NoToken' } } $file = Read-DecodedText -Path $Path if (-not $file.Content.Contains($From)) { return [PSCustomObject]@{ Status = 'NoToken' } } if ($file.Content.Contains([char]0)) { return [PSCustomObject]@{ Status = 'Binary' } } if ($file.Problem) { throw $file.Problem } $replaced = $file.Content.Replace($From, $To) if ([string]::Equals($replaced, $file.Content, 'Ordinal')) { return [PSCustomObject]@{ Status = 'NoToken' } } return [PSCustomObject]@{ Status = 'Edit' Content = $replaced Encoding = $file.Encoding } } #endregion Private/Get-TokenEdit.ps1 #region Private/Read-DecodedText.ps1 function Read-DecodedText { <# .SYNOPSIS Reads a file once, and decodes it by its byte order mark. .DESCRIPTION Not exported. Bytes that are not valid in the encoding are not an error here: the text comes back decoded loosely, with Problem saying what was wrong, so a caller that only has to know whether a token is present can still look, and one that is about to rewrite the file can refuse instead - a rewrite would turn each such byte into a replacement character for good. .PARAMETER Path The full path of the file, as Resolve-TextFilePath returns it. .PARAMETER Encoding What to decode a file with no byte order mark as, instead of UTF-8. A byte order mark still decides. It is used strictly, and without a mark of its own, so the Encoding returned writes the file back with the same bytes it was read from. .OUTPUTS A PSCustomObject with Content, Encoding, and Problem ($null when the bytes were all valid). #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [string]$Path, [Encoding]$Encoding ) try { $bytes = [File]::ReadAllBytes($Path) } catch { throw "Cannot read '$Path': $($_.Exception.GetBaseException().Message)" } $bom = Get-BomEncoding -Byte $bytes $chosen = $bom.Encoding if ($bom.PreambleLength -eq 0 -and $null -ne $Encoding) { $chosen = Get-StrictEncoding -Encoding $Encoding -WithoutPreamble } $length = $bytes.Length - $bom.PreambleLength $problem = $null try { $content = $chosen.GetString($bytes, $bom.PreambleLength, $length) } catch { $loose = [Encoding]::GetEncoding($chosen.CodePage) $content = $loose.GetString($bytes, $bom.PreambleLength, $length) $reason = $_.Exception.GetBaseException().Message $advice = 'Rewriting it would corrupt it;' + ' pass -Encoding if it is in another encoding.' $problem = "'$Path' is not valid $($chosen.WebName) text: $reason $advice" } return [PSCustomObject]@{ Content = $content Encoding = $chosen Problem = $problem } } #endregion Private/Read-DecodedText.ps1 #region Private/Read-FileHead.ps1 function Read-FileHead { <# .SYNOPSIS Returns the first bytes of a file, without reading the rest of it. .DESCRIPTION Not exported. A file shorter than -Count comes back whole. One read can return fewer bytes than asked for even when more are coming - on a network share, say - so reading goes on until -Count bytes or the end of the file. .PARAMETER Path The full path of the file, as Resolve-TextFilePath returns it. .PARAMETER Count How many bytes to read at most. .OUTPUTS The bytes, as one byte array. It is wrapped in a one-item array, which the pipeline unwraps, so an empty file comes back as no bytes rather than as nothing. #> [CmdletBinding()] [OutputType([object[]])] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [int]$Count ) try { $stream = [File]::OpenRead($Path) } catch { throw "Cannot read '$Path': $($_.Exception.GetBaseException().Message)" } try { $buffer = [byte[]]::new($Count) $read = $stream.ReadAtLeast($buffer, $Count, $false) } finally { $stream.Dispose() } $head = [byte[]]::new($read) [Array]::Copy($buffer, $head, $read) # One value that is an array: unrolled, an empty file would come back as # nothing at all rather than as no bytes. return , $head } #endregion Private/Read-FileHead.ps1 #region Private/Rename-NameToken.ps1 function Rename-NameToken { <# .SYNOPSIS Replaces a token in file and folder names. .DESCRIPTION Not exported. The longest path goes first. A child's path is always longer than its parent's, so every item is reached before its own ancestors, whose renaming would stale its path, without assuming a separator character. A rename that fails, usually because the new name is taken, is recorded with both paths, since naming both is what lets the gap be cleared, and the pass moves on to the next item. .PARAMETER Item The candidates, as Get-TokenCandidate returns them. Only those whose name holds the token are renamed. .PARAMETER From The token to replace. .PARAMETER To What to replace it with. .PARAMETER Cmdlet The public caller's $PSCmdlet, whose ShouldProcess is asked with each item's full path and its new name before it is renamed. An item it declines is neither renamed nor counted. .OUTPUTS A PSCustomObject with Renamed, how many items were renamed, and Failed, one "<from> -> <to> - <reason>" line for each item that could not be. #> [CmdletBinding()] [SuppressMessageAttribute( 'PSShouldProcess', '', Justification = 'Asks the public caller''s ShouldProcess, passed in as -Cmdlet.')] [OutputType([PSCustomObject])] param( [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Item, [Parameter(Mandatory)] [string]$From, [Parameter(Mandatory)] [string]$To, [Parameter(Mandatory)] [PSCmdlet]$Cmdlet ) $named = @($Item | Where-Object { $_.Name.Contains($From) }) $ordered = @($named | Sort-Object { $_.FullName.Length } -Descending) $renamed = 0 $failed = [List[string]]::new() foreach ($entry in $ordered) { $newName = $entry.Name.Replace($From, $To) if (-not $Cmdlet.ShouldProcess($entry.FullName, "Rename to '$newName'")) { continue } Write-Verbose "Renaming '$($entry.FullName)' to '$newName'." try { Rename-Item ` -LiteralPath $entry.FullName ` -NewName $newName ` -WhatIf:$false ` -Confirm:$false ` -Verbose:$false ` -ErrorAction Stop $renamed++ } catch { $reason = $_.Exception.GetBaseException().Message $failed.Add("$($entry.FullName) -> $newName - $reason") } } return [PSCustomObject]@{ Renamed = $renamed Failed = $failed.ToArray() } } #endregion Private/Rename-NameToken.ps1 #region Private/Resolve-TextFilePath.ps1 function Resolve-TextFilePath { <# .SYNOPSIS Returns the full path a file argument names, resolved against PowerShell's current location. .DESCRIPTION Not exported. .NET resolves a relative path against the process's own working directory, which Set-Location does not change, so a relative path handed straight to [File] can read or write a different file from the one PowerShell's own commands see. A path on a PowerShell drive comes back as the real file system path. A path on a drive of another provider - Env:, Variable:, HKCU: - is refused: what comes back for it is the provider's own name for the item, which [File] would take as a relative path and write in the process's working directory. .PARAMETER Path The path as the caller gave it. .PARAMETER MustExist Throws when there is no such file. .OUTPUTS The full path. Throws when it is blank, which PowerShell would resolve to the current folder; names a folder; is not on the file system; names a drive or provider that does not exist; or is not a usable path at all - one that climbs above its drive root, holds a NUL character, or is too long - giving the reason. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$Path, [switch]$MustExist ) if ([string]::IsNullOrWhiteSpace($Path)) { throw 'The path is blank; give the path of a file on disk.' } $provider = $null $drive = $null $isFolder = $false $isFile = $false $onDisk = 'give the path of a file on disk.' try { $paths = $ExecutionContext.SessionState.Path $full = $paths.GetUnresolvedProviderPathFromPSPath( $Path, [ref]$provider, [ref]$drive) if ($provider.Name -eq 'FileSystem') { $isFolder = Test-Path -LiteralPath $full -PathType Container $isFile = Test-Path -LiteralPath $full -PathType Leaf } } catch [DriveNotFoundException], [ProviderNotFoundException] { throw "'$Path' is not a path on any drive or provider here; $onDisk" } catch { $reason = $_.Exception.GetBaseException().Message throw "'$Path' is not a usable file path: $reason" } if ($provider.Name -ne 'FileSystem') { throw "'$Path' is not a file system path; $onDisk" } if ($isFolder) { throw "'$Path' is a folder, not a file." } if ($MustExist -and -not $isFile) { throw "No such file: '$Path'." } return $full } #endregion Private/Resolve-TextFilePath.ps1 #region Private/Resolve-TreeRoot.ps1 function Resolve-TreeRoot { <# .SYNOPSIS Returns the full path of the folder a path argument names, resolved against PowerShell's current location. .DESCRIPTION Not exported. A relative path is relative to PowerShell's location, not the process's, and a path on a PowerShell drive comes back as the real file system path, as Resolve-TextFilePath does for a file. A wildcard character in the path is part of the name. .PARAMETER Path The path as the caller gave it. .OUTPUTS The full path. Throws when the path is blank, is not usable as a path at all, is on a drive that is not the file system, names a file, or names nothing. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$Path ) if ([string]::IsNullOrWhiteSpace($Path)) { throw 'The path is blank; give the path of a folder on disk.' } $provider = $null $drive = $null $isFolder = $false $isFile = $false try { $paths = $ExecutionContext.SessionState.Path $full = $paths.GetUnresolvedProviderPathFromPSPath( $Path, [ref]$provider, [ref]$drive) if ($provider.Name -eq 'FileSystem') { $isFolder = Test-Path -LiteralPath $full -PathType Container $isFile = Test-Path -LiteralPath $full -PathType Leaf } } catch { $reason = $_.Exception.GetBaseException().Message throw "'$Path' is not a usable folder path: $reason" } if ($provider.Name -ne 'FileSystem') { throw "'$Path' is not a file system path; give a folder on disk." } if ($isFile) { throw "'$Path' is a file, not a folder." } if (-not $isFolder) { throw "No such folder: '$Path'." } return $full } #endregion Private/Resolve-TreeRoot.ps1 #region Private/Resolve-WriteEncoding.ps1 function Resolve-WriteEncoding { <# .SYNOPSIS Returns the encoding a write uses. .DESCRIPTION Not exported. The encoding the caller gave, if any. Otherwise the one the reference file is written in, read from its byte order mark. With neither, UTF-8 without a mark. A reference with no mark that is not valid UTF-8, Windows-1252 say, has no encoding to read off it, so it throws rather than silently turning the file into UTF-8. Every encoding returned throws on text it cannot hold. .PARAMETER Reference The full path of the file to match, as Resolve-WriteReference returns it. .PARAMETER Encoding The encoding the caller asked for. .OUTPUTS The encoding to write with. #> [CmdletBinding()] [OutputType('System.Text.Encoding')] param( [string]$Reference, [Encoding]$Encoding ) [Encoding]$chosen = [UTF8Encoding]::new($false, $true) if ($null -ne $Encoding) { $chosen = Get-StrictEncoding -Encoding $Encoding } elseif ($Reference) { $decoded = Read-DecodedText -Path $Reference if ($decoded.Problem -and $decoded.Encoding.GetPreamble().Length -eq 0) { throw ("Cannot tell what encoding '$Reference' is in:" + ' it has no byte order mark and is not valid UTF-8.' + ' Pass -Encoding to say which encoding to write.') } $chosen = $decoded.Encoding } return $chosen } #endregion Private/Resolve-WriteEncoding.ps1 #region Private/Resolve-WriteReference.ps1 function Resolve-WriteReference { <# .SYNOPSIS Returns the existing file a write takes its encoding and line ending from, or nothing when there is none. .DESCRIPTION Not exported. The file being written, when it already holds something, and otherwise the sibling named by -LikeFilePath, when that does. An empty file has nothing to preserve, so it is passed over, and so is a sibling that is not there. A sibling that is a folder or a blank path is a mistake, and throws. .PARAMETER Path The full path of the file being written. .PARAMETER LikeFilePath The sibling to fall back on, as the caller gave it. .OUTPUTS The full path of the file to read, or nothing. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [string]$Path, [string]$LikeFilePath ) $candidates = @($Path) if ($PSBoundParameters.ContainsKey('LikeFilePath')) { $candidates += Resolve-TextFilePath -Path $LikeFilePath } foreach ($candidate in $candidates) { $isFile = Test-Path -LiteralPath $candidate -PathType Leaf if ($isFile -and ([FileInfo]$candidate).Length -gt 0) { return $candidate } } } #endregion Private/Resolve-WriteReference.ps1 #region Private/Test-BinaryHead.ps1 function Test-BinaryHead { <# .SYNOPSIS Says whether a file's first 8 KB hold a NUL that no UTF-16 or UTF-32 byte order mark accounts for. .DESCRIPTION Not exported. The test git uses to tell binary content from text, made without reading the rest of the file, so a large binary file costs a few kilobytes rather than a full read and decode. UTF-16 and UTF-32 text is full of NULs, so a file that starts with one of their marks counts as text; without a mark it looks binary, as it does to git. .PARAMETER Path The full path of the file, as Resolve-TextFilePath returns it. .OUTPUTS [bool] #> [CmdletBinding()] [OutputType([bool])] param( [Parameter(Mandatory)] [string]$Path ) $head = Read-FileHead -Path $Path -Count 8KB $bom = Get-BomEncoding -Byte $head if ($bom.Encoding -is [UnicodeEncoding] -or $bom.Encoding -is [UTF32Encoding]) { return $false } return [Array]::IndexOf($head, [byte]0) -ge 0 } #endregion Private/Test-BinaryHead.ps1 #region Private/Test-ByteToken.ps1 function Test-ByteToken { <# .SYNOPSIS Says whether a file's bytes hold a token written in UTF-8, UTF-16, or UTF-32, in either byte order. .DESCRIPTION Not exported. For content that is not going to be decoded as text. The file is read a chunk at a time, so its size does not matter, and each chunk is searched as Latin-1 for the token's patterns. Each chunk is searched together with the end of the one before it, so a token split across two reads is still found. .PARAMETER Path The full path of the file, as Resolve-TextFilePath returns it. .PARAMETER Token The text to look for. .PARAMETER ChunkSize How many bytes to read at a time. .OUTPUTS [bool] #> [CmdletBinding()] [OutputType([bool])] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [string]$Token, [ValidateRange('Positive')] [int]$ChunkSize = 1MB ) $patterns = @(Get-ByteTokenPattern -Token $Token) $measured = $patterns | Measure-Object -Property Length -Maximum $overlap = $measured.Maximum - 1 $buffer = [byte[]]::new($ChunkSize) $carry = '' $stream = [File]::OpenRead($Path) try { $read = $stream.Read($buffer, 0, $ChunkSize) while ($read -gt 0) { $text = $carry + [Encoding]::Latin1.GetString($buffer, 0, $read) foreach ($pattern in $patterns) { if ($text.Contains($pattern)) { return $true } } $keep = [Math]::Min($text.Length, $overlap) $carry = $text.Substring($text.Length - $keep) $read = $stream.Read($buffer, 0, $ChunkSize) } } finally { $stream.Dispose() } return $false } #endregion Private/Test-ByteToken.ps1 #region Private/Write-FileByte.ps1 function Write-FileByte { <# .SYNOPSIS Writes a byte order mark and some bytes over a file. .DESCRIPTION Not exported. The file is written in place rather than replaced, so it keeps its attributes: a hidden or system file stays one, and can be written at all. What is longer than the new bytes is cut off. A file that cannot be opened, because its folder is missing, another program holds it, or it is read-only, throws "Cannot write" with the path and the reason, before the file is changed. -CreateDirectory makes the folders on the way first. .PARAMETER Path The full path of the file. .PARAMETER Preamble The byte order mark, or no bytes. .PARAMETER Payload The encoded text. .PARAMETER CreateDirectory Makes any folder missing on the way to the file. #> [CmdletBinding()] param( [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [AllowEmptyCollection()] [byte[]]$Preamble, [Parameter(Mandatory)] [AllowEmptyCollection()] [byte[]]$Payload, [switch]$CreateDirectory ) try { if ($CreateDirectory) { $null = [Directory]::CreateDirectory([Path]::GetDirectoryName($Path)) } $stream = [File]::Open( $Path, [FileMode]::OpenOrCreate, [FileAccess]::Write, [FileShare]::Read) } catch { throw "Cannot write '$Path': $($_.Exception.GetBaseException().Message)" } try { $stream.Write($Preamble, 0, $Preamble.Length) $stream.Write($Payload, 0, $Payload.Length) $stream.SetLength($stream.Position) } finally { $stream.Dispose() } } #endregion Private/Write-FileByte.ps1 #region Public/Get-FileEncoding.ps1 function Get-FileEncoding { <# .SYNOPSIS Returns the encoding a file is written in, from the byte order mark it currently starts with. .DESCRIPTION Rewriting a file through PowerShell's own defaults is lossy: Set-Content writes UTF-8 without a BOM, so a file that had one loses it, and a UTF-16 file is silently transcoded. Reading the mark and handing it back keeps a content edit to just the content. UTF-8, UTF-16, and UTF-32 marks are recognized, in both byte orders where there is a choice. UTF-8 without a BOM is the fallback, which is also what .NET assumes when it decodes. A file in a legacy encoding such as Windows-1252 has no mark to read, so it is reported as UTF-8 too, and the encoding returned throws when it is asked to decode that file. The marks overlap in one place: FF FE 00 00 starts both UTF-32 little endian and UTF-16 little endian text whose first character is U+0000. It is read as UTF-32, so such a UTF-16 file is reported as UTF-32. A file that cannot be inspected - missing, a folder, not on the file system - is a terminating error, and in a pipeline it stops the pipeline. .PARAMETER Path The file to inspect. A relative path is relative to PowerShell's current location. Path strings can be piped in, and so can files from Get-ChildItem (by their FullName or PSPath) and Resolve-Path output (by its Path). .INPUTS System.String. The path of a file; or any object with a FullName, PSPath, or Path property, such as the files Get-ChildItem returns. .OUTPUTS System.Text.Encoding. The encoding, which throws on text it cannot map instead of substituting a character. .EXAMPLE Get-FileEncoding -Path ./README.md Returns the encoding README.md is written in. .EXAMPLE Get-ChildItem -File -Filter *.cs -Recurse | Get-FileEncoding Returns the encoding of every C# file under the current folder, one per file, in the order they are listed. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Get-LineEnding #> [CmdletBinding()] [OutputType('System.Text.Encoding')] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName', 'PSPath')] [string]$Path ) process { $ErrorActionPreference = 'Stop' $full = Resolve-TextFilePath -Path $Path -MustExist $head = Read-FileHead -Path $full -Count 4 return (Get-BomEncoding -Byte $head).Encoding } } #endregion Public/Get-FileEncoding.ps1 #region Public/Get-LineEnding.ps1 function Get-LineEnding { <# .SYNOPSIS Returns the line ending already used in a piece of text. .DESCRIPTION Whichever of CRLF and bare LF the text uses more often, so a file with a stray odd line is not converted wholesale to the odd one out; a tie goes to CRLF. A CRLF's own LF is not counted as a bare one. Falls back to this process's own default only for content that carries no line ending to read at all, such as a brand new file. A bare CR, the classic Mac OS ending, is not counted, so text that uses only that gets the fallback too. .PARAMETER Content The text to inspect. .INPUTS None. The text is given with -Content. .OUTPUTS System.String. The line ending: CRLF or LF, or this process's own default when the text has none. .EXAMPLE Get-LineEnding -Content (Get-Content -Raw -LiteralPath ./README.md) Returns "`r`n" when README.md has at least as many CRLF endings as bare LF ones, "`n" when it has more bare LF ones, and this process's own line ending when it has neither. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Get-FileEncoding #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory, Position = 0)] [AllowEmptyString()] [string]$Content ) $crlf = [regex]::Matches($Content, "`r`n").Count $lf = [regex]::Matches($Content, "(?<!`r)`n").Count if ($crlf -eq 0 -and $lf -eq 0) { return [Environment]::NewLine } if ($crlf -ge $lf) { return "`r`n" } return "`n" } #endregion Public/Get-LineEnding.ps1 #region Public/Read-TextFile.ps1 function Read-TextFile { <# .SYNOPSIS Reads a text file's content, encoding, and line ending, so a rewrite can preserve all three. .DESCRIPTION The file is decoded strictly. Text that is not valid in its encoding - a Windows-1252 file read as UTF-8, say, or a UTF-8 one read with -Encoding ASCII - throws rather than coming back with replacement characters, which a rewrite would then make permanent. A file that cannot be read - missing, a folder, not on the file system, or not valid in its encoding - is a terminating error, and in a pipeline it stops the pipeline. .PARAMETER Path The file to read. A relative path is relative to PowerShell's current location. Path strings can be piped in, and so can files from Get-ChildItem (by their FullName or PSPath) and Resolve-Path output (by its Path). .PARAMETER Encoding What to read a file with no byte order mark as, instead of UTF-8. A byte order mark still decides. Takes a System.Text.Encoding object, such as [Text.Encoding]::GetEncoding(1252) - not a name like 'utf8' as Get-Content does. It comes back as the file's Encoding, without a mark of its own, so it describes the file as it was read. .INPUTS System.String. The path of a file; or any object with a FullName, PSPath, or Path property, such as the files Get-ChildItem returns. .OUTPUTS System.Management.Automation.PSCustomObject. One per file, with Content, Encoding, and LineEnding. .EXAMPLE $file = Read-TextFile -Path ./README.md Reads README.md; $file.Content is its text, $file.Encoding the encoding it is written in, and $file.LineEnding its line ending. .EXAMPLE $file = Read-TextFile -Path ./legacy.txt ` -Encoding ([Text.Encoding]::GetEncoding(1252)) Reads a Windows-1252 file, which has no byte order mark to read, as Windows-1252. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Get-FileEncoding .LINK Get-LineEnding #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName', 'PSPath')] [string]$Path, [Encoding]$Encoding ) process { $ErrorActionPreference = 'Stop' $full = Resolve-TextFilePath -Path $Path -MustExist $decoded = Read-DecodedText -Path $full -Encoding $Encoding if ($decoded.Problem) { throw $decoded.Problem } return [PSCustomObject]@{ Content = $decoded.Content Encoding = $decoded.Encoding LineEnding = Get-LineEnding -Content $decoded.Content } } } #endregion Public/Read-TextFile.ps1 #region Public/Rename-Token.ps1 function Rename-Token { <# .SYNOPSIS Replaces a placeholder token in file content, file names, and folder names. .DESCRIPTION Two passes, in this order: file contents, then names, longest path first. Contents come first because the list of items is taken up front, and a rename would stale the path of any file not yet read. Names go longest path first for the same reason: renaming a parent would stale every path beneath it. Neither pass stops at its first failure. The token has already been replaced elsewhere by then, and a tree that is half one name and half the other is easier to reason about with every gap named at once. So each pass collects what it could not do, and this throws at the end if anything is on that list: a caller must never land a commit on a tree that still says both names. The match is literal and case-sensitive throughout, so a token that differs from its replacement only in case is still a rename. A file is read once and written back in the encoding it had, with its line endings untouched. A file that has the token but is not valid in its encoding, Windows-1252 text for one, is a failure and is not rewritten, because doing so would replace each such character for good. A file without the token is never looked at that closely. Content with a NUL in it is binary, or UTF-16 or UTF-32 text without a byte order mark, which looks the same. It is left alone, and a file that holds the token in such content is named in Warning. A NUL in the first 8 KB settles it without the file being decoded: its bytes are searched for the token instead. Symbolic links and junctions are never followed or read. A link's own name is renamed, but the walk does not enter a linked folder, and a linked file's content is left to whatever it points at. A link's target is never rewritten either, so a link whose target holds the token, such as one pointing at a folder of the tree that is being renamed, is named in Warning, to be re-pointed by hand. A hard link is an ordinary file with a second name, and is edited like any other. A folder that cannot be listed is named in Warning, so a partial run is not mistaken for a full one. Before anything is changed, every new name is checked. On Windows one that would be unusable (see -To) stops the run before the content pass, so an unusable name cannot leave a tree whose contents are renamed and whose paths are not. -WhatIf and -Confirm name each file whose content holds the token and each item whose name does, one at a time. With -Confirm an item that is declined is left as it was and not counted. With -WhatIf nothing is changed and nothing is returned. With -Verbose, names each file as it is written and each item as it is renamed. .PARAMETER Path The folder to search, which must be a folder on the file system. A relative path is relative to PowerShell's current location. Only what is inside it is renamed: the folder's own name is left as it is, even when it holds the token. .PARAMETER From The token to replace. -WhatIf, -Confirm, -Verbose, the warnings, and the error messages show this text, so a secret should not be given where that output is kept. .PARAMETER To What to replace it with. The names it makes are judged by the file system this runs on, which is the one that will hold the tree. On Windows that refuses a name older Windows and many Windows tools treat as a device (CON, NUL, COM1, and the like) and one ending in a dot or space; everywhere it must not hold a character no file name can hold. -WhatIf, -Confirm, -Verbose, and the error messages show the names it makes, so a secret should not be given here either. .PARAMETER SkipExtension Extensions, each with its dot, of files whose content is not worth reading. Such a file is still renamed. Content that turns out to be binary anyway is detected and left alone, so this list is a shortcut rather than the safeguard. .PARAMETER Exclude File and folder names to skip entirely, wherever they sit in the tree. An excluded folder is not entered at all. Empty excludes nothing. Each name is compared with the whole of an item's name, without regard to case and literally: wildcards are not supported, so '*.log' excludes only an item named exactly that. .PARAMETER Force Goes ahead when -To contains -From, such as 'Foo' to 'FooBar'. That is refused by default because running it again would rename the result once more; with -Force the caller is taking that on. .PARAMETER WhatIf Shows what would happen if the command runs. The command is not run. .PARAMETER Confirm Prompts for confirmation before the command runs. .INPUTS None. Nothing can be piped in. .OUTPUTS System.Management.Automation.PSCustomObject. FilesEdited, PathsRenamed, and Warning, one line for each file skipped as binary, folder that could not be listed, and link whose target holds the token. Nothing under -WhatIf. .EXAMPLE Rename-Token -Path ./MyProject -From 'Placeholder' -To 'MyProject' Replaces Placeholder in every file, file name, and folder name under MyProject, and throws at the end, naming each item, if any of it could not be done. .EXAMPLE Rename-Token -Path . -From 'Placeholder' -To 'MyProject' ` -Exclude '.git', 'packages' -WhatIf Shows each file and name that would change, entering neither a packages folder nor a .git one, and changes nothing. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Update-FileToken #> [CmdletBinding(SupportsShouldProcess)] [SuppressMessageAttribute( 'PSShouldProcess', '', Justification = 'The helpers it hands $PSCmdlet to ask its ShouldProcess.')] [OutputType([PSCustomObject])] param( [Parameter(Mandatory, Position = 0)] [string]$Path, [Parameter(Mandatory)] [ValidatePattern('\S')] [string]$From, [Parameter(Mandatory)] [ValidatePattern('\S')] [string]$To, [ValidatePattern( '^\.', ErrorMessage = "an extension starts with a dot, such as '.png' - not '{0}'")] [string[]]$SkipExtension = @( '.dll' '.exe' '.gif' '.ico' '.jpeg' '.jpg' '.pdf' '.png' '.snk' '.zip' ), [string[]]$Exclude = @( '.git' 'bin' 'node_modules' 'obj' ), [switch]$Force ) $ErrorActionPreference = 'Stop' if (-not $PSBoundParameters.ContainsKey('WhatIf')) { $WhatIfPreference = $PSCmdlet.GetVariableValue('WhatIfPreference') } if (-not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = $PSCmdlet.GetVariableValue('ConfirmPreference') } if (-not $PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } $root = Resolve-TreeRoot -Path $Path if ([string]::Equals($From, $To, 'Ordinal')) { if ($WhatIfPreference) { return } return [PSCustomObject]@{ FilesEdited = 0 PathsRenamed = 0 Warning = @() } } Assert-TokenPair -From $From -To $To -Force:$Force $candidates = Get-TokenCandidate -Path $root -Exclude $Exclude if ($IsWindows) { $unusable = @(Find-UnusableName -Item $candidates.Item -From $From -To $To) if ($unusable) { $count = $unusable.Count $lines = $unusable -join "`n " throw "Cannot rename '$From' to '$To': $count of the new names" + " would be unusable on Windows, so nothing was changed:`n $lines" } } $links = @(Get-LinkWarning -Item $candidates.Item -From $From) $content = Edit-ContentToken -Item $candidates.Item -From $From -To $To ` -SkipExtension $SkipExtension -Cmdlet $PSCmdlet $names = Rename-NameToken -Item $candidates.Item -From $From -To $To ` -Cmdlet $PSCmdlet $failed = @($content.Failed) + @($names.Failed) if ($failed) { $lines = $failed -join "`n " throw "Could not rename '$From' -> '$To' in $($failed.Count) item(s):`n $lines" } if ($WhatIfPreference) { return } return [PSCustomObject]@{ FilesEdited = $content.Edited PathsRenamed = $names.Renamed Warning = @($candidates.Warning) + $links + @($content.Warning) } } #endregion Public/Rename-Token.ps1 #region Public/Update-FileToken.ps1 function Update-FileToken { <# .SYNOPSIS Replaces a token in one file's content, keeping its encoding and line ending. .DESCRIPTION The file is read once and written once, in the encoding it was read in, and its line endings are written as they were. The match is literal and case-sensitive, and every occurrence is replaced. A file without the token is left alone, whatever it holds. A file whose first 8 KB hold a NUL is binary content, which an extension list cannot recognize and rewriting as text would destroy. It is never decoded: its bytes are searched for the token, as UTF-8, UTF-16, and UTF-32. One that holds the token is declined with a warning, so declining is not mistaken for there being nothing to do. UTF-16 or UTF-32 text without a byte order mark is full of NULs and is declined the same way. Text that holds the token but is not valid in its encoding, such as Windows-1252 text read as UTF-8, throws and is left as it was: rewriting it would replace each such character for good. A file that cannot be updated is a terminating error for that call, and in a pipeline it stops the pipeline: files after it are not touched, and files before it stay updated. -WhatIf and -Confirm name each file that holds the token, once it has been read; a file without it is not named. With -WhatIf nothing is changed and nothing is returned, and with -Confirm a file declined at the prompt is left as it was and returns nothing. With -Verbose, names each file as it is written, with its size and encoding. .PARAMETER Path The file to update. A relative path is relative to PowerShell's current location. Path strings can be piped in, and so can files from Get-ChildItem (by their FullName or PSPath) and Resolve-Path output (by its Path). A folder, given or piped in, throws and so stops the pipeline: list files with Get-ChildItem -File. .PARAMETER From The token to replace. -WhatIf, -Confirm, -Verbose, and the warning for binary content show this text, so a secret should not be given where that output is kept. .PARAMETER To What to replace it with. Empty removes the token. No output shows it. .PARAMETER WhatIf Shows what would happen if the command runs. The command is not run. .PARAMETER Confirm Prompts for confirmation before the command runs. .INPUTS System.String. The path of a file; or any object with a FullName, PSPath, or Path property, such as the files Get-ChildItem returns. .OUTPUTS System.Boolean. Whether the file was rewritten, one per file. Nothing under -WhatIf, nor for a file declined at a -Confirm prompt. .EXAMPLE Update-FileToken -Path ./Program.cs -From 'OldName' -To 'NewName' Replaces the token in Program.cs, and returns $true if it held the token and $false if it did not. .EXAMPLE Get-ChildItem -File -Filter *.cs -Recurse | Update-FileToken -From 'OldName' -To 'NewName' Replaces the token in every C# file under the current folder, and returns one $true or $false for each. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Write-TextFile #> [CmdletBinding(SupportsShouldProcess)] [SuppressMessageAttribute( 'PSShouldProcess', '', Justification = 'Edit-TextFileToken asks this command''s ShouldProcess.')] [OutputType([bool])] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('FullName', 'PSPath')] [string]$Path, [Parameter(Mandatory)] [ValidatePattern('\S')] [string]$From, [Parameter(Mandatory)] [AllowEmptyString()] [string]$To ) process { $ErrorActionPreference = 'Stop' if (-not $PSBoundParameters.ContainsKey('WhatIf')) { $WhatIfPreference = $PSCmdlet.GetVariableValue('WhatIfPreference') } if (-not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = $PSCmdlet.GetVariableValue('ConfirmPreference') } if (-not $PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } $status = Edit-TextFileToken -Path $Path -From $From -To $To ` -Cmdlet $PSCmdlet if ($status -eq 'Binary') { $reason = "holds '$From' and a NUL, so it was not rewritten." Write-Warning "Skipped binary content: '$Path' $reason" } if ($WhatIfPreference -or $status -eq 'Declined') { return } return $status -eq 'Edited' } } #endregion Public/Update-FileToken.ps1 #region Public/Write-TextFile.ps1 function Write-TextFile { <# .SYNOPSIS Writes text back with the encoding the file already had, and with -Line its CRLF or LF line ending too. .DESCRIPTION Rewriting a file through PowerShell's own defaults is lossy: it writes UTF-8 without a byte order mark, so a file that had one loses it, and it ends every line with this process's line ending. This keeps the file as it was except for its text. -Line is for text built up a line at a time: the lines are joined with the line ending the file already uses, and the file ends with exactly one. -Content is for text already assembled, written exactly as given, line endings included; only the encoding is matched. -LikeFilePath supplies the encoding and the line ending when Path does not exist yet, or is empty and so has nothing to preserve: a file only now being created, that should still come out looking like a sibling already on disk. With neither on disk to match, the file is UTF-8 without a BOM, and its line ending is this process's own. The encoding to keep comes from the file's byte order mark. A file with no mark that is not valid UTF-8 either - Windows-1252, say - has no encoding to read off it, so writing over it, or copying from it with -LikeFilePath, throws unless -Encoding says what to write. The text is encoded in full before the file is opened, so text the encoding cannot hold - a lone surrogate, or an accented letter for -Encoding ASCII - throws and leaves an existing file exactly as it was, and creates no new one. An existing file is written in place rather than replaced, so it keeps its attributes: a hidden or system file stays one, and can be written at all. Anything that stops the write is a terminating error for that call. Everything checked above, and a failure to open the file, is raised before the file is changed; a failure while writing it, after it is open, can leave it partly written. A file that cannot be opened - its folder is missing, another program holds it, or it is read-only - throws "Cannot write '<path>':" followed by the reason. A folder that is missing is made only when -CreateDirectory says so. With -WhatIf nothing is changed and nothing is returned. With -Verbose, names the file, the encoding and the size of what is written, never its text. .PARAMETER Path The file to write. A relative path is relative to PowerShell's current location. .PARAMETER Line Joined with the resolved line ending and given exactly one trailing one. A line break inside a line - CRLF, LF, or a lone CR - becomes the resolved ending too, so the file never ends up with two kinds; one break at the very end of the last line is dropped, since the file's own trailing ending stands in for it. No lines at all write no text. Use this, not -Content, for anything built up a line at a time. The resolved ending is the one Get-LineEnding reads off the file, CRLF or LF, never a lone CR: a file whose lines end in a lone CR is rewritten with this process's own line ending. Also accepted as -Lines. .PARAMETER Content Written exactly as given, line endings included: only the encoding is matched, never the line ending. For the rarer case where the caller has already assembled the whole file, trailing line ending included. .PARAMETER LikeFilePath A sibling file to copy the encoding and line ending from, when -Path itself does not exist yet or is empty. .PARAMETER Encoding Writes with this encoding whatever the file had, for a caller that means to change it - or to put back one Read-TextFile was given. Takes a System.Text.Encoding object, not a name like 'utf8'. Its byte order mark, if it has one, is written; text it cannot hold throws rather than being written with a stand-in character. .PARAMETER CreateDirectory Makes any folder missing on the way to Path before the file is written, as New-Item -Force does. Without it a missing folder is an error. With -WhatIf no folder is made. .PARAMETER WhatIf Shows what would happen if the command runs. The command is not run. .PARAMETER Confirm Prompts for confirmation before the command runs. .INPUTS None. The text is given with -Line or -Content. .OUTPUTS None. The text is written to the file. .EXAMPLE Write-TextFile -Path ./notes.txt -Line 'first', 'second' Writes the two lines, in notes.txt's own encoding and line ending if it exists, and in UTF-8 with this process's line ending if it does not. .EXAMPLE $file = Read-TextFile -Path ./README.md $text = $file.Content -replace 'old', 'new' Write-TextFile -Path ./README.md -Content $text Changes a word and keeps everything else about README.md. .EXAMPLE Write-TextFile -Path ./build/new.txt -Content 'text' -CreateDirectory Makes the build folder if it is missing, and writes the file in it. .LINK https://github.com/TaffarelJr/powershell-modules/blob/main/src/TaffarelJr.FileText/README.md .LINK Read-TextFile .LINK Get-FileEncoding .LINK Get-LineEnding #> [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Lines')] param( [Parameter(Mandatory, Position = 0)] [string]$Path, [Parameter(Mandatory, ParameterSetName = 'Lines')] [AllowEmptyCollection()] [AllowEmptyString()] [Alias('Lines')] [string[]]$Line, [Parameter(Mandatory, ParameterSetName = 'Content')] [AllowEmptyString()] [string]$Content, [string]$LikeFilePath, [Encoding]$Encoding, [switch]$CreateDirectory ) $ErrorActionPreference = 'Stop' if (-not $PSBoundParameters.ContainsKey('WhatIf')) { $WhatIfPreference = $PSCmdlet.GetVariableValue('WhatIfPreference') } if (-not $PSBoundParameters.ContainsKey('Confirm')) { $ConfirmPreference = $PSCmdlet.GetVariableValue('ConfirmPreference') } if (-not $PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference') } $full = Resolve-TextFilePath -Path $Path if ($PSBoundParameters.ContainsKey('LikeFilePath')) { $reference = Resolve-WriteReference -Path $full ` -LikeFilePath $LikeFilePath } else { $reference = Resolve-WriteReference -Path $full } $chosen = Resolve-WriteEncoding -Reference $reference -Encoding $Encoding $body = $Content if ($PSCmdlet.ParameterSetName -eq 'Lines') { $lineEnding = [Environment]::NewLine if ($reference) { $decoded = Read-DecodedText -Path $reference -Encoding $Encoding $lineEnding = Get-LineEnding -Content $decoded.Content } $body = Format-TextBody -Line $Line -LineEnding $lineEnding } $preamble = $chosen.GetPreamble() $payload = $chosen.GetBytes($body) if (-not $PSCmdlet.ShouldProcess($full, 'Write file')) { return } $size = $preamble.Length + $payload.Length Write-Verbose "Writing $size bytes to '$full' as $($chosen.WebName)." Write-FileByte -Path $full -Preamble $preamble -Payload $payload ` -CreateDirectory:$CreateDirectory } #endregion Public/Write-TextFile.ps1 Export-ModuleMember -Function @( 'Get-FileEncoding' 'Get-LineEnding' 'Read-TextFile' 'Rename-Token' 'Update-FileToken' 'Write-TextFile' ) |