Skip to content

Instantly share code, notes, and snippets.

@aplocher
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aplocher/01909ad12ff53c93e0ae to your computer and use it in GitHub Desktop.
Save aplocher/01909ad12ff53c93e0ae to your computer and use it in GitHub Desktop.
This is a basic script that helps cleanup a series of unused constants in a single file by scanning all *.cs files from a folder to try to find any usages. If not found, it will get commented out and the dev will be able to easily Find/Replace all commented lines with an empty line after verifying that nothing is broken. It uses text parsing, so…
$fileToCheck = 'C:\SourceCode\BitCollectors.WinFormsControls\BitCollectors.WinFormsControls\Common\Win32Native.cs'
$fileToOutput = 'C:\Temp\Win32Native.new.cs'
$fileToBackup = 'C:\Temp\Win32Native.old.cs'
$folderToLookIn = 'C:\SourceCode\BitCollectors.WinFormsControls\BitCollectors.WinFormsControls'
$constRegex = '^\s*[^\/]\s*((internal|private|public|protected)?\s+const\s+[a-zA-Z0-9]+)?\s+([A-Z]{1}[a-zA-Z0-9_]+)\s*\=.*(;|,)\s*$'
$csFiles = Get-ChildItem -Path $folderToLookIn -Recurse -Filter '*.cs'
#region Functions
Function OnLoad {
Clear-Host
Write-Output 'Starting'
$execTime = (Measure-Command { $unusedMembers = GetUnusedMembers } )
Write-Output "GetUnusedMembers: $($execTime.TotalSeconds)"
$null = New-Item -Path 'C:\TEMP\testMembers.txt' -Force
$unusedMembers | Add-Content 'C:\TEMP\testMembers.txt'
$execTime = (Measure-Command { RemoveMembersFromFileAndSave -members $unusedMembers })
Write-Output "RemoveMembersFromFileAndSave: $($execTime.TotalSeconds)"
Write-Output "Done"
}
Function GetParsedMembers {
param(
[System.String]$fileToCheck
)
# 1.27
Get-Content -Path $fileToCheck |
% { if ($_ -cmatch $constRegex) { , $matches[3] } } |
Select-Object -Unique
}
Function GetUnusedMembers {
$csFiles |
Get-Content |
? { $_ -notmatch '^\s*\/(\/|\*)' }|
% { $fileContents += $_ }
GetParsedMembers -fileToCheck $fileToCheck |
Where-Object {
([regex]::matches($fileContents, [regex]::escape($_)).Count) -lt 2
}
}
Function RemoveMembersFromFileAndSave {
param (
[System.String[]]$members
)
Copy-Item $fileToCheck -Destination $fileToBackup -Force
$writer = [System.IO.StreamWriter] $fileToOutput
try {
$reader = [System.IO.File]::OpenText($fileToBackup)
try {
for(;;) {
$line = $reader.ReadLine()
if ($line -eq $null) {
break }
if ($line -cmatch $constRegex -and $members -contains $matches[3]) {
$line = "// -CONST- $($line)" }
$writer.WriteLine($line)
}
} finally {
$reader.Close()
}} finally {
$writer.Close()
}
}
#endregion
#region Entry
OnLoad
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment