Repository navigation
Expand file tree
/
Copy pathNativeTools.cs
More file actions
317 lines (271 loc) · 12 KB
/
Copy pathNativeTools.cs
File metadata and controls
317 lines (271 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
using System;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
namespace CodingSahayi;
public class NativeTools
{
public static Dictionary<string, string> _fileBackups = new();
public static void RollbackChanges()
{
foreach (var kvp in _fileBackups)
{
if (File.Exists(kvp.Key))
{
File.WriteAllText(kvp.Key, kvp.Value);
}
}
_fileBackups.Clear();
}
public static string ReadFile(string filePath)
{
try
{
if (!File.Exists(filePath))
return $"Error: File not found at {filePath}";
return File.ReadAllText(filePath);
}
catch (Exception ex)
{
return $"Error reading file: {ex.Message}";
}
}
public static string WriteFile(string filePath, string content)
{
return content;
}
public static string PatchFile(string filePath, string targetSnippet, string replacementSnippet)
{
try
{
if (!File.Exists(filePath)) return $"Error: File not found at {filePath}";
string content = File.ReadAllText(filePath);
string normalizedContent = content.Replace("\r\n", "\n");
string normalizedTarget = targetSnippet.Replace("\r\n", "\n");
string normalizedReplacement = replacementSnippet.Replace("\r\n", "\n");
int firstIndex = normalizedContent.IndexOf(normalizedTarget);
if (firstIndex == -1) return "Error: Target snippet not found in file. Please read the file first and provide the exact text to match.";
int lastIndex = normalizedContent.LastIndexOf(normalizedTarget);
bool hadMultiple = (firstIndex != lastIndex);
string newContent = normalizedContent.Substring(0, firstIndex)
+ normalizedReplacement
+ normalizedContent.Substring(firstIndex + normalizedTarget.Length);
return newContent;
string msg = $"Success: Replaced snippet in {filePath}";
if (hadMultiple) msg += " (Warning: snippet appeared multiple times, only replaced the FIRST occurrence. Use more context lines for precision.)";
return msg;
}
catch (Exception ex)
{
return $"Error patching file: {ex.Message}";
}
}
public static string ListDirectory(string directoryPath, int maxDepth = 3)
{
try
{
if (!Directory.Exists(directoryPath)) return $"Error: Directory not found at {directoryPath}";
var sb = new System.Text.StringBuilder();
var ignoredDirs = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".git", "bin", "obj", "node_modules", ".vs", "dist", "build" };
void WalkDirectory(string path, int currentDepth, string prefix)
{
if (currentDepth > maxDepth) return;
var dirInfo = new DirectoryInfo(path);
sb.AppendLine($"{prefix}{dirInfo.Name}/");
try
{
var dirs = dirInfo.GetDirectories().Where(d => !ignoredDirs.Contains(d.Name)).OrderBy(d => d.Name).ToList();
var files = dirInfo.GetFiles().OrderBy(f => f.Name).ToList();
for (int i = 0; i < dirs.Count; i++)
{
bool isLast = (i == dirs.Count - 1) && (files.Count == 0);
WalkDirectory(dirs[i].FullName, currentDepth + 1, prefix + (isLast ? " " : "│ "));
}
for (int i = 0; i < files.Count; i++)
{
bool isLast = (i == files.Count - 1);
sb.AppendLine($"{prefix}{(isLast ? "└── " : "├── ")}{files[i].Name}");
}
}
catch (UnauthorizedAccessException) { }
}
WalkDirectory(directoryPath, 0, "");
return sb.ToString();
}
catch (Exception ex)
{
return $"Error listing directory: {ex.Message}";
}
}
public static string SearchDirectory(string directoryPath, string searchPattern = "*")
{
try
{
if (!Directory.Exists(directoryPath)) return $"Error: Directory not found at {directoryPath}";
var files = Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
if (files.Length == 0) return "No files found matching the pattern.";
var sb = new System.Text.StringBuilder();
sb.AppendLine($"Found {files.Length} file(s):");
foreach (var f in files)
{
// Make relative to the search root for cleaner output
string relPath = f.StartsWith(directoryPath, StringComparison.OrdinalIgnoreCase)
? f.Substring(directoryPath.Length).TrimStart('\\', '/')
: f;
sb.AppendLine($"- {relPath}");
}
return sb.ToString();
}
catch (UnauthorizedAccessException ex)
{
return $"Access denied: {ex.Message}";
}
catch (DirectoryNotFoundException ex)
{
return $"Directory not found: {ex.Message}";
}
catch (Exception ex)
{
return $"Error searching directory: {ex.Message}";
}
}
public static string SearchCode(string directoryPath, string searchQuery, string fileExtensionFilter = "*.*")
{
try
{
if (!Directory.Exists(directoryPath)) return $"Error: Directory not found at {directoryPath}";
var sb = new System.Text.StringBuilder();
var ignoredDirs = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".git", "bin", "obj", "node_modules", ".vs", "dist", "build" };
var files = Directory.EnumerateFiles(directoryPath, string.IsNullOrEmpty(fileExtensionFilter) ? "*.*" : fileExtensionFilter, new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.Hidden | FileAttributes.System
}).Where(f => !ignoredDirs.Any(ig => f.Contains($"\\{ig}\\") || f.Contains($"/{ig}/")));
int matchCount = 0;
foreach (var file in files)
{
if (matchCount >= 50) { sb.AppendLine("Warning: Reached maximum match limit (50). Truncated."); break; }
var lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(searchQuery, StringComparison.OrdinalIgnoreCase))
{
matchCount++;
sb.AppendLine($"File: {file}:{i + 1}");
if (i > 0) sb.AppendLine($" {i}: {lines[i - 1]}");
sb.AppendLine($" {i + 1}: {lines[i]}");
if (i < lines.Length - 1) sb.AppendLine($" {i + 2}: {lines[i + 1]}");
sb.AppendLine("---");
}
}
}
if (matchCount == 0) return "No matches found.";
return sb.ToString();
}
catch (Exception ex)
{
return $"Error searching code: {ex.Message}";
}
}
public static string ExecuteTerminalSafe(string command, string workingDirectory = "", int timeoutSeconds = 45, CancellationToken cancellationToken = default)
{
try
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"{command}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? AppContext.BaseDirectory : workingDirectory
}
};
var outputBuilder = new System.Text.StringBuilder();
process.OutputDataReceived += (s, e) => { if (e.Data != null) outputBuilder.AppendLine(e.Data); };
process.ErrorDataReceived += (s, e) => { if (e.Data != null) outputBuilder.AppendLine($"ERROR: {e.Data}"); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
bool cancelled = false;
bool exited = false;
// Loop waiting for exit, breaking early if the caller cancels.
while (!process.HasExited)
{
if (cancellationToken.IsCancellationRequested)
{
cancelled = true;
break;
}
if (process.WaitForExit(100))
{
exited = true;
break;
}
}
if (cancelled)
{
process.Kill(true); // Kill process tree
outputBuilder.AppendLine($"\n\n--- COMMAND CANCELLED ---");
}
else if (!exited)
{
process.Kill(true); // Kill process tree
outputBuilder.AppendLine($"\n\n--- COMMAND TIMED OUT AFTER {timeoutSeconds} SECONDS ---");
}
string output = outputBuilder.ToString();
if (output.Length > 10240)
{
output = "... [TRUNCATED] ...\n" + output.Substring(output.Length - 10240);
}
var lines = output.Split('\n');
if (lines.Length > 200)
{
output = "... [TRUNCATED] ...\n" + string.Join('\n', lines.Skip(lines.Length - 200));
}
return string.IsNullOrWhiteSpace(output) ? "Command executed successfully with no output." : output;
}
catch (Exception ex)
{
return $"Failed to start process: {ex.Message}";
}
}
public static string SemanticCodeSearch(string query)
{
try
{
var queryVector = VectorService.GetEmbeddingAsync(query).GetAwaiter().GetResult();
if (queryVector == null || queryVector.Length == 0)
return "Error: Could not generate embedding for query.";
using var db = new CodingSahayi.Data.AppDbContext();
var chunks = db.CodeChunks.ToList();
var scoredChunks = chunks.Select(c => {
float[] vector = string.IsNullOrEmpty(c.EmbeddingJson) ? Array.Empty<float>() : System.Text.Json.JsonSerializer.Deserialize<float[]>(c.EmbeddingJson) ?? Array.Empty<float>();
float score = VectorService.CosineSimilarity(queryVector, vector);
return (Chunk: c, Score: score);
})
.Where(x => x.Score > 0)
.OrderByDescending(x => x.Score)
.Take(3)
.ToList();
if (scoredChunks.Count == 0) return "No relevant code chunks found in the semantic database.";
var sb = new System.Text.StringBuilder();
sb.AppendLine("Top Semantic Search Results:");
foreach (var sc in scoredChunks)
{
sb.AppendLine($"--- File: {sc.Chunk.FilePath} (Score: {sc.Score:F3}) ---");
sb.AppendLine(sc.Chunk.Content);
}
return sb.ToString();
}
catch (Exception ex)
{
return $"Error performing semantic search: {ex.Message}";
}
}
}