Public/PsStrUtil.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533

<############################################################################
 # 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.
.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
.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 = @()
    }

    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-Verbose "Load content from file '$file'"
            $lines = Get-Content $file
            $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($lines -match $unlessAlreadyMatches) {
                Write-Verbose "Already matches '$unlessAlreadyMatches', do not perform any changes"
                $keepGoing = $false
            }
            # TODO -simpleMatch case
        }

        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 $file
        } else {
            $lines 
        }
    }
}


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
}