'use strict';

const { relative } = require('path');
const Transform = require('internal/streams/transform');

// This reporter is based on the LCOV format, as described here:
// https://ltp.sourceforge.net/coverage/lcov/geninfo.1.php
// Excerpts from this documentation are included in the comments that make up
// the _transform function below.
class LcovReporter extends Transform {
  constructor(options) {
    super({ ...options, writableObjectMode: true, __proto__: null });
  }

  _transform(event, _encoding, callback) {
    if (event.type !== 'test:coverage') {
      return callback(null);
    }
    let lcov = '';
    // A tracefile is made up of several human-readable lines of text, divided
    // into sections. If available, a tracefile begins with the testname which
    // is stored in the following format:
    // ## TN:\<test name\>
    lcov += 'TN:\n';
    const {
      data: {
        summary: { workingDirectory },
      },
    } = event;
    try {
      for (let i = 0; i < event.data.summary.files.length; i++) {
        const file = event.data.summary.files[i];
        // For each source file referenced in the .da file, there is a section
        // containing filename and coverage data:
        // ## SF:\<path to the source file\>
        lcov += `SF:${relative(workingDirectory, file.path)}\n`;

        // Following is a list of line numbers for each function name found in
        // the source file:
        // ## FN:\<line number of function start\>,\<function name\>
        //
        // After, there is a list of execution counts for each instrumented
        // function:
        // ## FNDA:\<execution count\>,\<function name\>
        //
        // This loop adds the FN lines to the lcov variable as it goes and
        // gathers the FNDA lines to be added later. This way we only loop
        // through the list of functions once.
        let fnda = '';
        for (let j = 0; j < file.functions.length; j++) {
