MarketAlly.AIPlugin.Extensions/Test.Refactoring/Program.cs

329 lines
11 KiB
C#
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MarketAlly.AIPlugin;
using MarketAlly.AIPlugin.Refactoring.Plugins;
using System.Text.Json;
namespace MarketAlly.AIPlugin.Refactoring.TestConsole;
class GitProgram
{
static async Task<int> OldMain(string[] args)
{
var host = CreateHost();
var testService = host.Services.GetRequiredService<EnhancedRefactoringTestService>();
try
{
ShowWelcomeEnhanced();
// If command line arguments provided, execute them first
if (args.Length > 0)
{
await ExecuteEnhancedCommand(args, testService);
Console.WriteLine();
}
// Start interactive loop
while (true)
{
try
{
Console.Write("RefactoringTest> ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
continue;
if (input.Trim() == "/exit" || input.Trim() == "exit")
{
Console.WriteLine("[INFO] Goodbye!");
break;
}
if (input.Trim() == "/help" || input.Trim() == "help")
{
ShowEnhancedHelp();
continue;
}
var commandArgs = ParseInput(input);
if (commandArgs.Length == 0)
continue;
await ExecuteEnhancedCommand(commandArgs, testService);
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Command error: {ex.Message}");
Console.WriteLine();
}
}
return 0;
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Application error: {ex.Message}");
return 1;
}
}
private static async Task ExecuteEnhancedCommand(string[] args, EnhancedRefactoringTestService service)
{
if (args.Length == 0)
{
ShowEnhancedHelp();
return;
}
var command = args[0].ToLower();
switch (command)
{
case "create-advanced-samples":
await service.CreateAdvancedSampleFiles();
break;
case "test-refactor":
var refactorFile = GetFilePathFromArgs(args, "Enter file path for refactoring: ");
if (!string.IsNullOrEmpty(refactorFile))
{
var operations = GetOperationsFromArgs(args, "Enter operations (extract-methods,split-classes,simplify-conditionals,remove-duplicates,introduce-parameter-objects): ");
var apply = args.Contains("--apply");
await service.TestActualRefactoring(refactorFile, operations, apply);
}
break;
case "test-workflow":
await service.TestCompleteRefactoringWorkflow();
break;
case "compare-before-after":
var compareFile = GetFilePathFromArgs(args, "Enter file path to compare: ");
if (!string.IsNullOrEmpty(compareFile))
{
await CompareBeforeAfter(compareFile, service);
}
break;
case "demo-refactoring":
await DemonstrateRefactoringCapabilities(service);
break;
// Include all original commands...
case "create-sample":
//await service.CreateSampleFilesAsync();
break;
case "test-analysis":
var analysisFile = GetFilePathFromArgs(args, "Enter file path for analysis: ");
//if (!string.IsNullOrEmpty(analysisFile))
//await service.TestCodeAnalysisAsync(analysisFile);
break;
case "help":
ShowEnhancedHelp();
break;
default:
Console.WriteLine($"[ERROR] Unknown command: {command}");
ShowEnhancedHelp();
break;
}
}
private static async Task CompareBeforeAfter(string filePath, EnhancedRefactoringTestService service)
{
Console.WriteLine($"[COMPARE] Demonstrating refactoring impact on: {Path.GetFileName(filePath)}");
Console.WriteLine(new string('=', 80));
// Show original analysis
Console.WriteLine("[BEFORE REFACTORING]");
await service.TestCodeAnalysisOnFile(filePath);
// Perform refactoring (preview mode)
Console.WriteLine("\n[REFACTORING PREVIEW]");
await service.TestActualRefactoring(filePath, "extract-methods,simplify-conditionals", false);
Console.WriteLine("\n[COMPARISON COMPLETE]");
Console.WriteLine("The above shows what improvements would be made to your code.");
Console.WriteLine("Use 'test-refactor --file <path> --operations <ops> --apply' to make actual changes.");
}
private static async Task DemonstrateRefactoringCapabilities(EnhancedRefactoringTestService service)
{
Console.WriteLine("[DEMO] Demonstrating MarketAlly Refactoring Plugin Capabilities");
Console.WriteLine(new string('=', 80));
Console.WriteLine("This demo shows how the refactoring plugins can:");
Console.WriteLine("1. ✓ Analyze code quality and complexity");
Console.WriteLine("2. ✓ Generate intelligent documentation");
Console.WriteLine("3. ✓ Format and clean up code style");
Console.WriteLine("4. ✓ Improve naming conventions");
Console.WriteLine("5. ✓ ACTUALLY REFACTOR CODE STRUCTURE (New!)");
Console.WriteLine();
// Create and demonstrate on a complex file
await service.CreateAdvancedSampleFiles();
var complexFile = Path.Combine(Directory.GetCurrentDirectory(), "advanced_samples", "ComplexCalculator.cs");
Console.WriteLine("[DEMO STEP 1] Original code analysis:");
await service.TestCodeAnalysisOnFile(complexFile);
Console.WriteLine("\n[DEMO STEP 2] Actual refactoring suggestions:");
await service.TestActualRefactoring(complexFile, "extract-methods,simplify-conditionals", false);
Console.WriteLine("\n[DEMO COMPLETE]");
Console.WriteLine("The refactoring plugin can now:");
Console.WriteLine("• Extract complex methods into smaller, focused methods");
Console.WriteLine("• Identify opportunities to split large classes");
Console.WriteLine("• Find and suggest removal of duplicate code");
Console.WriteLine("• Recommend parameter objects for methods with many parameters");
Console.WriteLine("• Simplify complex conditional logic");
Console.WriteLine("• Actually modify your code files (with backup)");
}
private static string GetOperationsFromArgs(string[] args, string prompt)
{
var operationsIndex = Array.IndexOf(args, "--operations");
if (operationsIndex >= 0 && operationsIndex + 1 < args.Length)
{
return args[operationsIndex + 1];
}
Console.Write(prompt);
var operations = Console.ReadLine()?.Trim();
return string.IsNullOrEmpty(operations) ? "extract-methods,simplify-conditionals" : operations;
}
private static string GetFilePathFromArgs(string[] args, string prompt)
{
if (args.Length >= 3 && args[1] == "--file")
{
return args[2];
}
Console.Write(prompt);
var filePath = Console.ReadLine()?.Trim();
return string.IsNullOrEmpty(filePath) ? null : filePath;
}
private static string[] ParseInput(string input)
{
var parts = new List<string>();
var current = new System.Text.StringBuilder();
bool inQuotes = false;
foreach (char c in input)
{
if (c == '"')
{
inQuotes = !inQuotes;
continue;
}
if (char.IsWhiteSpace(c) && !inQuotes)
{
if (current.Length > 0)
{
parts.Add(current.ToString());
current.Clear();
}
}
else
{
current.Append(c);
}
}
if (current.Length > 0)
{
parts.Add(current.ToString());
}
return parts.ToArray();
}
private static void ShowWelcomeEnhanced()
{
Console.WriteLine("MarketAlly AI Plugin ENHANCED Refactoring Test Console");
Console.WriteLine("=" + new string('=', 56));
Console.WriteLine();
Console.WriteLine("🚀 NOW WITH ACTUAL CODE REFACTORING CAPABILITIES! 🚀");
Console.WriteLine();
Console.WriteLine("Test suite for analysis, documentation, formatting, AND refactoring");
Console.WriteLine("Type 'help' for commands or 'exit' to quit");
Console.WriteLine();
}
private static void ShowEnhancedHelp()
{
Console.WriteLine();
Console.WriteLine("Available commands:");
Console.WriteLine();
Console.WriteLine("📝 ANALYSIS & DOCUMENTATION:");
Console.WriteLine(" create-sample Create basic sample C# files");
Console.WriteLine(" test-analysis [--file <path>] Test CodeAnalysisPlugin");
Console.WriteLine(" test-documentation [--file <path>] [--style <style>] [--apply] Test documentation");
Console.WriteLine(" test-formatting [--file <path>] [--style <style>] [--apply] Test code formatting");
Console.WriteLine(" test-naming [--file <path>] [--apply] Test naming conventions");
Console.WriteLine();
Console.WriteLine("🔧 ACTUAL REFACTORING (NEW!):");
Console.WriteLine(" create-advanced-samples Create complex files for refactoring");
Console.WriteLine(" test-refactor [--file <path>] [--operations <ops>] [--apply] Perform actual refactoring");
Console.WriteLine(" test-workflow Complete refactoring workflow demo");
Console.WriteLine(" compare-before-after [--file <path>] Show refactoring impact");
Console.WriteLine(" demo-refactoring Full capability demonstration");
Console.WriteLine();
Console.WriteLine("⚡ BATCH OPERATIONS:");
Console.WriteLine(" test-batch [--directory <path>] [--operations <ops>] [--apply] Test batch refactoring");
Console.WriteLine(" test-all Run all plugin tests");
Console.WriteLine(" benchmark Run performance benchmarks");
Console.WriteLine();
Console.WriteLine(" HELP & EXIT:");
Console.WriteLine(" help Show this help");
Console.WriteLine(" exit Exit application");
Console.WriteLine();
Console.WriteLine("🔧 Refactoring Operations:");
Console.WriteLine(" extract-methods Extract complex methods into smaller methods");
Console.WriteLine(" split-classes Split large classes into focused classes");
Console.WriteLine(" simplify-conditionals Simplify complex if/else logic");
Console.WriteLine(" remove-duplicates Find and suggest duplicate code removal");
Console.WriteLine(" introduce-parameter-objects Suggest parameter objects for long parameter lists");
Console.WriteLine();
Console.WriteLine("📊 Documentation styles: intelligent, comprehensive, basic, minimal");
Console.WriteLine("🎨 Formatting styles: microsoft, allman, kr, google");
Console.WriteLine();
Console.WriteLine("💡 Examples:");
Console.WriteLine(" create-advanced-samples");
Console.WriteLine(" test-refactor --file ComplexCalculator.cs --operations \"extract-methods,simplify-conditionals\" --apply");
Console.WriteLine(" compare-before-after --file UserManagementSystem.cs");
Console.WriteLine(" demo-refactoring");
Console.WriteLine(" test-workflow");
Console.WriteLine();
Console.WriteLine("⚠️ Note: Always backup your code before applying refactoring changes!");
Console.WriteLine(" The plugin automatically creates .bak files when making changes.");
Console.WriteLine();
}
private static IHost CreateHost()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddLogging(builder =>
{
builder.AddConsole();
builder.SetMinimumLevel(LogLevel.Information);
});
services.AddSingleton<AIPluginRegistry>();
services.AddTransient<EnhancedRefactoringTestService>();
})
.Build();
}
}