| | | 1 | | using ArturRios.Data.Export.Abstractions; |
| | | 2 | | using ArturRios.Data.Export.Configuration; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Data.Export.Exporters; |
| | | 6 | | |
| | | 7 | | /// <summary>Writes records as delimited text using the shared column map and RFC 4180 quoting.</summary> |
| | | 8 | | /// <remarks> |
| | | 9 | | /// Quoting follows RFC 4180: a field is quoted when it holds the delimiter, a double quote or a line |
| | | 10 | | /// break, and an embedded quote is doubled. The delimiter and the line terminator are not fixed to the |
| | | 11 | | /// RFC's comma and CRLF - the delimiter comes from the options and lines end with the platform's |
| | | 12 | | /// newline - so the output is RFC 4180 only when those happen to match. |
| | | 13 | | /// Text that a spreadsheet would evaluate as a formula is prefixed with <c>'</c> unless |
| | | 14 | | /// <see cref="CsvOptions.EscapeFormulas" /> is off. |
| | | 15 | | /// </remarks> |
| | | 16 | | /// <typeparam name="T">The record type.</typeparam> |
| | | 17 | | /// <param name="options">CSV options.</param> |
| | | 18 | | /// <param name="logger">Optional logger; see <see cref="ExporterBase{T}" />.</param> |
| | | 19 | | public class CsvExporter<T>(CsvOptions options, ILogger<CsvExporter<T>>? logger = null) |
| | 36 | 20 | | : ExporterBase<T>(logger) where T : class |
| | | 21 | | { |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | protected override async Task WriteCoreAsync(IEnumerable<T> data, Stream destination, CancellationToken ct) |
| | | 24 | | { |
| | 32 | 25 | | var columns = ColumnMap.For<T>(); |
| | 32 | 26 | | var writer = new StreamWriter(destination, options.Encoding, leaveOpen: true); |
| | | 27 | | |
| | 32 | 28 | | await using var writerScope = writer.ConfigureAwait(false); |
| | | 29 | | |
| | 32 | 30 | | if (options.IncludeHeader) |
| | | 31 | | { |
| | 10 | 32 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 40 | 33 | | columns.Select(c => Escape(c.Header, options.Delimiter)))).ConfigureAwait(false); |
| | | 34 | | } |
| | | 35 | | |
| | 124 | 36 | | foreach (var item in data) |
| | | 37 | | { |
| | 30 | 38 | | ct.ThrowIfCancellationRequested(); |
| | 30 | 39 | | await writer.WriteLineAsync(string.Join(options.Delimiter, |
| | 120 | 40 | | columns.Select(c => Escape(Render(c.Getter(item)), options.Delimiter)))).ConfigureAwait(false); |
| | | 41 | | } |
| | | 42 | | |
| | 32 | 43 | | await writer.FlushAsync(ct).ConfigureAwait(false); |
| | 32 | 44 | | } |
| | | 45 | | |
| | | 46 | | // Characters that make a spreadsheet treat a cell as a formula (OWASP "CSV Injection"). |
| | 4 | 47 | | private static readonly char[] FormulaTriggers = ['=', '+', '-', '@', '\t', '\r']; |
| | | 48 | | |
| | | 49 | | private string Render(object? value) |
| | | 50 | | { |
| | 90 | 51 | | var text = ValueRenderer.Render(value); |
| | | 52 | | |
| | | 53 | | // Only text is neutralized: a formatted value (number, date, enum, Guid) is produced by the runtime, |
| | | 54 | | // not by whoever supplied the data, and a negative number must stay a number. |
| | 90 | 55 | | var isText = value is string or char || value is not null and not IFormattable; |
| | | 56 | | |
| | 90 | 57 | | return options.EscapeFormulas && isText && text.Length > 0 && FormulaTriggers.Contains(text[0]) |
| | 90 | 58 | | ? "'" + text |
| | 90 | 59 | | : text; |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | private static string Escape(string field, char delimiter) |
| | | 63 | | { |
| | 120 | 64 | | var mustQuote = field.Contains(delimiter) || field.Contains('"') || field.Contains('\n') || field.Contains('\r') |
| | 120 | 65 | | return mustQuote ? $"\"{field.Replace("\"", "\"\"")}\"" : field; |
| | | 66 | | } |
| | | 67 | | } |