Public/PsStrUtil.ps1


<############################################################################
 # Find line of code by regex1, and if following line matches regex2, then
 # append supplied code after that line
 ############################################################################>

Function AppendCodeBeforeMatchingLine([string]$csFile, [string]$regex, [string]$codeToAppend, [string]$unlessALineMatchesThisRegex) 
{
    $contents = (Get-Content $csFile)

    if($contents | ?{$_ -match $unlessALineMatchesThisRegex}) {
        Write-Verbose "### File '$csFile' already matches '$unlessALineMatchesThisRegex', no need to change"
        # already matches, skip it
    } else {
        [bool]$foundMatch = $false
        for($index = 0; $index -lt $contents.Length; $index++) {

            if($contents[$index] -match $regex) {
                $contents[$index] =  $codeToAppend + "`r`n" + $contents[$index]
                $foundMatch = $true
                break
            }
        }
        if($foundMatch -eq $false) {
            $msg = @"
AppendCodeBeforeMatchingLine could not find pattern '$regex' in file '$csFile'
CALLSTACK:$(Get-PSCallStack | Out-String)
"@

            throw $msg
        }
        $contents | Set-Content $csFile
    }
}

<############################################################################
 # Replace all occurences of $lookFor with $replaceWith in $file save
 # results in place.
 ############################################################################>

Function ReplacePatternInFile([string]$file, [string]$lookFor, [string]$replaceWith)
{
    (Get-Content $file) -replace $lookFor,$replaceWith | Out-FileUtf8NoBom $file
}

<############################################################################
 # Find line of code by regex1, and if following line matches regex2, then
 # append supplied code after that line
 ############################################################################>

Function AppendCodeAfterTwoMatchingLines([string]$csFile, [string]$regex1, [string]$regex2, [string]$codeToAppend, [string]$unlessALineMatchesThisRegex) 
{
    $contents = (Get-Content $csFile)

    if($contents | ?{$_ -match $unlessALineMatchesThisRegex}) {
        Write-Verbose "### File '$csFile' already matches '$unlessALineMatchesThisRegex', no need to change"
        # already matches, skip it
    } else {
        [bool]$foundMatch = $false
        for($index = 1; $index -lt $contents.Length; $index++) {

            if(    ($contents[$index - 1] -match $regex1) -and ($contents[$index] -match $regex2) ) {
                $contents[$index] = $contents[$index] + "`r`n" + $codeToAppend
                $foundMatch = $true
                break
            }
        }
        if($foundMatch -eq $false) {
            $msg = @"
AppendCodeAfterTwoMatchingLines could not find patterns '$regex1' followed by '$regex2' in file '$csFile'
CALLSTACK:$(Get-PSCallStack | Out-String)
"@

            throw $msg
        }
        $contents | Set-Content $csFile
    }
}





<############################################################################
 # Cleanse multiline string for purposes of string comparison for unit testing
 #
 # Remove leading and trailing whitespace from each line
 # Collapse all remaining contiguous spaces/tabs into single space
 # Ensure all newlines are \r\n not just \n
 # Remove all blank lines
 ############################################################################>

Function Cleanse-String() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$inputStr
    )

    [string[]]$lines = (($inputStr -split '[\r\n]') |? {$_} )
    [string]$result = ""
    [int] $index = -1 | Out-Null
    for($index = 0; $index -lt $lines.length; $index++) {
        $line = $lines[$index]
        # remove leading space
        $line = $line -replace '^\s+', ''
        # remove trailing space
        $line = $line -replace '\s+$', ''
        # collapse internal space
        $line = $line -replace '\s+', ' '

        if($line.length -gt 0) {
            if($result -eq "") {
                $result = $line
            } else {
                $result = $result + "`r`n$line"
            }
        }
    }
    return $result
}




<############################################################################
 # Convert strings like appleSauce or AppleSauce or APPLE_SAUCE to apple-sauce
 ############################################################################>

Function ConvertTo-KebabCase() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$str
    )
    if([string]::IsNullOrWhitespace($str) -or ($str -match " ")) {
        throw "Cannot convert '$str' to kebab case, invalid string"
    } else {
        [string]$result = ($str -creplace "([a-z])([A-Z])","`$1_`$2" -creplace "-","_" -split "_" | % { $_.ToLower() }) -join "-"
        return $result 
    }
}

<############################################################################
 # Convert strings like appleSauce or AppleSauce or apple-sauce to APPLE_SAUCE
 ############################################################################>

Function ConvertTo-AllCapsCase() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$str
    )
    if([string]::IsNullOrWhitespace($str) -or ($str -match " ")) {
        throw "Cannot convert '$str' to all caps case, invalid string"
    } else {
        [string]$result = ($str -creplace "([a-z])([A-Z])","`$1_`$2" -creplace "-","_" -split "_" | % { $_.ToUpper() }) -join "_"
        return $result 
    }
}

<############################################################################
 # Convert strings like AppleSauce or apple-sauce or APPLE_SAUCE to appleSauce
 ############################################################################>

Function ConvertTo-LowerCamelCase() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$str
    )
    if([string]::IsNullOrWhitespace($str) -or ($str -match " ")) {
        throw "Cannot convert '$str' to lower camel case, invalid string"
    } else {
        [string]$result = ($str -creplace "([a-z])([A-Z])","`$1_`$2" -creplace "-","_" -split "_" | % { $_.substring(0, 1).ToUpper() + $_.substring(1).ToLower() }) -join ""
        $result = $result.substring(0,1).ToLower() + $result.substring(1)    
        return $result 
    }
}
    
<############################################################################
 # Convert strings like appleSauce or apple-sauce or APPLE_SAUCE to AppleSauce
 ############################################################################>

Function ConvertTo-CapitalCamelCase() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$str
    )
    if([string]::IsNullOrWhitespace($str) -or ($str -match " ")) {
        throw "Cannot convert '$str' to capital camel case, invalid string"
    } else {
        [string]$result = ($str -creplace "([a-z])([A-Z])","`$1_`$2" -creplace "-","_" -split "_" | % { $_.substring(0, 1).ToUpper() + $_.substring(1).ToLower() }) -join ""
        return $result 
    }
}

<############################################################################
 # Convert strings like appleSauce or apple-sauce or APPLE_SAUCE or AppleSauce
 # to "Apple Sauce"
 ############################################################################>

Function ConvertTo-TitleCase() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)][string]$str
    )
    if([string]::IsNullOrWhitespace($str) -or ($str -match " ")) {
        throw "Cannot convert '$str' to title case, invalid string"
    } else {
        [string]$result = ($str -creplace "([a-z])([A-Z])","`$1_`$2" -creplace "-","_" -split "_" | % { $_.substring(0, 1).ToUpper() + $_.substring(1).ToLower() }) -join " "
        return $result 
    }
}


<#
 # Given a variable that is either a string or an array of strings,
 # return an array of strings where all embedded newlines (either CR
 # or CRLF) get split out into separate lines, blank lines are removed,
 # each line is trimmed, and all consecutive whitespace (other than
 # leading or trailing) is combined into a single space.
 #>

Function ConvertTo-CleanStringArray() {
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeline)]$myData
    )


    begin {
        [string[]]$lines = @()
    }
    process {
        foreach($line in $myData) {
            $line -split "`r?`n" | % { $lines += $_ }
        }
    }
    # Because I want all the input lines from file, pipeline, or string array command line argument.
    end {
        [string[]]$result = @()
        foreach($line in $lines) {
            # remove leading space
            $line = $line -replace '^\s+', ''
            # remove trailing space
            $line = $line -replace '\s+$', ''
            # collapse internal space
            $line = $line -replace '\s+', ' '
            # add all nonblank lines
            if($line.length -gt 0) {
                $result += $line
            }
        }
        return $result
    }
}

<#
.SYNOPSIS
    Find regex pattern, possibly multi-line, in a file, and insert/append/replace with one or more
    lines.
.DESCRIPTION
    Will attempt to delete existing directory or halt if deletion fails.
.PARAMETER input
    Input string to perform actions on. Also supports pipeline input. Can either be a simple string,
    string with embedded newlines, array of strings, or array of strings some of which have embedded newlines.
    Will handle UNIX or Windows style newlines. If specified do not specify -file parameter.
.PARAMETER file
    Name of file to use as input. If specified, do not use -input or pipeline input. If this parameter
    is supplied, file is changed in place with no backup and no data sent to pipeline. If no path is specified,
    it will look in current directory. If not found it will look in all subdirectories. If one and only one
    file name match is found in subdirectories it will use that file.
.PARAMETER match
    Array of one or more lines, including possible embedded newline characters, that we are trying to match.
    These are all regex unless -simpleMatch specified.
.PARAMETER prependBefore
    If specified and the match succeeds, insert these supplied line or lines before the match lines.
.PARAMETER appendAfter
    If specified and the match succeeds, insert these supplied line or lines after the match lines.
.PARAMETER replaceWith
    If specified and the match succeeds, replace matched lines with these supplied lines.
.PARAMETER fromUrl
    If specified then the match string is actually a URL and use the data from that downloaded URL
.PARAMETER simpleMatch
    If specified will do a simple string match (trimming front and end of input lines) instead of a regex match.
    Also applies to $unlessAlreadyMatches if specified.
.PARAMETER lastRowRepeats
    If specified then assume that the last line of the match pattern repeats indefinitely and we should
    extend the match to include those additional lines
.PARAMETER global
    If true assume match is a single expression with no newlines and not an array, and do a global search
    and replace
# Put in comments about how to use global
.PARAMETER unlessAlreadyMatches
    If the input already matches this regex (or simple match if -simpleMatch specified) then do not make any changes.
    This must be a string not an array
.PARAMETER throwIfNoMatch
    Throw exception if no match found, otherwise take no special action.
.EXAMPLE
.NOTES
    Author: Brian Woelfel
    Date: 2017/10/17
#>

Function Edit-String() {
    [CmdletBinding()]
    Param(
        [Parameter(ParameterSetName='prependFromString', Mandatory=$true, ValueFromPipeline=$true)]
        [Parameter(ParameterSetName='appendFromString', Mandatory=$true, ValueFromPipeline=$true)]
        [Parameter(ParameterSetName='replaceFromString', Mandatory=$true, ValueFromPipeline=$true)]
        [Alias("input")]
        [string[]]$input2,
        
        [Parameter(ParameterSetName='prependFromFile', Mandatory=$true)]
        [Parameter(ParameterSetName='appendFromFile', Mandatory=$true)]
        [Parameter(ParameterSetName='replaceFromFile', Mandatory=$true)]
        [string]$file,
        
        [Parameter(Mandatory=$true)]
        [string[]]$match,

        [Parameter(Mandatory=$true,ParameterSetName='prependFromString')]
        [Parameter(Mandatory=$true,ParameterSetName='prependFromFile')]
        [Alias("prepend")]
        [string[]]$prependBefore,

        [Parameter(Mandatory=$true,ParameterSetName='appendFromString')]
        [Parameter(Mandatory=$true,ParameterSetName='appendFromFile')]
        [Alias("append")]
        [string[]]$appendAfter,

        [Parameter(Mandatory=$true,ParameterSetName='replaceFromString')]
        [Parameter(Mandatory=$true,ParameterSetName='replaceFromFile')]
        [Alias("replace")]
        [string[]]$replaceWith,

        [switch]$fromUrl,

        [switch]$simpleMatch,
        
        [Parameter(ParameterSetName='appendFromString')]
        [Parameter(ParameterSetName='appendFromFile')]
        [Parameter(ParameterSetName='replaceFromString')]
        [Parameter(ParameterSetName='replaceFromFile')]
        [switch]$lastRowRepeats,

        [Parameter(ParameterSetName='replaceFromString')]
        [Parameter(ParameterSetName='replaceFromFile')]
        [switch]$global,

        [switch]$throwIfNoMatch,

        [string]$unlessAlreadyMatches=""
    )

    begin {
        [string[]]$lines = @()
        [string]$fullPath = $file
    }

    process {
        # If data is supplied through pipeline via "Get-Content myfile.txt | Edit-String ..."
        # or " 'a','b','c' | Edit-String ..." then this process section gets called once
        # per input line. Lines may have embedded newlines, split them out
        foreach($input2Piece in $input2) {
            $input2Piece -split "`r?`n" | % { $lines += $_ }
        }
    }

    # Because I want all the input lines from file, pipeline, or string array command line argument.
    end {

        # Special case. If -global supplied, then $match and $replaceWith must both be one line
        if($global -eq $true) {
            if( ($match.Length -ne 1) -or ($replaceWith.Length -ne 1) ) {
                throw "If -global supplied, -match and -replaceWith must both be a single non-blank string"
            }
        }

        # If data is supplied through "Edit-String -file myfile.txt"
        # then ignore all the pipeline stuff above and just load it now into $lines
        [bool]$fileMode = $false
        if(($PsCmdlet.ParameterSetName -eq "prependFromFile") -or ($PsCmdlet.ParameterSetName -eq "appendFromFile") -or ($PsCmdlet.ParameterSetName -eq "replaceFromFile")) {
            Write-Host "Attempt to locate file '$file'"
            $fullPath = Find-FileFromHere $file
            Write-Host "Load content from file '$fullPath'"
            $lines = Get-Content $fullPath
            $fileMode = $true
        }

        [string]$type = ""
        if(($PsCmdlet.ParameterSetName -eq "prependFromString") -or ($PsCmdlet.ParameterSetName -eq "prependFromFile")) { 
            $type = "PREPEND"
        } elseif(($PsCmdlet.ParameterSetName -eq "appendFromString") -or ($PsCmdlet.ParameterSetName -eq "appendFromFile")) { 
            $type = "APPEND"
        } elseif(($PsCmdlet.ParameterSetName -eq "replaceFromString") -or ($PsCmdlet.ParameterSetName -eq "replaceFromFile")) { 
            $type = "REPLACE"
        } else {
            throw "Unknown parameter set $($PsCmdlet.ParameterSetName)"
        }

        Write-Verbose "parameterSetName=$($PsCmdlet.ParameterSetName), lines=$($lines), file=$($file), match=$($match), prepend=$($prependBefore), append=$($appendAfter), replace=$($replaceWith), fromUrl=$($fromUrl), simpleMatch=$($simpleMatch), lastRowRepeats=$($lastRowRepeats), throwIfNoMatch=$($throwIfNoMatch), unlessAlreadyMatches=$($unlessAlreadyMatches), type=$($type)"    

        [bool]$keepGoing = $true
        if(-not [string]::IsNullOrWhitespace($unlessAlreadyMatches)) {
            if($simpleMatch -eq $true) {
                # match without regex
                if($lines.Trim() -eq $unlessAlreadyMatches.Trim()) {
                    Write-Verbose "Already matches '$unlessAlreadyMatches', do not perform any changes"
                    $keepGoing = $false
                }
            } else {
                # match using regex
                if($lines -match $unlessAlreadyMatches) {
                    Write-Verbose "Already matches '$unlessAlreadyMatches', do not perform any changes"
                    $keepGoing = $false
                }
            }
        }

        if($keepGoing -eq $true) {
            if($global -eq $true) {
                if($simpleMatch -eq $true) {
                    $lineMatch = ($lines -match [regex]::escape($match))
            
                    # simple global search/replace no regex
                    $lines = $lines -replace [regex]::escape($match),$replaceWith
                } else {
                    $lineMatch = ($lines -match $match)
            
                    # simple global search/replace with regex
                    $lines = $lines -replace $match,$replaceWith
                }
            } else {
                # multiline match
                [int]$matchLineCount = $match.Count
                [int]$lineCount = $lines.Count

                $debugMsg = ""
                if($matchLineCount -le $lineCount) {
                    [int]$lineIndex = 0;
                    while($lineIndex -le ($lineCount - $matchLineCount)) {
                        [string]$line = $lines[$lineIndex]
                        [bool]$lineMatch = $false
                        [int]$offset = 0
                        $debugMsgPrefix = "From line (zero-based) $lineIndex '$line' "
                        for($i = 0; $i -lt $matchLineCount; $i++) {
                            $futureLine = $lines[$lineIndex + $offset]
                            $debugMsg = "$($debugMsgPrefix) looking forward an offset of (zero-based) $($offset) to future line '$($futureLine)' against (zero-based) $($offset) of '$($match[$i])' of $matchLineCount match lines"
                            $lineMatch = CheckOneLine $simpleMatch $futureLine $match[$i]
                            if($lineMatch -eq $false) {
                                Write-Verbose "$($debugMsg): no match"
                                break
                            } else {
                                Write-Verbose "$($debugMsg): match"
                                $offset++
                            }
                        }
                        $additionalMatchedLines = 0
                        $finalMatch = $match[$matchLineCount - 1]
                        if($lineMatch -and $lastRowRepeats -and ($type -ne "PREPEND")) {
                            # We matched, but it's possible that the last line of the pattern
                            # repeats, so keep going
                            while($offset -lt ($lineCount - $lineIndex)) {
                                $futureLine = $lines[$lineIndex + $offset]
                                $debugMsg = "$($debugMsgPrefix) looking forward an offset of (zero-based) $($offset) to future '$($futureLine)' against final repeating match '$($finalMatch)"
                                $extraLineMatch = CheckOneLine $simpleMatch $futureLine $finalMatch
                                if($extraLineMatch -eq $false) {
                                    Write-Verbose "$($debugMsg): no match on extra line"
                                    break
                                } else {
                                    Write-Verbose "$($debugMsg): match"
                                    $additionalMatchedLines++
                                    $offset++
                                }
                            }
                        }

                        if($lineMatch) {
                            if($type -eq "PREPEND") {
                                Write-Verbose "Insert before (zero-based) index $lineIndex '$($lines[$lineIndex])'"
                                $lines[$lineIndex] = [string]::Concat($prependBefore -join "`r`n", "`r`n", $line)
                            } elseif($type -eq "APPEND") {
                                $appendAfterIndex = $lineIndex + $matchLineCount + $additionalMatchedLines - 1
                                Write-Verbose "Append after (zero-based) index $appendAfterIndex '$($lines[$appendAfterIndex])'"
                                $lines[$appendAfterIndex] = [string]::Concat($lines[$appendAfterIndex], "`r`n", $appendAfter -join "`r`n") 
                            } elseif($type -eq "REPLACE") {
                                $maxIndex = $lines.Count - 1
                                $startHead = 0
                                $endHead = $lineIndex - 1
                                $startTail = $lineIndex + $offset 
                                $endTail = $maxIndex

                                Write-Verbose "Replace with original (zero-based) rows $startHead to $endHead then replacement then original (zero-based) rows $startTail to $endTail"
                                
                                if($fromUrl -eq $true) {
                                    Write-Verbose "Downloading replacement text from '$($replaceWith)'"
                                    try {
                                        # Array to string
                                        [string]$url = ($replaceWith -join '')                                
                                        $replaceWith = (New-Object System.Net.WebClient).DownloadString($url)
                                    } catch {
                                        Write-Error "Unable to download replacement text from '$replaceWith' $_"
                                        Exit -1
                                    }
                                }

                                if($lines.Count -eq 1) {
                                    # There's only one line, just replace it
                                    $lines = $replaceWith
                                } elseif( ($endHead -ge 0) -and ($startTail -le $maxIndex) ) {
                                    # Replace in the middle
                                    $lines = $lines[$startHead .. $endHead] + ($replaceWith) + $lines[$startTail .. $endTail]
                                } elseif( $startTail -ge $maxIndex) {
                                    # No tail
                                    $lines = $lines[$startHead .. $endHead] + ($replaceWith) 
                                } else {
                                    # No head
                                    $lines = ($replaceWith) + $lines[$startTail .. $endTail]
                                }
                            }
                            break
                        }
                        $lineIndex++
                    }
                }
            }
        }

        if( ($throwIfNoMatch -eq $true) -and ($lineMatch -eq $false) ) {
            throw "Failed to find matching lines."
        }

        if($fileMode -eq $true) {
            $lines | Out-FileUtf8NoBom $fullPath
        } else {
            $lines 
        }
    }
}

<#
 # Return true if $lineToCheck matches regex $match (if $simpleMatch is true)
 # or if $lineToCheck matches nonregex $match) if ($simpleMatch is false)
 #>

Function CheckOneLine($simpleMatch, $lineToCheck, $match) {
    if($simpleMatch -eq $false) {
        # Attempt full regex match
        if($lineToCheck -match $match) {
            $lineMatch = $true
        } else {
            $lineMatch = $false
        }
    } else {
        # Attempt simple match on substring contains
        if($lineToCheck.Contains($match)) {
            $lineMatch = $true
        } else {
            $lineMatch = $false
        }
    }

    return $lineMatch
}