< Summary

Information
Class: ToolCore.FileUtils
Assembly: ToolCore
File(s): /home/runner/work/InvAit/InvAit/ToolCore/FileUtils.cs
Tag: 194_44631168438
Line coverage
92%
Covered lines: 46
Uncovered lines: 4
Coverable lines: 50
Total lines: 117
Line coverage: 92%
Branch coverage
80%
Covered branches: 29
Total branches: 36
Branch coverage: 80.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%22100%
ReadFileWithMetadataAsync()85.71%282891.89%
SaveFileAsync()66.66%6690%

File(s)

/home/runner/work/InvAit/InvAit/ToolCore/FileUtils.cs

#LineLine coverage
 1using System.IO.Abstractions;
 2using System.Text;
 3
 4namespace ToolCore;
 5
 6public class FileUtils
 7{
 8    private readonly IFileSystem _fileSystem;
 9
 10    // Конструктор по умолчанию использует реальную ОС, а для тестов мы сможем передать мок
 2011    public FileUtils(IFileSystem? fileSystem = null)
 12    {
 2013        _fileSystem = fileSystem ?? new FileSystem();
 2014    }
 15
 16    public async Task<(List<string> Lines, Encoding Encoding, string Separator, bool HasFinalNewLine)> ReadFileWithMetad
 17        string filepath, CancellationToken cancellationToken = default)
 18    {
 2019        var lines = new List<string>();
 2020        Encoding encoding = new UTF8Encoding(false);
 2021        var separator = Environment.NewLine;
 2022        var hasFinalNewLine = false;
 23
 2024        if (!_fileSystem.File.Exists(filepath)) // Используем интерфейс
 25        {
 226            return (lines, encoding, separator, hasFinalNewLine);
 27        }
 28
 29        // Ограничиваем максимальный размер
 1830        var fileInfo = _fileSystem.FileInfo.New(filepath);
 31        const long maxAllowedSize = 2 * 1024 * 1024; // 2 МБ и то много
 1832        if (fileInfo.Length > maxAllowedSize)
 33        {
 34            // Файл слишком большой для этого метода, возвращаем пустой результат
 035            return (lines, encoding, separator, hasFinalNewLine);
 36        }
 37
 38        // ПРОВЕРКА НА БИНАРНОСТЬ: Заглядываем в начало файла
 1839        using (var fsCheck = _fileSystem.FileStream.New(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, 
 40        {
 1841            var sampleBuffer = new byte[1024];
 1842            var bytesRead = await fsCheck.ReadAsync(sampleBuffer, 0, sampleBuffer.Length, cancellationToken).ConfigureAw
 43
 110444            for (var i = 0; i < bytesRead; i++)
 45            {
 53646                if (sampleBuffer[i] == 0x00) // Обнаружен Null-символ -> это бинарный файл
 47                {
 48                    // Пропускаем чтение бинарного файла
 049                    return (lines, encoding, separator, hasFinalNewLine);
 50                }
 51            }
 1652        }
 53
 54        // Читаем текстовый файл
 55        string fullText;
 1656        using (var fs = _fileSystem.FileStream.New(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileO
 1657        using (var reader = new StreamReader(fs, encoding, detectEncodingFromByteOrderMarks: true))
 58        {
 1659            fullText = await reader.ReadToEndAsync().ConfigureAwait(false);
 1660            encoding = reader.CurrentEncoding;
 1661        }
 62
 1663        cancellationToken.ThrowIfCancellationRequested();
 64
 1665        if (string.IsNullOrEmpty(fullText))
 66        {
 067            return (lines, encoding, separator, hasFinalNewLine);
 68        }
 69
 70        // Определение разделителей
 2471        if (fullText.Contains("\r\n")) separator = "\r\n";
 1272        else if (fullText.Contains("\n")) separator = "\n";
 473        else if (fullText.Contains("\r")) separator = "\r";
 74
 1675        if (fullText.EndsWith("\n") || fullText.EndsWith("\r"))
 76        {
 677            hasFinalNewLine = true;
 78        }
 79
 80        // Парсинг строк
 1681        var splitSeparators = new[] { "\r\n", "\r", "\n" };
 1682        var allLines = fullText.Split(splitSeparators, StringSplitOptions.None);
 83
 1684        if (allLines.Length > 0)
 85        {
 1686            lines.AddRange(allLines);
 87
 1688            if (hasFinalNewLine && lines.Count > 0 && string.IsNullOrEmpty(lines[lines.Count - 1]))
 89            {
 690                lines.RemoveAt(lines.Count - 1);
 91            }
 92        }
 93
 1694        return (lines, encoding, separator, hasFinalNewLine);
 1895    }
 96
 97    public async Task SaveFileAsync(string filepath, List<string> lines, Encoding encoding, string separator, bool hasFi
 98    {
 1299        var content = string.Join(separator, lines);
 100
 12101        if (hasFinalNewLine)
 102        {
 6103            content += separator;
 104        }
 105
 12106        var directory = _fileSystem.Path.GetDirectoryName(filepath);
 12107        if (!string.IsNullOrEmpty(directory) && !_fileSystem.Directory.Exists(directory))
 108        {
 0109            _fileSystem.Directory.CreateDirectory(directory);
 110        }
 111
 112        // Создаем файл через фабрику интерфейса
 12113        using var fs = _fileSystem.FileStream.New(filepath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, Fil
 12114        using var writer = new StreamWriter(fs, encoding);
 12115        await writer.WriteAsync(content).ConfigureAwait(false);
 12116    }
 117}