Primera Version Funcionando

This commit is contained in:
Miguel 2025-02-23 11:10:00 +01:00
commit 76c83caff5
19 changed files with 1667 additions and 0 deletions

363
.gitignore vendored Normal file
View File

@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

9
App.xaml Normal file
View File

@ -0,0 +1,9 @@
<Application x:Class="CodeMerger.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CodeMerger"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

13
App.xaml.cs Normal file
View File

@ -0,0 +1,13 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace CodeMerger;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}

10
AssemblyInfo.cs Normal file
View File

@ -0,0 +1,10 @@
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

View File

@ -0,0 +1,125 @@
using ICSharpCode.AvalonEdit.Rendering;
using System.Windows.Media;
using System;
using System.Windows;
using ICSharpCode.AvalonEdit.Document;
namespace CodeMerger;
public class ChangesHighlightingColorizer : IBackgroundRenderer
{
private static readonly Brush AddedLineBrush = new SolidColorBrush(Color.FromArgb(40, 50, 205, 50)); // Verde más visible
private static readonly Brush ModifiedLineBrush = new SolidColorBrush(Color.FromArgb(40, 255, 215, 0)); // Amarillo más visible
private TextView _textView;
public KnownLayer Layer => KnownLayer.Background;
public void SetTextView(TextView textView)
{
if (_textView != null)
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
_textView = textView;
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
_textView?.InvalidateLayer(Layer);
}
public void Draw(TextView textView, DrawingContext drawingContext)
{
if (textView?.Document == null) return;
bool isInAddedSection = false;
bool isInModifiedSection = false;
int sectionStartDepth = 0;
int currentDepth = 0;
int currentLine = 1;
int totalLines = textView.Document.LineCount;
while (currentLine <= totalLines)
{
var documentLine = textView.Document.GetLineByNumber(currentLine);
var lineText = textView.Document.GetText(documentLine);
var trimmedText = lineText.Trim();
// Actualizar el nivel de anidación
currentDepth += CountOpenBraces(trimmedText) - CountCloseBraces(trimmedText);
// Detectar inicio de secciones
if (trimmedText.Contains("// Added:") || trimmedText.Contains("// New:"))
{
isInAddedSection = true;
isInModifiedSection = false;
sectionStartDepth = currentDepth;
}
else if (trimmedText.Contains("// Modified:") || trimmedText.Contains("// Changed:"))
{
isInAddedSection = false;
isInModifiedSection = true;
sectionStartDepth = currentDepth;
}
// Obtener la línea visual
var visualLine = textView.GetOrConstructVisualLine(documentLine);
if (visualLine != null)
{
// Determinar el color basado en el estado actual
Brush brush = null;
if (isInAddedSection)
{
brush = AddedLineBrush;
}
else if (isInModifiedSection)
{
brush = ModifiedLineBrush;
}
// Si tenemos un color asignado y no es una línea de separador
if (brush != null && !trimmedText.Contains("// ----------------------------------------"))
{
var rect = BackgroundGeometryBuilder.GetRectsFromVisualSegment(textView, visualLine, 0, 1000)
.First();
// Dibujar el fondo de la línea completa
drawingContext.DrawRectangle(
brush,
null,
new Rect(0, rect.Top, textView.ActualWidth, rect.Height)
);
}
}
// Detectar fin de secciones
// Si volvemos al mismo nivel de anidación donde empezó la sección y encontramos una llave de cierre
if ((isInAddedSection || isInModifiedSection) &&
currentDepth <= sectionStartDepth &&
trimmedText.Contains("}"))
{
isInAddedSection = false;
isInModifiedSection = false;
}
// También terminar sección si encontramos un nuevo marcador
if (trimmedText.Contains("// ----------------------------------------"))
{
isInAddedSection = false;
isInModifiedSection = false;
}
currentLine++;
}
}
private int CountOpenBraces(string text)
{
return text.Count(c => c == '{');
}
private int CountCloseBraces(string text)
{
return text.Count(c => c == '}');
}
}

29
CodeMerger.csproj Normal file
View File

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Test\llm.cs" />
<Compile Remove="Test\merged.cs" />
<Compile Remove="Test\original.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Test\llm.cs" />
<None Include="Test\merged.cs" />
<None Include="Test\original.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" />
</ItemGroup>
</Project>

25
CodeMerger.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.13.35806.99 d17.13
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeMerger", "CodeMerger.csproj", "{0D46F18D-F5F1-4BED-B149-0549D1568443}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0D46F18D-F5F1-4BED-B149-0549D1568443}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0D46F18D-F5F1-4BED-B149-0549D1568443}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D46F18D-F5F1-4BED-B149-0549D1568443}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D46F18D-F5F1-4BED-B149-0549D1568443}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4D6D330B-6A32-4A81-8239-E0CC76419FFE}
EndGlobalSection
EndGlobal

82
MainWindow.xaml Normal file
View File

@ -0,0 +1,82 @@
<Window x:Class="CodeMerger.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalon="http://icsharpcode.net/sharpdevelop/avalonedit"
xmlns:cmerger="clr-namespace:CodeMerger"
Title="Code Merger" Height="800" Width="1200">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- File Selection Controls -->
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
<Button Content="Original File" Width="120" Margin="0,0,10,0"
Command="{Binding SelectOriginalFileCommand}"/>
<TextBlock Text="{Binding OriginalFileName}" VerticalAlignment="Center" Margin="0,0,20,0"/>
<Button Content="LLM File" Width="120" Margin="0,0,10,0"
Command="{Binding SelectLLMFileCommand}"/>
<TextBlock Text="{Binding LlmFileName}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<Button Content="Paste LLM" Width="120" Margin="0,0,10,0"
Command="{Binding PasteLLMCommand}"/>
<Button Content="Output File" Width="120" Margin="0,0,10,0"
Command="{Binding SelectOutputFileCommand}"/>
<TextBlock Text="{Binding OutputFileName}" VerticalAlignment="Center"/>
</StackPanel>
<!-- Code Display Area -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<GroupBox Header="Original Code" Grid.Column="0" Margin="0,0,5,0">
<avalon:TextEditor
x:Name="txtOriginalCode"
ShowLineNumbers="True"
FontFamily="Consolas"
SyntaxHighlighting="C#"
Document="{Binding OriginalDocument}"
WordWrap="True"/>
</GroupBox>
<GroupBox Header="LLM Code" Grid.Column="1" Margin="5,0,5,0">
<avalon:TextEditor
x:Name="txtLLMCode"
ShowLineNumbers="True"
FontFamily="Consolas"
SyntaxHighlighting="C#"
Document="{Binding LLMDocument}"
WordWrap="True"/>
</GroupBox>
<GroupBox Header="Merged Code" Grid.Column="2" Margin="5,0,0,0">
<avalon:TextEditor
x:Name="txtMergedCode"
ShowLineNumbers="True"
FontFamily="Consolas"
SyntaxHighlighting="C#"
Document="{Binding MergedDocument}"
WordWrap="True"
Loaded="txtMergedCode_Loaded"
IsReadOnly="True"/>
</GroupBox>
</Grid>
<!-- Bottom Controls -->
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,10,0,0" HorizontalAlignment="Right">
<Button Content="View Log" Width="120" Height="30" Margin="0,0,10,0"
Command="{Binding ShowLogCommand}"/>
<Button Content="Copy Merged" Width="120" Height="30" Margin="0,0,10,0"
Command="{Binding CopyMergedCommand}"/>
<Button Content="Merge Code" Width="120" Height="30"
Command="{Binding MergeCodeCommand}"/>
</StackPanel>
</Grid>
</Window>

38
MainWindow.xaml.cs Normal file
View File

@ -0,0 +1,38 @@
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using CodeMerger.ViewModels;
using ICSharpCode.AvalonEdit;
namespace CodeMerger;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ChangesHighlightingColorizer _highlightingColorizer;
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
_highlightingColorizer = new ChangesHighlightingColorizer();
}
private void txtMergedCode_Loaded(object sender, RoutedEventArgs e)
{
var textEditor = (ICSharpCode.AvalonEdit.TextEditor)sender;
_highlightingColorizer.SetTextView(textEditor.TextArea.TextView);
textEditor.TextArea.TextView.BackgroundRenderers.Add(_highlightingColorizer);
}
}

30
Models/AppSettings.cs Normal file
View File

@ -0,0 +1,30 @@
using System.Text.Json;
using System.IO;
namespace CodeMerger.Models;
public class AppSettings
{
private const string CONFIG_FILE = "appsettings.json";
private static string ConfigPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CONFIG_FILE);
public string? LastOriginalFilePath { get; set; }
public string? LastLLMFilePath { get; set; }
public string? LastOutputFilePath { get; set; }
public static AppSettings Load()
{
if (File.Exists(ConfigPath))
{
var json = File.ReadAllText(ConfigPath);
return JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
}
return new AppSettings();
}
public void Save()
{
var json = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(ConfigPath, json);
}
}

25
Models/LogMessage.cs Normal file
View File

@ -0,0 +1,25 @@
using System;
namespace CodeMerger.Models;
public class LogMessage
{
public string Message { get; private set; }
public LogLevel Level { get; private set; }
public DateTime Timestamp { get; private set; }
public LogMessage(string message, LogLevel level)
{
Message = message;
Level = level;
Timestamp = DateTime.Now;
}
}
public enum LogLevel
{
Info,
Warning,
Error,
Debug
}

11
Test/llm.cs Normal file
View File

@ -0,0 +1,11 @@
using System;
namespace Demo {
public class MyClass {
public void MyMethod() {
Console.WriteLine("Inicio Modificado");
Console.WriteLine("Paso intermedio");
// ... resto del código ...
}
}
}

18
Test/merged.cs Normal file
View File

@ -0,0 +1,18 @@
using System;
namespace Demo
{
public class MyClass
{
public int MyProperty { get; set; }
public void MyMethod()
{
{
Console.WriteLine("Inicio Modificado");
Console.WriteLine("Paso intermedio");
Console.WriteLine("Fin Original");
}
}
}
}

13
Test/original.cs Normal file
View File

@ -0,0 +1,13 @@
using System;
namespace Demo {
public class MyClass {
public int MyProperty { get; set; }
public void MyMethod() {
Console.WriteLine("Inicio Original");
Console.WriteLine("Paso intermedio");
Console.WriteLine("Fin Original");
}
}
}

View File

@ -0,0 +1,46 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Text;
using System.Windows;
using CodeMerger.Models;
namespace CodeMerger.ViewModels;
public partial class LogViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<LogMessage> logMessages = new();
public void AddLog(string message, LogLevel level = LogLevel.Info)
{
App.Current.Dispatcher.Invoke(() =>
{
LogMessages.Add(new LogMessage(message, level));
});
}
public void Clear()
{
LogMessages.Clear();
}
[RelayCommand]
private void CopyToClipboard()
{
var sb = new StringBuilder();
foreach (var message in LogMessages)
{
sb.AppendLine($"[{message.Timestamp:HH:mm:ss.fff}] [{message.Level}] {message.Message}");
}
try
{
Clipboard.SetText(sb.ToString());
}
catch (System.Exception ex)
{
AddLog($"Error copying to clipboard: {ex.Message}", LogLevel.Error);
}
}
}

219
ViewModels/MainViewModel.cs Normal file
View File

@ -0,0 +1,219 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System.IO;
using System;
using CodeMerger.Models;
using ICSharpCode.AvalonEdit.Document;
using System.Windows;
namespace CodeMerger.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly cCodeMerger _codeMerger;
private readonly AppSettings _settings;
private readonly LogViewModel _logViewModel;
[ObservableProperty]
private string originalFilePath;
[ObservableProperty]
private string llmFilePath;
[ObservableProperty]
private string outputFilePath;
[ObservableProperty]
private string originalFileName;
[ObservableProperty]
private string llmFileName;
[ObservableProperty]
private string outputFileName;
[ObservableProperty]
private TextDocument originalDocument;
[ObservableProperty]
private TextDocument lLMDocument;
[ObservableProperty]
private TextDocument mergedDocument;
public MainViewModel()
{
_codeMerger = new cCodeMerger();
_settings = AppSettings.Load();
_logViewModel = new LogViewModel();
// Initialize documents
OriginalDocument = new TextDocument();
LLMDocument = new TextDocument();
MergedDocument = new TextDocument();
LoadLastUsedFiles();
}
private void LoadLastUsedFiles()
{
if (!string.IsNullOrEmpty(_settings.LastOriginalFilePath) && File.Exists(_settings.LastOriginalFilePath))
{
OriginalFilePath = _settings.LastOriginalFilePath;
OriginalFileName = Path.GetFileName(OriginalFilePath);
OriginalDocument.Text = File.ReadAllText(OriginalFilePath);
}
if (!string.IsNullOrEmpty(_settings.LastLLMFilePath) && File.Exists(_settings.LastLLMFilePath))
{
LlmFilePath = _settings.LastLLMFilePath;
LlmFileName = Path.GetFileName(LlmFilePath);
LLMDocument.Text = File.ReadAllText(LlmFilePath);
}
if (!string.IsNullOrEmpty(_settings.LastOutputFilePath))
{
OutputFilePath = _settings.LastOutputFilePath;
OutputFileName = Path.GetFileName(OutputFilePath);
LoadMergedFile();
}
}
private void LoadMergedFile()
{
if (!string.IsNullOrEmpty(OutputFilePath) && File.Exists(OutputFilePath))
{
try
{
MergedDocument.Text = File.ReadAllText(OutputFilePath);
_logViewModel.AddLog($"Loaded merged file: {OutputFilePath}", LogLevel.Info);
}
catch (Exception ex)
{
_logViewModel.AddLog($"Error loading merged file: {ex.Message}", LogLevel.Error);
}
}
}
[RelayCommand]
private void SelectOriginalFile()
{
var dialog = new OpenFileDialog
{
Filter = "C# files (*.cs)|*.cs|All files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
OriginalFilePath = dialog.FileName;
OriginalFileName = Path.GetFileName(OriginalFilePath);
OriginalDocument.Text = File.ReadAllText(OriginalFilePath);
_settings.LastOriginalFilePath = OriginalFilePath;
_settings.Save();
}
}
[RelayCommand]
private void SelectLLMFile()
{
var dialog = new OpenFileDialog
{
Filter = "C# files (*.cs)|*.cs|All files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
LlmFilePath = dialog.FileName;
LlmFileName = Path.GetFileName(LlmFilePath);
LLMDocument.Text = File.ReadAllText(LlmFilePath);
_settings.LastLLMFilePath = LlmFilePath;
_settings.Save();
}
}
[RelayCommand]
private void SelectOutputFile()
{
var dialog = new SaveFileDialog
{
Filter = "C# files (*.cs)|*.cs|All files (*.*)|*.*",
DefaultExt = ".cs"
};
if (dialog.ShowDialog() == true)
{
OutputFilePath = dialog.FileName;
OutputFileName = Path.GetFileName(OutputFilePath);
_settings.LastOutputFilePath = OutputFilePath;
_settings.Save();
LoadMergedFile();
}
}
[RelayCommand]
private void MergeCode()
{
if (string.IsNullOrWhiteSpace(OriginalFilePath) ||
string.IsNullOrWhiteSpace(LlmFilePath) ||
string.IsNullOrWhiteSpace(OutputFilePath))
{
throw new InvalidOperationException("Please select all required files first.");
}
var result = _codeMerger.MergeCode(OriginalDocument.Text, LLMDocument.Text, OutputFilePath, _logViewModel);
if (result.Success)
{
MergedDocument.Text = result.MergedCode;
}
else
{
throw new InvalidOperationException($"Merge failed:\n{string.Join("\n", result.Diagnostics)}");
}
}
[RelayCommand]
private void ShowLog()
{
var logWindow = new Views.LogWindow(_logViewModel);
logWindow.Owner = App.Current.MainWindow;
logWindow.Show();
}
[RelayCommand]
private void PasteLLM()
{
try
{
var text = Clipboard.GetText();
if (!string.IsNullOrEmpty(text))
{
LLMDocument.Text = text;
_logViewModel.AddLog("LLM code pasted from clipboard", LogLevel.Info);
}
}
catch (Exception ex)
{
_logViewModel.AddLog($"Error pasting from clipboard: {ex.Message}", LogLevel.Error);
}
}
[RelayCommand]
private void CopyMerged()
{
try
{
Clipboard.SetText(MergedDocument.Text);
_logViewModel.AddLog("Merged code copied to clipboard", LogLevel.Info);
}
catch (Exception ex)
{
_logViewModel.AddLog($"Error copying to clipboard: {ex.Message}", LogLevel.Error);
}
}
}

31
Views/LogWindow.xaml Normal file
View File

@ -0,0 +1,31 @@
<Window x:Class="CodeMerger.Views.LogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Merge Log" Height="600" Width="800"
WindowStartupLocation="CenterOwner">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox ItemsSource="{Binding LogMessages}" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding Timestamp, StringFormat=HH:mm:ss.fff, Mode=OneWay}" Foreground="Gray"/>
<Run Text=" ["/>
<Run Text="{Binding Level, Mode=OneWay}" FontWeight="Bold"/>
<Run Text="] "/>
<Run Text="{Binding Message, Mode=OneWay}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Grid.Row="1" Content="Copy to Clipboard"
HorizontalAlignment="Right" Margin="0,10,0,0"
Width="120" Height="30"
Command="{Binding CopyToClipboardCommand}"/>
</Grid>
</Window>

13
Views/LogWindow.xaml.cs Normal file
View File

@ -0,0 +1,13 @@
using System.Windows;
using CodeMerger.ViewModels;
namespace CodeMerger.Views;
public partial class LogWindow : Window
{
public LogWindow(LogViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
}

567
cCodeMerger.cs Normal file
View File

@ -0,0 +1,567 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using CodeMerger.ViewModels;
using CodeMerger.Models;
public class cCodeMerger
{
private const string CONTINUATION_MARKER = "// ... resto del código ...";
private class ClassNamespaceMapping
{
public Dictionary<string, string> ClassToNamespace { get; } = new Dictionary<string, string>();
public void AddMapping(string className, string namespaceName)
{
if (!ClassToNamespace.ContainsKey(className))
{
ClassToNamespace[className] = namespaceName;
}
}
public string GetNamespace(string className)
{
return ClassToNamespace.TryGetValue(className, out var ns) ? ns : null;
}
}
private readonly ClassNamespaceMapping _classNamespaceMapping = new ClassNamespaceMapping();
public class MergeResult
{
public bool Success { get; set; }
public string MergedCode { get; set; }
public List<string> Diagnostics { get; set; } = new List<string>();
}
public MergeResult MergeCode(string originalCode, string llmCode, string outputPath, LogViewModel logger)
{
var result = new MergeResult();
try
{
logger.AddLog("Starting code merge process...");
logger.AddLog("Parsing original code...", LogLevel.Debug);
var originalTree = CSharpSyntaxTree.ParseText(originalCode);
var originalRoot = originalTree.GetRoot() as CompilationUnitSyntax;
logger.AddLog("Parsing LLM code...", LogLevel.Debug);
var llmTree = CSharpSyntaxTree.ParseText(llmCode);
var llmRoot = llmTree.GetRoot() as CompilationUnitSyntax;
if (originalRoot == null || llmRoot == null)
{
logger.AddLog("Failed to parse syntax trees", LogLevel.Error);
result.Success = false;
result.Diagnostics.Add("Error parsing syntax trees");
return result;
}
logger.AddLog("Processing namespaces...");
var newRoot = ProcessNamespaces(originalRoot, llmRoot, logger);
logger.AddLog("Formatting result...");
var formattedRoot = newRoot.NormalizeWhitespace();
logger.AddLog($"Writing output to: {outputPath}");
File.WriteAllText(outputPath, formattedRoot.ToFullString());
result.Success = true;
result.MergedCode = formattedRoot.ToFullString();
logger.AddLog("Merge completed successfully!");
return result;
}
catch (Exception ex)
{
logger.AddLog($"Error during merge: {ex.Message}", LogLevel.Error);
logger.AddLog(ex.StackTrace ?? "", LogLevel.Debug);
result.Success = false;
result.Diagnostics.Add($"Error during merge: {ex.Message}");
return result;
}
}
private CompilationUnitSyntax ProcessNamespaces(CompilationUnitSyntax originalRoot, CompilationUnitSyntax llmRoot, LogViewModel logger)
{
logger.AddLog("Checking for top-level members in LLM code...", LogLevel.Debug);
var topLevelMembers = GetTopLevelMembers(llmRoot).ToList();
if (topLevelMembers.Any())
{
logger.AddLog("Found top-level members in LLM code, determining best namespace...", LogLevel.Debug);
var targetNamespace = FindBestNamespaceForMembers(topLevelMembers, originalRoot, logger);
// Create or update namespace with top-level members
var existingNamespace = llmRoot.Members.OfType<NamespaceDeclarationSyntax>()
.FirstOrDefault(ns => ns.Name.ToString() == targetNamespace);
if (existingNamespace != null)
{
logger.AddLog($"Adding top-level members to existing namespace: {targetNamespace}", LogLevel.Debug);
llmRoot = llmRoot.ReplaceNode(existingNamespace,
existingNamespace.WithMembers(
existingNamespace.Members.AddRange(topLevelMembers)));
}
else
{
logger.AddLog($"Creating new namespace {targetNamespace} for top-level members", LogLevel.Debug);
var newNamespace = SyntaxFactory.NamespaceDeclaration(
SyntaxFactory.ParseName(targetNamespace))
.WithMembers(SyntaxFactory.List(topLevelMembers));
llmRoot = llmRoot.WithMembers(
SyntaxFactory.List(
llmRoot.Members.Where(m => m is NamespaceDeclarationSyntax)
.Concat(new[] { newNamespace })));
}
}
// Continue with existing namespace processing
logger.AddLog("Analyzing LLM code structure:", LogLevel.Debug);
var llmNamespaces = new Dictionary<string, NamespaceDeclarationSyntax>();
// Log and collect LLM namespaces
foreach (var ns in llmRoot.Members.OfType<NamespaceDeclarationSyntax>())
{
var nsName = ns.Name.ToString();
logger.AddLog($"Found LLM namespace: {nsName}", LogLevel.Debug);
llmNamespaces[nsName] = ns;
foreach (var cls in ns.Members.OfType<ClassDeclarationSyntax>())
{
logger.AddLog($" Class in LLM: {cls.Identifier}", LogLevel.Debug);
logger.AddLog(" Fields and Properties in LLM class:", LogLevel.Debug);
// Log fields
foreach (var field in cls.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variable in field.Declaration.Variables)
{
logger.AddLog($" Field: {variable.Identifier} : {field.Declaration.Type}", LogLevel.Debug);
}
}
// Log properties
foreach (var prop in cls.Members.OfType<PropertyDeclarationSyntax>())
{
logger.AddLog($" Property: {prop.Identifier} : {prop.Type}", LogLevel.Debug);
}
foreach (var method in cls.Members.OfType<MethodDeclarationSyntax>())
{
logger.AddLog($" Method: {method.Identifier}", LogLevel.Debug);
}
}
}
logger.AddLog("\nAnalyzing original code structure:", LogLevel.Debug);
var namespacesToProcess = originalRoot.Members.OfType<NamespaceDeclarationSyntax>().ToList();
foreach (var ns in namespacesToProcess)
{
var nsName = ns.Name.ToString();
logger.AddLog($"Found original namespace: {nsName}", LogLevel.Debug);
foreach (var cls in ns.Members.OfType<ClassDeclarationSyntax>())
{
logger.AddLog($" Class in original: {cls.Identifier}", LogLevel.Debug);
logger.AddLog(" Fields and Properties in original class:", LogLevel.Debug);
// Log fields
foreach (var field in cls.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variable in field.Declaration.Variables)
{
logger.AddLog($" Field: {variable.Identifier} : {field.Declaration.Type}", LogLevel.Debug);
}
}
// Log properties
foreach (var prop in cls.Members.OfType<PropertyDeclarationSyntax>())
{
logger.AddLog($" Property: {prop.Identifier} : {prop.Type}", LogLevel.Debug);
}
foreach (var member in cls.Members)
{
switch (member)
{
case MethodDeclarationSyntax method:
logger.AddLog($" Method in original: {method.Identifier}", LogLevel.Debug);
break;
case PropertyDeclarationSyntax prop:
logger.AddLog($" Property in original: {prop.Identifier}", LogLevel.Debug);
break;
}
}
}
}
var newMembers = new List<MemberDeclarationSyntax>();
foreach (var ns in namespacesToProcess)
{
var nsName = ns.Name.ToString();
logger.AddLog($"Processing namespace: {nsName}", LogLevel.Debug);
if (llmNamespaces.TryGetValue(nsName, out var llmNs))
{
logger.AddLog($"Found matching LLM namespace for: {nsName}", LogLevel.Debug);
var processedNs = ProcessNamespace(ns, llmNs, logger);
newMembers.Add(processedNs);
}
else
{
logger.AddLog($"No matching LLM namespace found for: {nsName}, keeping original", LogLevel.Debug);
newMembers.Add(ns);
}
}
// Add new namespaces from LLM code
foreach (var llmNs in llmNamespaces.Values)
{
var nsName = llmNs.Name.ToString();
if (!namespacesToProcess.Any(ns => ns.Name.ToString() == nsName))
{
logger.AddLog($"Adding new namespace from LLM: {nsName}", LogLevel.Debug);
newMembers.Add(llmNs);
}
}
return originalRoot.WithMembers(SyntaxFactory.List(newMembers));
}
private IEnumerable<MemberDeclarationSyntax> GetTopLevelMembers(CompilationUnitSyntax root)
{
return root.Members.Where(m => !(m is NamespaceDeclarationSyntax));
}
private string FindBestNamespaceForMembers(
IEnumerable<MemberDeclarationSyntax> members,
CompilationUnitSyntax originalRoot,
LogViewModel logger)
{
var methodsByClass = members.OfType<ClassDeclarationSyntax>()
.ToDictionary(
c => c.Identifier.ToString(),
c => c.Members.OfType<MethodDeclarationSyntax>()
.Select(m => m.Identifier.ToString())
.ToHashSet()
);
foreach (var ns in originalRoot.Members.OfType<NamespaceDeclarationSyntax>())
{
foreach (var cls in ns.Members.OfType<ClassDeclarationSyntax>())
{
var className = cls.Identifier.ToString();
foreach (var method in cls.Members.OfType<MethodDeclarationSyntax>())
{
if (methodsByClass.Any(kvp => kvp.Value.Contains(method.Identifier.ToString())))
{
var nsName = ns.Name.ToString();
logger.AddLog($"Found matching method {method.Identifier} in namespace {nsName}", LogLevel.Debug);
// Registrar el namespace para la clase que contiene el método coincidente
var matchingClass = methodsByClass.First(kvp => kvp.Value.Contains(method.Identifier.ToString())).Key;
_classNamespaceMapping.AddMapping(matchingClass, nsName);
return nsName;
}
}
}
}
// If no matching methods found, use first namespace
var firstNamespace = originalRoot.Members.OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
if (firstNamespace != null)
{
logger.AddLog($"No matching methods found, using first namespace: {firstNamespace.Name}", LogLevel.Debug);
return firstNamespace.Name.ToString();
}
logger.AddLog("No namespaces found in original code!", LogLevel.Warning);
return "DefaultNamespace";
}
private NamespaceDeclarationSyntax ProcessNamespace(NamespaceDeclarationSyntax original, NamespaceDeclarationSyntax llm, LogViewModel logger)
{
logger.AddLog($"Processing classes in namespace: {original.Name}", LogLevel.Debug);
var classesToProcess = original.Members.OfType<ClassDeclarationSyntax>();
var llmClasses = llm.Members.OfType<ClassDeclarationSyntax>()
.ToDictionary(c => c.Identifier.ToString());
var newMembers = new List<MemberDeclarationSyntax>();
foreach (var cls in classesToProcess)
{
if (llmClasses.TryGetValue(cls.Identifier.ToString(), out var llmClass))
{
// Process methods and properties within the class
var processedClass = ProcessClass(cls, llmClass, logger);
newMembers.Add(processedClass);
}
else
{
// Keep original class unchanged
newMembers.Add(cls);
}
}
// Add any new classes from LLM code
foreach (var llmClass in llmClasses.Values)
{
if (!classesToProcess.Any(c => c.Identifier.ToString() == llmClass.Identifier.ToString()))
{
newMembers.Add(llmClass);
}
}
return original.WithMembers(SyntaxFactory.List(newMembers));
}
private ClassDeclarationSyntax ProcessClass(ClassDeclarationSyntax original, ClassDeclarationSyntax llm, LogViewModel logger)
{
logger.AddLog($"Processing class: {original.Identifier}", LogLevel.Debug);
// Log original fields and properties
logger.AddLog("Original class fields and properties:", LogLevel.Debug);
foreach (var field in original.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variable in field.Declaration.Variables)
{
logger.AddLog($" Field: {variable.Identifier} : {field.Declaration.Type}", LogLevel.Debug);
}
}
foreach (var prop in original.Members.OfType<PropertyDeclarationSyntax>())
{
logger.AddLog($" Property: {prop.Identifier} : {prop.Type}", LogLevel.Debug);
}
// Log LLM fields and properties
logger.AddLog("LLM class fields and properties:", LogLevel.Debug);
foreach (var field in llm.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variable in field.Declaration.Variables)
{
logger.AddLog($" Field: {variable.Identifier} : {field.Declaration.Type}", LogLevel.Debug);
}
}
foreach (var prop in llm.Members.OfType<PropertyDeclarationSyntax>())
{
logger.AddLog($" Property: {prop.Identifier} : {prop.Type}", LogLevel.Debug);
}
var newMembers = new List<MemberDeclarationSyntax>();
var processedMembers = new HashSet<string>();
var processedFields = new HashSet<string>();
var processedProperties = new HashSet<string>();
// Process existing fields first
foreach (var member in original.Members)
{
if (member is FieldDeclarationSyntax originalField)
{
foreach (var variable in originalField.Declaration.Variables)
{
var fieldName = variable.Identifier.ToString();
var llmField = llm.Members.OfType<FieldDeclarationSyntax>()
.FirstOrDefault(f => f.Declaration.Variables
.Any(v => v.Identifier.ToString() == fieldName));
if (llmField != null)
{
logger.AddLog($" Updating field: {fieldName}", LogLevel.Debug);
newMembers.Add(llmField);
processedFields.Add(fieldName);
}
else
{
logger.AddLog($" Keeping original field: {fieldName}", LogLevel.Debug);
newMembers.Add(originalField);
processedFields.Add(fieldName);
}
break; // Process one field declaration at a time
}
}
}
// Add new fields from LLM
foreach (var field in llm.Members.OfType<FieldDeclarationSyntax>())
{
foreach (var variable in field.Declaration.Variables)
{
var fieldName = variable.Identifier.ToString();
if (!processedFields.Contains(fieldName))
{
logger.AddLog($" Adding new field from LLM: {fieldName}", LogLevel.Debug);
// Add comment to mark new field with separator
var newField = field.WithLeadingTrivia(
SyntaxFactory.TriviaList(
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// ----------------------------------------"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Added: New field"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n")));
newMembers.Add(newField);
processedFields.Add(fieldName);
break;
}
}
}
// Procesar primero las propiedades existentes
foreach (var member in original.Members)
{
if (member is PropertyDeclarationSyntax originalProperty)
{
var propertyName = originalProperty.Identifier.ToString();
var llmProperty = llm.Members.OfType<PropertyDeclarationSyntax>()
.FirstOrDefault(p => p.Identifier.ToString() == propertyName);
if (llmProperty != null)
{
logger.AddLog($" Updating property: {propertyName}", LogLevel.Debug);
newMembers.Add(llmProperty);
processedProperties.Add(propertyName);
}
else
{
logger.AddLog($" Keeping original property: {propertyName}", LogLevel.Debug);
newMembers.Add(originalProperty);
processedProperties.Add(propertyName);
}
}
}
// Añadir nuevas propiedades del LLM
foreach (var member in llm.Members.OfType<PropertyDeclarationSyntax>())
{
var propertyName = member.Identifier.ToString();
if (!processedProperties.Contains(propertyName))
{
logger.AddLog($" Adding new property from LLM: {propertyName}", LogLevel.Debug);
// Add comment to mark new property with separator
var newProperty = member.WithLeadingTrivia(
SyntaxFactory.TriviaList(
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// ----------------------------------------"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Added: New property"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n")));
newMembers.Add(newProperty);
processedProperties.Add(propertyName);
}
}
// Procesar métodos como antes
foreach (var member in original.Members)
{
if (member is MethodDeclarationSyntax originalMethod)
{
var methodName = originalMethod.Identifier.ToString();
var llmMethod = llm.Members.OfType<MethodDeclarationSyntax>()
.FirstOrDefault(m => m.Identifier.ToString() == methodName);
if (llmMethod != null)
{
logger.AddLog($" Found matching method: {methodName}", LogLevel.Debug);
var processedMethod = ProcessMethod(originalMethod, llmMethod, logger);
// Add comment to mark modified method with separator
var modifiedMethod = processedMethod.WithLeadingTrivia(
SyntaxFactory.TriviaList(
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// ----------------------------------------"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Modified: Updated implementation"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n")));
newMembers.Add(modifiedMethod);
processedMembers.Add(methodName);
}
else
{
logger.AddLog($" Keeping original method: {methodName}", LogLevel.Debug);
newMembers.Add(member);
}
}
else if (!(member is PropertyDeclarationSyntax))
{
newMembers.Add(member);
}
}
// Añadir nuevos métodos del LLM como antes
foreach (var member in llm.Members)
{
if (member is MethodDeclarationSyntax llmMethod &&
!processedMembers.Contains(llmMethod.Identifier.ToString()))
{
logger.AddLog($" Adding new method from LLM: {llmMethod.Identifier}", LogLevel.Debug);
// Add comment to mark new method with separator
var newMethod = llmMethod.WithLeadingTrivia(
SyntaxFactory.TriviaList(
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// ----------------------------------------"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia, "// Added: New method"),
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n")));
newMembers.Add(newMethod);
}
}
return original.WithMembers(SyntaxFactory.List(newMembers));
}
private MethodDeclarationSyntax ProcessMethod(MethodDeclarationSyntax original, MethodDeclarationSyntax llm, LogViewModel logger)
{
var methodName = original.Identifier.ToString();
logger.AddLog($" Processing method: {methodName}", LogLevel.Debug);
var llmBody = llm.Body?.ToString() ?? "";
logger.AddLog($" Original signature: {original.Modifiers} {original.ReturnType} {methodName}({string.Join(", ", original.ParameterList.Parameters)})", LogLevel.Debug);
logger.AddLog($" LLM signature: {llm.Modifiers} {llm.ReturnType} {methodName}({string.Join(", ", llm.ParameterList.Parameters)})", LogLevel.Debug);
if (llmBody.Contains(CONTINUATION_MARKER))
{
logger.AddLog(" Found continuation marker in LLM code", LogLevel.Debug);
var originalBody = original.Body?.ToString() ?? "";
var llmLines = llmBody.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var lastLlmLine = llmLines
.Take(Array.FindIndex(llmLines, l => l.Contains(CONTINUATION_MARKER)))
.Where(l => !string.IsNullOrWhiteSpace(l))
.LastOrDefault();
if (lastLlmLine != null)
{
logger.AddLog($" Last LLM line before marker: {lastLlmLine}", LogLevel.Debug);
var originalLines = originalBody.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var continuationIndex = Array.FindIndex(originalLines, l => l.Trim() == lastLlmLine.Trim());
if (continuationIndex >= 0)
{
logger.AddLog($" Found continuation point at line {continuationIndex + 1}", LogLevel.Debug);
var newBody = string.Join(Environment.NewLine,
llmLines.Take(Array.FindIndex(llmLines, l => l.Contains(CONTINUATION_MARKER)))
.Concat(originalLines.Skip(continuationIndex + 1)));
logger.AddLog(" Successfully merged method bodies", LogLevel.Debug);
return llm.WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement(newBody)));
}
else
{
logger.AddLog(" Could not find continuation point in original code", LogLevel.Warning);
}
}
}
else
{
logger.AddLog(" Using complete LLM method implementation", LogLevel.Debug);
}
return llm;
}
}