Skip to content

Instantly share code, notes, and snippets.

@Tzrlk
Created November 28, 2023 02:31
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 Tzrlk/fc8e0a1c7a3eb30bda600d355004bc0f to your computer and use it in GitHub Desktop.
Save Tzrlk/fc8e0a1c7a3eb30bda600d355004bc0f to your computer and use it in GitHub Desktop.
Powershell Invoke-Build script to save Invoke-ScriptAnalyzer results to checkstyle.xml format
using namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
# Synopsis: Statically analyses the codebase for badness.
Add-BuildTask lint -Inputs ${Sources} -Outputs "${PSScriptRoot}/checkstyle.xml" {
Import-Module PSScriptAnalyzer
# Run the linter, producing a list of result objects.
$Results = Invoke-ScriptAnalyzer `
-Path "${PSScriptRoot}" `
-CustomRulePath "${PSScriptRoot}/.lint-rules" `
-RecurseCustomRulePath `
-IncludeDefaultRules `
-ReportSummary `
-Recurse
# Get the total count of errors in the results.
$ErrorCount = ${Results} `
| Where-Object { ${_}.Severity -eq [DiagnosticSeverity]::Error } `
| Measure-Object
# Cannot have any errors at all
Assert-Build `
-Condition ( ${ErrorCount}.Count -eq 0 ) `
-Message "Cannot have any linting errors. $(${ErrorCount}.Count) errors found."
# Group results again by file to work better in the report.
$FileResults = ${Results} | Group-Object `
-Property ScriptName `
-AsHashTable
# Write a checkstyle-formatted report to disk.
# https://github.com/PowerShell/PSScriptAnalyzer/issues/1296
$XmlWriter = New-Object System.Xml.XmlTextWriter("${Outputs}", $Null)
try {
$XmlWriter.Formatting = 'Indented'
$XmlWriter.Indentation = 1
$XmlWriter.IndentChar = "`t"
$XmlWriter.WriteStartDocument()
$XmlWriter.WriteStartElement("checkstyle")
$XmlWriter.WriteAttributeString("version", "1.0.0")
foreach ($FileResult in (${FileResults} ?? @{}).GetEnumerator()) {
$XmlWriter.WriteStartElement("file")
$XmlWriter.WriteAttributeString("name", ${FileResult}.Name)
foreach ($Result in ${FileResult}.Value) {
$XmlWriter.WriteStartElement("error")
$XmlWriter.WriteAttributeString("line", ${Result}.Line)
$XmlWriter.WriteAttributeString("column", ${Result}.Column)
$XmlWriter.WriteAttributeString("severity", ${Result}.Severity)
$XmlWriter.WriteAttributeString("message", ${Result}.Message)
$XmlWriter.WriteAttributeString("source", ${Result}.RuleName)
$XmlWriter.WriteEndElement()
}
$XmlWriter.WriteEndElement()
}
$XmlWriter.WriteEndElement()
$XmlWriter.WriteEndDocument()
$XmlWriter.Flush()
} finally {
$XmlWriter.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment