Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | 3x 3x 3x 3x 3x 3x 3x 7x 28x 7x 7x 28x 24x 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 3x 3x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 3x 3x 3x 3x 3x 3x 2x 1x 3x 3x 3x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import fs from 'fs/promises';
import path from 'path';
import { Command } from 'commander';
import { bomAgent, BomAgentResult } from './bomAgent';
import { lintAgent, LintAgentResult } from './lintAgent';
import { securityAgent, SecurityAgentResult } from './securityAgent';
import { testAgent, TestAgentResult } from './testAgent';
// Function to generate a synthetic coverage paragraph
export function paragrapheCoverage(
lines: number,
functions: number,
branches: number,
statements: number,
standard: number = 80
): string {
type Niveau = 'IL Y A DU TRAVAIL' | 'PEUT MIEUX FAIRE' | 'PRESQUE CONFORME' | 'OK';
const qualif = (p: number): Niveau =>
p < 50 ? 'IL Y A DU TRAVAIL'
: p < 70 ? 'PEUT MIEUX FAIRE'
: p < standard ? 'PRESQUE CONFORME'
: 'OK';
const indics = {
lignes: { val: lines, niv: qualif(lines) },
fonctions: { val: functions, niv: qualif(functions) },
branches: { val: branches, niv: qualif(branches) },
instructions: { val: statements, niv: qualif(statements) },
};
const ordre: Record<Niveau, number> = {
'IL Y A DU TRAVAIL': 0,
'PEUT MIEUX FAIRE': 1,
'PRESQUE CONFORME': 2,
'OK': 3,
};
const global = (Object.values(indics).map(o => o.niv).sort((a, b) => ordre[a] - ordre[b])[0]) as Niveau;
const [faibleCle, faible] = Object.entries(indics).sort(([, a], [, b]) => a.val - b.val)[0];
const intro: Record<Niveau, string> = {
'IL Y A DU TRAVAIL': 'La couverture globale des tests est très insuffisante.',
'PEUT MIEUX FAIRE': 'Il existe des tests dans l’application, mais la couverture globale reste à améliorer.',
'PRESQUE CONFORME': 'La couverture globale s’approche du seuil visé.',
'OK': 'La couverture globale est conforme au standard en vigueur.',
};
const action: Record<Niveau, string> = {
'IL Y A DU TRAVAIL': 'Une action urgente est requise pour réduire les zones non testées.',
'PEUT MIEUX FAIRE': 'Des efforts complémentaires sont recommandés pour atteindre le niveau attendu.',
'PRESQUE CONFORME': 'Un effort résiduel permettra d’atteindre la conformité totale.',
'OK': 'Il est conseillé de maintenir ce niveau dans la durée.',
};
return [
intro[global],
`La couverture par ${faibleCle} est actuellement la plus basse avec ${faible.val} %.`,
action[global],
`Indicateur de test : ${global}.`,
].join(' ');
}
/**
* Génère un graphique SVG simple pour les métriques de coverage
*/
function generateCoverageChart(metrics: { lines: number; functions: number; branches: number; statements: number }): string {
// Chart size slightly enlarged again (increased width)
const svgWidth = 240;
const svgHeight = 130;
// margins adjusted for new size
const margin = { top: 12, right: 12, bottom: 22, left: 12 };
const barGap = 12;
const barCount = 4;
const rawBarWidth = (svgWidth - margin.left - margin.right - barGap * (barCount - 1)) / barCount;
// half-thickness bars
const barWidth = rawBarWidth / 2;
const names = ['Lines', 'Functions', 'Branches', 'Statements'];
const values = [metrics.lines, metrics.functions, metrics.branches, metrics.statements];
let svg = `<svg width="${svgWidth}" height="${svgHeight}" xmlns="http://www.w3.org/2000/svg">`;
svg += `<style>
.label { font-family: sans-serif; font-size: 12px; fill: #000; text-anchor: middle; }
</style>`;
const threshold = 80;
const maxBarHeight = svgHeight - margin.top - margin.bottom;
// Draw bars
for (let i = 0; i < barCount; i++) {
// Center bars in their slot by halving remaining space
const slotWidth = rawBarWidth + barGap;
const x = margin.left + i * slotWidth + (slotWidth - barWidth) / 2;
const barHeight = (values[i] / 100) * maxBarHeight;
const y = margin.top + (maxBarHeight - barHeight);
// Color red if below threshold
const fillColor = values[i] < threshold ? '#fdd3cb' : '#a7d2ea';
svg += `<rect x="${x}" y="${y}" width="${barWidth}" height="${barHeight}" fill="${fillColor}"/>`;
svg += `<text class="label" x="${x + barWidth/2}" y="${y - 5}">${values[i]}%</text>`;
svg += `<text class="label" x="${x + barWidth/2}" y="${svgHeight - margin.bottom + 15}">${names[i]}</text>`;
}
// Draw threshold line at 80%
const threshY = margin.top + (maxBarHeight - (threshold / 100) * maxBarHeight);
svg += `<line x1="${margin.left}" x2="${svgWidth - margin.right}" y1="${threshY}" y2="${threshY}" stroke="#e74c3c" stroke-dasharray="4,4"/>`;
// Add threshold label vertically along the y-axis (shifted lower and right)
const labelX = margin.left + 10;
// Descend le label de 45px (35px + 10px supplémentaire)
const labelY = threshY + 45;
svg += `<text x="${labelX}" y="${labelY}" fill="#e74c3c" font-family="sans-serif" font-size="12" transform="rotate(-90 ${labelX} ${labelY})" text-anchor="middle">Coverage required</text>`;
svg += '</svg>';
return svg;
}
export interface FullAgentOptions {}
export interface FullAgentResult {
test: TestAgentResult;
lint: LintAgentResult;
security: SecurityAgentResult;
bom: BomAgentResult;
report: string;
}
/**
* Ordonne et exécute tous les agents de quantimétrie pour générer
* un rapport complet en markdown.
*/
export async function fullAgent(
opts?: FullAgentOptions,
): Promise<FullAgentResult> {
const test = await testAgent(opts);
const lint = await lintAgent(opts);
const security = await securityAgent(opts);
const bom = await bomAgent(opts);
// Construction d'un rapport au format Markdown
let report = '# Rapport Qualimétrie\n\n';
report += '## 1. Tests & Couverture\n\n';
if (test.success && test.summary && test.metrics) {
// Test summary as narrative sentence with bold numbers
report += `Les tests ont été exécutés pour un total de **${test.summary.total}** tests, dont **${test.summary.passed}** réussis et **${test.summary.failed}** échoués, en **${test.summary.duration}**.\n\n`;
// Coverage metrics as cards with analysis
report += '<div class="coverage-summary-grid">\n';
report += '<div class="coverage-cards">\n';
report += `<div class="card"><div class="card-header"><div class="card-icon">${Math.round(test.metrics.lines)}%</div><div class="card-title">Lines covered</div></div><div class="card-description">ceci est les contenu de la card</div></div>\n`;
report += `<div class="card"><div class="card-header"><div class="card-icon">${Math.round(test.metrics.functions)}%</div><div class="card-title">Functions covered</div></div><div class="card-description">ceci est les contenu de la card</div></div>\n`;
report += `<div class="card"><div class="card-header"><div class="card-icon">${Math.round(test.metrics.branches)}%</div><div class="card-title">Branches covered</div></div><div class="card-description">ceci est les contenu de la card</div></div>\n`;
report += `<div class="card"><div class="card-header"><div class="card-icon">${Math.round(test.metrics.statements)}%</div><div class="card-title">Statements covered</div></div><div class="card-description">ceci est les contenu de la card</div></div>\n`;
report += '</div>\n';
report += '<div class="coverage-analysis">\n';
report += '<div class="coverage-pretitle">Rapport</div>\n';
report += '<h2 style="margin-top:0">Analyse</h2>\n';
// Synthèse de la couverture sous forme de bloc HTML
report += paragrapheCoverage(
Math.round(test.metrics.lines),
Math.round(test.metrics.functions),
Math.round(test.metrics.branches),
Math.round(test.metrics.statements)
) + '\n\n';
// Graphe de couverture
report += '<div class="chart-container">' + generateCoverageChart({
lines: Math.round(test.metrics.lines),
functions: Math.round(test.metrics.functions),
branches: Math.round(test.metrics.branches),
statements: Math.round(test.metrics.statements),
}) + '</div>\n\n';
report += '</div>\n';
report += '</div>\n\n';
} else {
report += 'Erreur lors de l\'exécution des tests ou de la collecte de la couverture.\n\n';
}
report += '## 2. Qualité de code (ESLint)\n\n';
if (lint.metrics) {
report += `- Erreurs: **${lint.metrics.errors}**\n`;
report += `- Warnings: **${lint.metrics.warnings}**\n`;
report += `- Fichiers analysés: **${lint.metrics.files}**\n`;
report += `- Total problèmes: **${lint.metrics.total}**\n`;
report += `- Problèmes fixables: **${lint.metrics.fixable}**\n\n`;
if (lint.summary) {
report += '**Top fichiers problématiques**\n';
lint.summary.topFiles.forEach(f => {
const rel = path.relative(process.cwd(), f.filePath) || f.filePath;
report += `- ${rel}: ${f.total} problèmes (${f.errors} erreurs, ${f.warnings} avertissements)\n`;
});
report += '\n**Top règles violées**\n';
lint.summary.topRules.forEach(r => {
report += `- ${r.ruleId}: ${r.count} occurrences\n`;
});
report += '\n';
}
if (lint.detailPath) {
report += `> Rapport complet ESLint: ${lint.detailPath}\n\n`;
}
} else {
report += "Erreur lors de l'exécution d'ESLint.\n\n";
}
report += '## 3. Sécurité (Vulnérabilités)\n';
report += '```json\n' + JSON.stringify(security.vulnerabilities, null, 2) + '\n```\n\n';
report += '## 4. Bill Of Materials (Licences)\n\n';
report +=
'Le tableau ci-dessous présente les 50 premières dépendances du Bill of Materials, ' +
'avec leur nom, version et licence.\n\n';
report += '<table style="width:100%; border-collapse: collapse;">\n';
report += '<thead>\n';
report += '<tr style="background-color: #eef5fb;">\n';
report += '<th style="border: 1px solid #ddd; padding: 8px;">Nom</th>\n';
report += '<th style="border: 1px solid #ddd; padding: 8px;">Version</th>\n';
report += '<th style="border: 1px solid #ddd; padding: 8px;">Licence</th>\n';
report += '</tr>\n';
report += '</thead>\n';
report += '<tbody>\n';
bom.packages.slice(0, 50).forEach((pkg, index) => {
const bgStyle = index % 2 === 0 ? 'background-color: #eef5fb;' : '';
report += `<tr style="${bgStyle}">\n`;
report += `<td style="border: 1px solid #ddd; padding: 8px;">${pkg.name}</td>\n`;
report += `<td style="border: 1px solid #ddd; padding: 8px;">${pkg.version}</td>\n`;
report += `<td style="border: 1px solid #ddd; padding: 8px;">${pkg.license}</td>\n`;
report += '</tr>\n';
});
report += '</tbody>\n';
report += '</table>\n\n';
report += 'Liste complète en pièce jointe de ce document.\n\n';
return { test, lint, security, bom, report };
}
export const cli = {
command: 'qualimetrie:full',
description: 'Exécute tous les agents de qualimétrie et génère un rapport (Markdown ou HTML)',
builder: (cmd: Command) =>
cmd
.option('--out <format>', 'Output format: markdown or html', 'markdown')
.option(
'--output <path>',
"Base path (without extension) for report (default: 'report/index')",
'report/index'
),
handler: async (opts: any) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { fullAgent: runFullAgent } = require('./fullAgent');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { markdownHtmlAgent: runMdAgent } = require('../markdownHtmlAgent');
const res = await runFullAgent();
const format = (opts.out || 'markdown').toLowerCase();
const base = opts.output || 'report/index';
let outFile: string;
if (format === 'html') {
outFile = base.endsWith('.html') ? base : `${base}.html`;
} else {
outFile = base.endsWith('.md') ? base : `${base}.md`;
}
const outDir = path.dirname(outFile);
await fs.mkdir(outDir, { recursive: true });
if (format === 'html') {
try {
// Append attachments links for detailed reports
const attachments = `
## Attachments
- [Coverage HTML report](../coverage/lcov-report/index.html)
- [Coverage summary JSON](coverage-summary.json)
- [Jest results JSON](jest-results.json)
- [ESLint report JSON](eslint-report.json)
- [Audit report JSON](audit-report.json)
- [BOM report JSON](bom-report.json)
`;
const html = await runMdAgent({
title: 'Qualimetry Report',
markdown: res.report + attachments,
});
// Write HTML report
await fs.writeFile(outFile, html, 'utf-8');
// Copy detailed JSON reports into report folder
await fs.copyFile(
path.resolve('coverage', 'coverage-summary.json'),
path.join(outDir, 'coverage-summary.json')
);
await fs.copyFile(
path.resolve('jest-results.json'),
path.join(outDir, 'jest-results.json')
);
if (res.lint.detailPath) {
await fs.copyFile(
path.resolve(res.lint.detailPath),
path.join(outDir, path.basename(res.lint.detailPath))
);
}
if (res.security.detailPath) {
await fs.copyFile(
path.resolve(res.security.detailPath),
path.join(outDir, path.basename(res.security.detailPath))
);
}
// Write BOM details
await fs.writeFile(
path.join(outDir, 'bom-report.json'),
JSON.stringify(res.bom.packages, null, 2),
'utf-8'
);
console.log(`HTML report generated: ${outFile}`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
console.error('Error generating HTML report:', msg);
process.exit(1);
}
} else {
// Markdown output
await fs.writeFile(outFile, res.report, 'utf-8');
console.log(`Markdown report generated: ${outFile}`);
}
},
};
|