54 lines
2.1 KiB
C#
54 lines
2.1 KiB
C#
using CodeContextGenerator.Interfaces;
|
||
using System.IO;
|
||
using System.Text;
|
||
|
||
namespace CodeContextGenerator.Services;
|
||
|
||
public class ContextFileGenerator : IContextFileGenerator
|
||
{
|
||
private readonly IFileProcessorService _fileProcessorService;
|
||
|
||
public ContextFileGenerator(IFileProcessorService fileProcessorService)
|
||
{
|
||
_fileProcessorService = fileProcessorService;
|
||
}
|
||
|
||
public async Task GenerateContextFileAsync(List<string> selectedFiles, string outputPath, string projectRootPath, IProgress<int> progress, CancellationToken cancellationToken)
|
||
{
|
||
var outputContent = new StringBuilder();
|
||
int totalFiles = selectedFiles.Count;
|
||
int processedFiles = 0;
|
||
|
||
foreach (var filePath in selectedFiles)
|
||
{
|
||
cancellationToken.ThrowIfCancellationRequested();
|
||
|
||
try
|
||
{
|
||
string relativePath = Path.GetRelativePath(projectRootPath, filePath);
|
||
string fileContent = await File.ReadAllTextAsync(filePath, Encoding.UTF8);
|
||
|
||
// Обработка комментариев
|
||
fileContent = _fileProcessorService.ProcessFileContent(fileContent, Path.GetFileName(filePath));
|
||
|
||
outputContent.AppendLine($"=== Файл: {relativePath} ===");
|
||
outputContent.AppendLine(fileContent);
|
||
outputContent.AppendLine(); // Пустая строка между файлами
|
||
|
||
processedFiles++;
|
||
if (totalFiles > 0 && progress != null)
|
||
{
|
||
progress.Report((int)((processedFiles * 100.0) / totalFiles));
|
||
}
|
||
}
|
||
catch (IOException ex)
|
||
{
|
||
throw new IOException($"Файл '{Path.GetFileName(filePath)}' заблокирован или недоступен: {ex.Message}", ex);
|
||
}
|
||
}
|
||
|
||
// Сохраняем результат с кодировкой UTF-8 с BOM
|
||
var encoding = new UTF8Encoding(true);
|
||
await File.WriteAllTextAsync(outputPath, outputContent.ToString(), encoding);
|
||
}
|
||
} |