| | | 1 | | using ArturRios.Data.Export.Configuration; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Data.Export.Exporters; |
| | | 6 | | |
| | | 7 | | /// <summary>Writes one line per record: default <see cref="object.ToString" />, or a custom selector.</summary> |
| | | 8 | | /// <typeparam name="T">The record type.</typeparam> |
| | | 9 | | /// <param name="options">TXT options.</param> |
| | | 10 | | /// <param name="logger">Optional logger; see <see cref="ExporterBase{T}" />.</param> |
| | | 11 | | public class TxtExporter<T>(TxtOptions options, ILogger<TxtExporter<T>>? logger = null) |
| | 12 | 12 | | : ExporterBase<T>(logger) where T : class |
| | | 13 | | { |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | protected override Task WriteCoreAsync(IEnumerable<T> data, Stream destination, CancellationToken ct) => |
| | 6 | 16 | | WriteLinesAsync(data, destination, item => item?.ToString() ?? string.Empty, ct); |
| | | 17 | | |
| | | 18 | | /// <summary>Writes each record on its own line using <paramref name="lineSelector" />.</summary> |
| | | 19 | | public Task<ProcessOutput> WriteAsync(IEnumerable<T> data, Stream destination, Func<T, string> lineSelector, |
| | | 20 | | CancellationToken ct = default) => |
| | 6 | 21 | | GuardedWriteAsync(data, destination, stream => WriteLinesAsync(data, stream, lineSelector, ct)); |
| | | 22 | | |
| | | 23 | | /// <summary>Writes each record on its own line to a file using <paramref name="lineSelector" />.</summary> |
| | | 24 | | public Task<ProcessOutput> WriteToFileAsync(IEnumerable<T> data, string path, Func<T, string> lineSelector, |
| | | 25 | | CancellationToken ct = default) => |
| | 0 | 26 | | GuardedFileAsync(data, path, stream => WriteLinesAsync(data, stream, lineSelector, ct)); |
| | | 27 | | |
| | | 28 | | private async Task WriteLinesAsync(IEnumerable<T> data, Stream destination, Func<T, string> lineSelector, |
| | | 29 | | CancellationToken ct) |
| | | 30 | | { |
| | 6 | 31 | | var writer = new StreamWriter(destination, options.Encoding, leaveOpen: true); |
| | | 32 | | |
| | 6 | 33 | | await using var writerScope = writer.ConfigureAwait(false); |
| | | 34 | | |
| | 24 | 35 | | foreach (var item in data) |
| | | 36 | | { |
| | 6 | 37 | | ct.ThrowIfCancellationRequested(); |
| | 6 | 38 | | await writer.WriteAsync(lineSelector(item)).ConfigureAwait(false); |
| | 6 | 39 | | await writer.WriteAsync(options.NewLine).ConfigureAwait(false); |
| | | 40 | | } |
| | | 41 | | |
| | 6 | 42 | | await writer.FlushAsync(ct).ConfigureAwait(false); |
| | 6 | 43 | | } |
| | | 44 | | } |