// Generated by testgen: rewritten every time tests are generated, do not edit. // testgen (@xylentis/testgen), Copyright (C) 2026 Xylentis. Licensed under AGPL-3.0-only with an additional // permission: as part of tests generated by testgen, this file may be used, modified and distributed under // terms of your choice (see NOTICE in @xylentis/testgen). import fs from 'node:fs'; /** * Rows of the CSV data file of a data-driven test, as objects with the given columns. The file is UTF-8, * with or without a BOM, separated by commas or semicolons (as Excel saves it in some languages), and its * first line names the columns; other columns are ignored, blank lines skipped. */ export function readCsv(file: string, columns: Column[]): Record[] { const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''); const firstLine = text.split(/\r?\n/, 1)[0]; const separator = !firstLine.includes(',') && firstLine.includes(';') ? ';' : ','; const [header, ...records] = parseCsv(text, separator); if (!header) throw new Error(`testgen: data file ${file} is empty`); const names = header.map(name => name.trim()); for (const column of columns) { if (!names.includes(column)) throw new Error(`testgen: data file ${file} has no column "${column}" (it has ${names.join(', ')})`); } const rows = records .filter(record => record.some(cell => cell.trim())) .map(record => Object.fromEntries(columns.map(column => [column, record[names.indexOf(column)] ?? ''])) as Record); if (!rows.length) throw new Error(`testgen: data file ${file} has no data rows`); return rows; } // RFC 4180: quoted fields may contain separators, line breaks and doubled quotes. function parseCsv(text: string, separator: string): string[][] { const rows: string[][] = []; let row: string[] = []; let field = ''; let quoted = false; for (let i = 0; i < text.length; i++) { const c = text[i]; if (quoted) { if (c === '"' && text[i + 1] === '"') { field += '"'; i++; } else if (c === '"') { quoted = false; } else { field += c; } } else if (c === '"') { quoted = true; } else if (c === separator) { row.push(field); field = ''; } else if (c === '\n' || c === '\r') { if (c === '\r' && text[i + 1] === '\n') i++; row.push(field); rows.push(row); row = []; field = ''; } else { field += c; } } if (field || row.length) { row.push(field); rows.push(row); } return rows; }