Skip to content

Instantly share code, notes, and snippets.

@theunrepentantgeek
Created April 5, 2018 19:49
Show Gist options
  • Save theunrepentantgeek/dd59e646b5f120308e75938bf012398c to your computer and use it in GitHub Desktop.
Save theunrepentantgeek/dd59e646b5f120308e75938bf012398c to your computer and use it in GitHub Desktop.
PowerShell script to burst a C# source file containing many classes/interfaces/etc into separate files, each containing one thing
#
# Split a C# source file containing many classes, interfaces, etc, into one file per item
#
param(
# Specify the source C# file that should be burst into separate components
[Parameter(Mandatory=$true)]
[string]
$sourceFile,
# Specify the output folder for all the separated pieces
[Parameter(Mandatory=$true)]
[string]
$outFolder
)
function Write-Info($message) {
$now = get-date -Format "HH:mm:ss.fff"
Write-Host "[info] $now $message" -ForegroundColor White
}
function Write-Detail($message) {
$now = get-date -Format "HH:mm:ss.fff"
Write-Host "[detl] $now $message" -ForegroundColor Blue
}
function FindPriorBlankLine($line) {
while ($content[$line].Trim() -ne "") {
$line--
}
$line
}
# Extract a single slice from the file
function Burst-File($name, $start, $finish) {
$outFile = "$outFolder\$name.cs"
Write-Info "Bursting into $outFile"
$fileContent = $content[0..$headerEnds] + $content[$start..$finish] + $content[$footerStarts..$content.Length]
set-content $outFile $fileContent
}
Write-Info "Output folder is $outFolder"
Write-Info "Reading source file $sourceFile"
$content = get-content $sourceFile
Write-Detail "Found $($content.Length) lines."
# Work out where each component's scope starts
# (Name is found from the previous line)
$breaks = 0..($content.Length) | Where { $content[$_] -eq " {" }
$headerEnds = FindPriorBlankLine($breaks[0])
$footerStarts = 0..($content.Length) | Where { $content[$_] -eq " }" } | Select-Object -Last 1
# Make sure the last class is burst
$breaks = $breaks + ($footerStarts+1)
$knownKeywords = "public", "enum", "class", "partial", "interface"
$priorStart = $null
$name = $null
foreach($break in $breaks ) {
$start = FindPriorBlankLine($break)
if ($priorStart -ne $null)
{
Burst-File -name $name -start $priorStart -finish $start
}
$priorStart = $start
$name = $content[$break-1].Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries ) | where { $_ -notin $knownKeywords } | Select-Object -First 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment