1

How would I write a script that will search my code files for key phrases (like "fit(" in a jasmine unit test) and throw an exception if it finds one. I don't mind supplying a top folder, but it should search through subfolders. Bonus points if I can pass it the key phrases in an array. I'm also ok with installing a node package to facilitate.

I have a script in my package json file I use for "checking in" files. It builds all, runs all tests, stages files and then commits them. I'd like to add this at the beginning, and exit (not build -> test, etc) if a forbidden phrase is found. (debugging flags like fit, deprecated methods maybe).

"commit-all": "ng build core-library --prod && ng build --prod && echo Executing tests && ng test --browsers ChromeHeadless --no-watch --codeCoverage=false && git checkout tsconfig.json && git checkout src/environments/environment.ts && git add . && git commit -m "
Steve Wash
  • 986
  • 4
  • 23
  • 50

1 Answers1

1

You can combine the Get-ChildItem, Select-String, and ForEach-Object cmdlets as follows:

$dir = '...' # specify the directory whose subtree to search.
Get-ChildItem $dir -Recurse -File -Filter *.ps1 | 
  Select-String 'fit(', 'fun(' -List | 
    ForEach-Object { Throw "Phrase found: $($_ | Out-String)" }

If you package the above as a script, using Throw will make your script report an exit code of 1.

Alternatively, if you want to find and report all matches before reporting an error, omit the ForEach-Object call, collect all matches with $matchesFound = Get-ChildItem ... and throw with them, or use Write-Error and manually call exit 1.

To invoke the script via the CLI, use:

# PowerShell [Core] executable shown; use powershell.exe for Windows PowerShell
pwsh -NoProfile -File YourScript.ps1

Note: Sadly, the PowerShell CLI unexpectedly reports errors via stdout, and errors messages are noisy and span multiple lines in Windows PowerShell - see this answer for a workaround and background information.

mklement0
  • 382,024
  • 64
  • 607
  • 775