All files / istanbul-lib-report/src/reports/text index.ts

100% Statements 166/166
94.73% Branches 90/95
100% Functions 29/29
100% Lines 158/158

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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375                    9x 9x 9x 9x 9x                                     70x       495x   495x 495x 1848x   495x       210x 210x   210x 210x 210x 210x   210x 210x     210x 205x   5x 5x   5x 5x   210x     210x       70x       140x       54x 27x     27x 27x 27x       54x 54x 7x 95x   20x     27x 27x   359x   60x 60x 42x 42x 18x     359x     42x   42x   6x     27x       58x       58x 58x 58x 46x 46x   58x       29x                 20x   58x   20x       20x 20x       20x 20x 20x   20x 20x 20x 20x 20x 20x 20x       10x 10x 10x 10x 10x 10x 10x 10x       13x                           38x 36x 26x                   13x   4x 4x     9x   9x   8x 4x       4x       4x                         29x 29x 29x 29x 4x     25x           29x   55x     70x   29x   29x 29x 29x 29x 29x 29x       29x                           15x   15x 15x   15x 15x 15x 15x 15x 15x       13x 13x 13x 13x 3x 3x 2x   3x 2x   3x   10x 10x   10x 10x   10x 10x 1x 1x 9x 9x 9x 1x       10x 10x 10x 10x       40x 11x   29x 29x                   29x 25x         21x       13x 10x   13x          
/*
 Copyright 2012-2015, Yahoo Inc.
 Copyrights licensed under the New BSD License. See the accompanying LICENSE
 file for terms.
 */
import type { CoverageSummary, Totals } from "@vitest/istanbul-lib-coverage";
 
import type { ContentWriter, Context, ReportBaseOptions, ReportNode } from "../../index";
import ReportBase from "../../report-base";
 
const NAME_COL = 4;
const PCT_COLS = 7;
const MISSING_COL = 17;
const TAB_SIZE = 1;
const DELIM = " | ";
 
/** the four coverage metrics shown in the table */
type MetricKey = "statements" | "branches" | "functions" | "lines";
 
/** options accepted by {@link TextReport} */
export interface TextOptions extends ReportBaseOptions {
  /** the file to write the report to, defaults to the console */
  file?: string | null;
  /** maximum column width of the table, defaults to the terminal width */
  maxCols?: number;
  /** skip rows with no coverage */
  skipEmpty?: boolean;
  /** skip rows with full coverage */
  skipFull?: boolean;
}
 
/** narrows a possibly-`"Unknown"` pct before handing it to `classForPercent` */
function classForPercent(context: Context, type: string, pct: Totals["pct"]): string {
  return context.classForPercent(type, typeof pct === "number" ? pct : NaN);
}
 
function padding(num: number, ch?: string): string {
  let str = "";
  let i;
  ch = ch || " ";
  for (i = 0; i < num; i += 1) {
    str += ch;
  }
  return str;
}
 
function fill(str: string | number, width: number, right?: boolean, tabs?: number): string {
  tabs = tabs || 0;
  str = String(str);
 
  const leadingSpaces = tabs * TAB_SIZE;
  const remaining = width - leadingSpaces;
  const leader = padding(leadingSpaces);
  let fmtStr = "";
 
  Eif (remaining > 0) {
    const strlen = str.length;
    let fillStr;
 
    if (remaining >= strlen) {
      fillStr = padding(remaining - strlen);
    } else {
      fillStr = "...";
      const length = remaining - fillStr.length;
 
      str = str.substring(strlen - length);
      right = true;
    }
    fmtStr = right ? fillStr + str : str + fillStr;
  }
 
  return leader + fmtStr;
}
 
function formatName(name: string, maxCols: number, level?: number): string {
  return fill(name, maxCols, false, level);
}
 
function formatPct(pct: string | number | "Unknown", width?: number): string {
  return fill(pct, width || PCT_COLS, true, 0);
}
 
function nodeMissing(node: ReportNode): string {
  if (node.isSummary()) {
    return "";
  }
 
  const metrics = node.getCoverageSummary()!;
  const isEmpty = metrics.isEmpty();
  const lines = isEmpty ? 0 : metrics.lines.pct;
 
  let coveredLines: [string, number | boolean][];
 
  const fileCoverage = node.getFileCoverage();
  if (lines === 100) {
    const branches = fileCoverage.getBranchCoverageByLine();
    coveredLines = Object.entries(branches).map(([key, { coverage }]) => [key, coverage === 100]);
  } else {
    coveredLines = Object.entries(fileCoverage.getLineCoverage());
  }
 
  let newRange = true;
  const ranges = coveredLines
    .reduce<number[][]>((acum, [line, hit]) => {
      if (hit) newRange = true;
      else {
        const lineNumber = parseInt(line);
        if (newRange) {
          acum.push([lineNumber]);
          newRange = false;
        } else acum[acum.length - 1][1] = lineNumber;
      }
 
      return acum;
    }, [])
    .map((range): number | string => {
      const { length } = range;
 
      if (length === 1) return range[0];
 
      return `${range[0]}-${range[1]}`;
    });
 
  return ([] as (number | string)[]).concat(...ranges).join(",");
}
 
function nodeName(node: ReportNode): string {
  return node.getRelativeName() || "All files";
}
 
function depthFor(node: ReportNode): number {
  let ret = 0;
  let parent = node.getParent();
  while (parent) {
    ret += 1;
    parent = parent.getParent();
  }
  return ret;
}
 
function nullDepthFor(): number {
  return 0;
}
 
function findWidth(
  node: ReportNode,
  context: Context,
  nodeExtractor: (node: ReportNode) => string,
  depthFor: (node: ReportNode) => number = nullDepthFor,
): number {
  let last = 0;
  function compareWidth(node: ReportNode) {
    last = Math.max(last, TAB_SIZE * depthFor(node) + nodeExtractor(node).length);
  }
  const visitor = {
    onSummary: compareWidth,
    onDetail: compareWidth,
  };
  node.visit(context.getVisitor(visitor));
  return last;
}
 
function makeLine(nameWidth: number, missingWidth: number): string {
  const name = padding(nameWidth, "-");
  const pct = padding(PCT_COLS, "-");
  const elements = [];
 
  elements.push(name);
  elements.push(pct);
  elements.push(padding(PCT_COLS + 1, "-"));
  elements.push(pct);
  elements.push(pct);
  elements.push(padding(missingWidth, "-"));
  return elements.join(DELIM.replace(/ /g, "-")) + "-";
}
 
function tableHeader(maxNameCols: number, missingWidth: number): string {
  const elements = [];
  elements.push(formatName("File", maxNameCols, 0));
  elements.push(formatPct("% Stmts"));
  elements.push(formatPct("% Branch", PCT_COLS + 1));
  elements.push(formatPct("% Funcs"));
  elements.push(formatPct("% Lines"));
  elements.push(formatName("Uncovered Line #s", missingWidth));
  return elements.join(DELIM) + " ";
}
 
function isFull(metrics: CoverageSummary): boolean {
  return (
    metrics.statements.pct === 100 &&
    metrics.branches.pct === 100 &&
    metrics.functions.pct === 100 &&
    metrics.lines.pct === 100
  );
}
 
/** why a row is left out of the table, or `null` when it is printed */
function skipReason(
  metrics: CoverageSummary,
  skipEmpty: boolean | undefined,
  skipFull: boolean | undefined,
): "empty" | "full" | null {
  if (skipEmpty && metrics.isEmpty()) return "empty";
  if (skipFull && isFull(metrics)) return "full";
  return null;
}
 
/** counts of skipped files when `skipFull` would leave the table without file rows, otherwise `null` */
function hiddenTableCounts(
  root: ReportNode,
  context: Context,
  skipEmpty: boolean | undefined,
  skipFull: boolean | undefined,
): { full: number; empty: number } | null {
  if (!skipFull) return null;
 
  const counts = { full: 0, empty: 0, shown: 0 };
  root.visit(
    context.getVisitor({
      onDetail(node) {
        const metrics = node.getCoverageSummary()!;
 
        if (!skipReason(metrics, skipEmpty, skipFull)) counts.shown += 1;
        // empty files are hidden by `skipFull` too, but they are not "fully covered"
        else if (metrics.isEmpty()) counts.empty += 1;
        else counts.full += 1;
      },
    }),
  );
  return counts.shown === 0 && counts.full + counts.empty > 0 ? counts : null;
}
 
function fileNoun(count: number): string {
  return count === 1 ? "file" : "files";
}
 
function tableRow(
  node: ReportNode,
  context: Context,
  colorizer: (str: string, clazz?: string) => string,
  maxNameCols: number,
  level: number,
  skipEmpty: boolean | undefined,
  skipFull: boolean | undefined,
  missingWidth: number,
): string {
  const name = nodeName(node);
  const metrics = node.getCoverageSummary()!;
  const isEmpty = metrics.isEmpty();
  if (skipReason(metrics, skipEmpty, skipFull)) {
    return "";
  }
 
  const mm: Record<MetricKey, number | "Unknown"> = {
    statements: isEmpty ? 0 : metrics.statements.pct,
    branches: isEmpty ? 0 : metrics.branches.pct,
    functions: isEmpty ? 0 : metrics.functions.pct,
    lines: isEmpty ? 0 : metrics.lines.pct,
  };
  const colorize: (str: string, key: MetricKey) => string = isEmpty
    ? function (str) {
        return str;
      }
    : function (str, key) {
        return colorizer(str, classForPercent(context, key, mm[key]));
      };
  const elements = [];
 
  elements.push(colorize(formatName(name, maxNameCols, level), "statements"));
  elements.push(colorize(formatPct(mm.statements), "statements"));
  elements.push(colorize(formatPct(mm.branches, PCT_COLS + 1), "branches"));
  elements.push(colorize(formatPct(mm.functions), "functions"));
  elements.push(colorize(formatPct(mm.lines), "lines"));
  elements.push(
    colorizer(formatName(nodeMissing(node), missingWidth), mm.lines === 100 ? "medium" : "low"),
  );
 
  return elements.join(DELIM) + " ";
}
 
class TextReport extends ReportBase {
  declare file: string | null;
  declare maxCols: number;
  declare cw: ContentWriter | null;
  declare skipEmpty: boolean | undefined;
  declare skipFull: boolean | undefined;
  declare nameWidth: number;
  declare missingWidth: number;
  declare hideTable: boolean;
 
  constructor(opts?: TextOptions) {
    super(opts);
 
    opts = opts || {};
    const { maxCols } = opts;
 
    this.file = opts.file || null;
    this.maxCols = maxCols != null ? maxCols : process.stdout.columns || 80;
    this.cw = null;
    this.skipEmpty = opts.skipEmpty;
    this.skipFull = opts.skipFull;
    this.hideTable = false;
  }
 
  onStart(root: ReportNode, context: Context): void {
    this.cw = context.writer.writeFile(this.file);
    const counts = hiddenTableCounts(root, context, this.skipEmpty, this.skipFull);
    this.hideTable = counts !== null;
    if (counts) {
      this.cw.println("No files with missing coverage.");
      if (counts.full > 0) {
        this.cw.println(`${counts.full} ${fileNoun(counts.full)} fully covered.`);
      }
      if (counts.empty > 0) {
        this.cw.println(`${counts.empty} empty ${fileNoun(counts.empty)} skipped.`);
      }
      return;
    }
    this.nameWidth = Math.max(NAME_COL, findWidth(root, context, nodeName, depthFor));
    this.missingWidth = Math.max(MISSING_COL, findWidth(root, context, nodeMissing));
 
    Eif (this.maxCols > 0) {
      const pct_cols = DELIM.length + 4 * (PCT_COLS + DELIM.length) + 2;
 
      const maxRemaining = this.maxCols - (pct_cols + MISSING_COL);
      if (this.nameWidth > maxRemaining) {
        this.nameWidth = maxRemaining;
        this.missingWidth = MISSING_COL;
      } else Eif (this.nameWidth < maxRemaining) {
        const maxRemaining = this.maxCols - (this.nameWidth + pct_cols);
        if (this.missingWidth > maxRemaining) {
          this.missingWidth = maxRemaining;
        }
      }
    }
    const line = makeLine(this.nameWidth, this.missingWidth);
    this.cw.println(line);
    this.cw.println(tableHeader(this.nameWidth, this.missingWidth));
    this.cw.println(line);
  }
 
  onSummary(node: ReportNode, context: Context): void {
    if (this.hideTable) {
      return;
    }
    const nodeDepth = depthFor(node);
    const row = tableRow(
      node,
      context,
      this.cw!.colorize.bind(this.cw),
      this.nameWidth,
      nodeDepth,
      this.skipEmpty,
      this.skipFull,
      this.missingWidth,
    );
    if (row) {
      this.cw!.println(row);
    }
  }
 
  onDetail(node: ReportNode, context: Context): void {
    return this.onSummary(node, context);
  }
 
  onEnd(): void {
    if (!this.hideTable) {
      this.cw!.println(makeLine(this.nameWidth, this.missingWidth));
    }
    this.cw!.close();
  }
}
 
export default TextReport;