using System;
using System.Linq;
using xCommons.Extensions;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using System.IO;
using System.Threading;
using xAiModels.Models;
using System.Text;
namespace xAiApi.Providers.Extractors
{
///
/// Extractor for source code files ...
/// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...)
///
public class XCodeFileContentExtractor : IXCodeFileContentExtractor
{
///
/// Supported MIME Types ...
///
private static readonly string[] SupportedMimeTypes =
[
"text/x-c",
"text/x-go",
"text/yaml",
"text/x-php",
"text/x-c++",
"text/x-sql",
"text/x-java",
"text/x-rust",
"text/x-ruby",
"text/x-csharp",
"text/x-python",
"text/javascript",
"text/typescript",
"text/x-java-source",
"application/x-yaml",
"application/x-csharp",
"application/x-python",
"application/javascript",
"application/typescript",
];
///
/// Check if this extractor supports the specified MIME type ...
///
///
///
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
///
/// Extract text content from file stream ...
///
///
///
///
///
public async Task ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
string.Empty,
mimeType,
cancellationToken
);
//
return result.Text;
}
///
/// Extract content from stream as Rich Result ...
///
///
///
///
///
///
public async Task ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
// Read entire source code as UTF-8 (with BOM detection) ...
using var reader = new StreamReader(
fileStream,
Encoding.UTF8,
leaveOpen: false,
detectEncodingFromByteOrderMarks: true
);
//
var content = await reader.ReadToEndAsync();
//
// Normalize line endings for consistent downstream processing ...
content = content?
.Replace("\r\n", "\n")
.Replace("\r", "\n");
//
result.Text = content;
//
return result;
}
}
}