Skip to content

Instantly share code, notes, and snippets.

@EricRohlfs
Created June 17, 2021 20:48
Show Gist options
  • Save EricRohlfs/3f22888274139907bba6d01fd0f222a7 to your computer and use it in GitHub Desktop.
Save EricRohlfs/3f22888274139907bba6d01fd0f222a7 to your computer and use it in GitHub Desktop.
param($path, $env)
#note: the metrics.exe is managed in the nuget package file for this project
#note: create and use a separate .sln file with only the projects that need scanning. Exclude test projects etc.
# run local command: .\"Deployment Scripts\generate_code_metrics.ps1" "E:\code\ESSO"
$metrics_exe = "$path\packages\Microsoft.CodeAnalysis.Metrics.3.3.0\Metrics\Metrics.exe"
$sln_file = "$path\CodeMetrics.sln"
$metricsHtmlFile = "$path\codeMetrics.html"
$metricsXmlFile = "$path\codeMetrics.xml"
$deploy = "$path\deploy"
$codeMetricsZip = "$deploy\codeMetrics.zip"
#remove old files
Remove-Item $metricsXmlFile -Force -ErrorAction 'SilentlyContinue'
Remove-Item $metricsHtmlFile -Force -ErrorAction 'SilentlyContinue'
Remove-Item $codeMetricsZip -Force -ErrorAction 'SilentlyContinue'
# run the code metrics nuget tool
$cmd = "$metrics_exe /s:$sln_file /o:$metricsXmlFile"
Invoke-Expression $cmd
#extract data from the code metrics output tool
$xml = [xml](Get-Content $metricsXmlFile)
$properties = "MaintainabilityIndex", "CyclomaticComplexity", "ClassCoupling","DepthOfInheritance","SourceLines", "ExecutableLines"
$metricsList = @()
foreach($assembly in $xml.SelectNodes("//Assembly")){
[hashtable]$info = @{Name = $assembly.Name.Split(',')[0]}
foreach($property in $properties){
$info.add($property, $assembly.SelectSingleNode("./Metrics/Metric[@Name='$property']").Value)
}
$metricsList += New-Object PSObject -Property $info
}
$columnNames = ,"Name" + $properties
#make the html table
$tableStr = $metricsList | ConvertTo-Html -Property $columnNames -Fragment #| Out-File -FilePath $metricsHtmlFile
#useful for debugging, the fragment returns different html
function WriteXmlToScreen ([xml]$xml)
{
$StringWriter = New-Object System.IO.StringWriter;
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter;
$XmlWriter.Formatting = "indented";
$xml.WriteTo($XmlWriter);
$XmlWriter.Flush();
$StringWriter.Flush();
Write-Output $StringWriter.ToString();
}
$table = [xml]$tableStr
#WriteXmlToScreen($table)
# for the table headers convert CapWords to ProperCase
foreach($th in $table.SelectNodes("//th")){
$th.InnerText = $th.InnerText -creplace '([A-Z])', ' $1'
}
$table.Save($metricsHtmlFile)
$compress = @{
DestinationPath = $codeMetricsZip
Path = $metricsXmlFile, $metricsHtmlFile
CompressionLevel = "Optimal"
}
New-Item -ItemType directory -Path "$path\deploy" -ErrorAction 'SilentlyContinue'
Compress-Archive @compress
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment