conocimientocicd-architecttemplates/7516 B
coverage-gate.ps1
Fichero que /hv:cicd-architect usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
#Requires -Version 5.1
<#
.SYNOPSIS
Gate de cobertura de Ovillo (G7 / R18): lee Cobertura u OpenCover y compara con umbrales de linea y rama.
.DESCRIPTION
Sustituye a cualquier herramienta externa de gate: cero dependencias (solo PowerShell 5.1+ o pwsh), ASCII puro,
corre igual en un agente Windows de Azure DevOps y en un runner Linux de GitHub Actions.
- Busca ficheros *cobertura*.xml y *opencover*.xml bajo -Path (o usa el fichero indicado).
- Con -Latest toma solo el mas reciente (agentes self-hosted cuyo temp persiste entre builds).
Sin -Latest agrega todos los encontrados (varios proyectos de test = una sola cifra).
- Compara linea y rama con -ThresholdLine / -ThresholdBranch.
- -Mode warn (default, WARN-first): avisa y sale 0. -Mode block: sale 3 si algun umbral no se cumple.
- Sin ficheros: aviso "gate OMITIDO" y exit 0 (nunca tumba un build por falta de cobertura).
- Emite anotaciones nativas: ##vso[task.logissue] en Azure DevOps (TF_BUILD), ::warning::/::error:: y
GITHUB_STEP_SUMMARY en GitHub Actions. Con -SummaryJson escribe un resumen para otros pasos.
Lo materializa /cicd-init en ops/cicd/scripts/coverage-gate.ps1; lo invocan steps/coverage-gate.yml (Azure)
y la composite action .github/actions/coverage-gate (GitHub). Ovillo cicd-architect coverage-gate.
.PARAMETER Path Fichero XML o directorio donde buscar (recursivo). Default: directorio actual.
.PARAMETER ThresholdLine Cobertura de lineas minima en %. Default 70.
.PARAMETER ThresholdBranch Cobertura de ramas minima en %. Default 60.
.PARAMETER Mode warn (avisa, exit 0) | block (exit 3 si incumple). Default warn.
.PARAMETER Latest Usar solo el fichero mas reciente en vez de agregar todos.
.PARAMETER SummaryJson Ruta donde escribir el resumen JSON (opcional).
.OUTPUTS
exit 0 = cumple, o incumple en modo warn, o sin ficheros (omitido) | exit 3 = incumple en modo block | exit 2 = XML ilegible
#>
[CmdletBinding()]
param(
[string] $Path = '.',
[double] $ThresholdLine = 70,
[double] $ThresholdBranch = 60,
[ValidateSet('warn', 'block')] [string] $Mode = 'warn',
[switch] $Latest,
[string] $SummaryJson = ''
)
$ErrorActionPreference = 'Stop'
$isAzure = [bool]$env:TF_BUILD
$isGitHub = [bool]$env:GITHUB_ACTIONS
function Write-Note([string] $Level, [string] $Msg) {
# Anotacion nativa de la plataforma + linea normal (los logs se leen igual en ambas)
if ($isAzure) {
$t = if ($Level -eq 'error') { 'error' } else { 'warning' }
Write-Host "##vso[task.logissue type=$t]$Msg"
} elseif ($isGitHub) {
Write-Host "::$Level::$Msg"
}
Write-Host "G7: $Msg"
}
# --- 1. Localizar ficheros ---
$files = @()
if (Test-Path -LiteralPath $Path -PathType Leaf) {
$files = @(Get-Item -LiteralPath $Path)
} elseif (Test-Path -LiteralPath $Path -PathType Container) {
$files = @(Get-ChildItem -LiteralPath $Path -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match 'cobertura.*\.xml$|opencover.*\.xml$' } |
Sort-Object LastWriteTime -Descending)
if ($Latest -and $files.Count -gt 1) { $files = @($files[0]) }
}
if ($files.Count -eq 0) {
Write-Note 'warning' "no se encontro XML de cobertura (Cobertura/OpenCover) en '$Path' -> gate OMITIDO (no bloquea)."
exit 0
}
# --- 2. Agregar contadores ---
$inv = [System.Globalization.CultureInfo]::InvariantCulture
$linesCovered = 0.0; $linesValid = 0.0; $branchesCovered = 0.0; $branchesValid = 0.0
$rateLine = @(); $rateBranch = @(); $used = @()
foreach ($f in $files) {
try { [xml] $doc = Get-Content -LiteralPath $f.FullName -Raw } catch { Write-Note 'error' "XML ilegible: $($f.FullName)"; exit 2 }
if ($doc.coverage) {
# Cobertura (coverlet): line-rate/branch-rate son ratios 0..1; los contadores absolutos pueden faltar
$c = $doc.coverage
$lc = $c.GetAttribute('lines-covered'); $lv = $c.GetAttribute('lines-valid')
$bc = $c.GetAttribute('branches-covered'); $bv = $c.GetAttribute('branches-valid')
if ($lv -and [double]::Parse($lv, $inv) -gt 0) {
$linesCovered += [double]::Parse($lc, $inv); $linesValid += [double]::Parse($lv, $inv)
if ($bv) { $branchesCovered += [double]::Parse($bc, $inv); $branchesValid += [double]::Parse($bv, $inv) }
} else {
$rateLine += [double]::Parse($c.GetAttribute('line-rate'), $inv)
$br = $c.GetAttribute('branch-rate'); if ($br) { $rateBranch += [double]::Parse($br, $inv) }
}
$used += "$($f.Name) (cobertura)"
} elseif ($doc.CoverageSession) {
# OpenCover: Summary con puntos de secuencia y de rama
$s = $doc.CoverageSession.Summary
$linesCovered += [double]::Parse($s.GetAttribute('visitedSequencePoints'), $inv)
$linesValid += [double]::Parse($s.GetAttribute('numSequencePoints'), $inv)
$branchesCovered += [double]::Parse($s.GetAttribute('visitedBranchPoints'), $inv)
$branchesValid += [double]::Parse($s.GetAttribute('numBranchPoints'), $inv)
$used += "$($f.Name) (opencover)"
} else {
Write-Note 'warning' "formato no reconocido, se ignora: $($f.FullName)"
}
}
if ($used.Count -eq 0) { Write-Note 'warning' "ningun fichero con formato Cobertura/OpenCover -> gate OMITIDO."; exit 0 }
function Pct([double] $num, [double] $den, [double[]] $rates) {
if ($den -gt 0) { return [math]::Round(100.0 * $num / $den, 1) }
if ($rates.Count -gt 0) { return [math]::Round(100.0 * (($rates | Measure-Object -Average).Average), 1) }
return $null
}
$line = Pct $linesCovered $linesValid $rateLine
$branch = Pct $branchesCovered $branchesValid $rateBranch
# --- 3. Evaluar ---
$fails = @()
if ($null -ne $line -and $line -lt $ThresholdLine) { $fails += "linea $line% < $ThresholdLine%" }
if ($null -ne $branch -and $branch -lt $ThresholdBranch) { $fails += "rama $branch% < $ThresholdBranch%" }
$lineTxt = if ($null -ne $line) { "$line%" } else { 'n/d' }
$branchTxt = if ($null -ne $branch) { "$branch%" } else { 'n/d' }
$resumen = "cobertura linea=$lineTxt rama=$branchTxt | umbral linea>=$ThresholdLine% rama>=$ThresholdBranch% | ficheros: $($used.Count) ($($used -join ', '))"
Write-Host "G7: $resumen"
if ($isGitHub -and $env:GITHUB_STEP_SUMMARY) {
$estado = if ($fails.Count -eq 0) { 'OK' } elseif ($Mode -eq 'block') { 'BLOQUEA' } else { 'AVISO' }
@("### Coverage gate (G7): $estado", '', '| Metrica | Valor | Umbral |', '|---|---|---|',
"| Lineas | $lineTxt | >= $ThresholdLine% |", "| Ramas | $branchTxt | >= $ThresholdBranch% |", '',
"Ficheros: $($used -join ', ')") | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
}
if ($SummaryJson) {
$obj = [ordered]@{ line = $line; branch = $branch; thresholdLine = $ThresholdLine; thresholdBranch = $ThresholdBranch
passed = ($fails.Count -eq 0); mode = $Mode; files = $used }
[System.IO.File]::WriteAllText($SummaryJson, ($obj | ConvertTo-Json -Depth 4), (New-Object System.Text.UTF8Encoding($false)))
}
if ($fails.Count -eq 0) { Write-Host "G7: cobertura dentro del umbral."; exit 0 }
if ($Mode -eq 'block') {
Write-Note 'error' "cobertura por debajo del umbral ($($fails -join '; ')). BLOQUEA (mode=block)."
exit 3
}
Write-Note 'warning' "cobertura por debajo del umbral ($($fails -join '; ')) -> AVISO (WARN-first, no bloquea; politica hooks.policy)."
exit 0