| | | 1 | | namespace ToolCore; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Line-based fuzzy search and replace for applying diff edits. |
| | | 5 | | /// |
| | | 6 | | /// MATCHING (case-insensitive; search lines are trimmed, so their own indentation is |
| | | 7 | | /// ignored; search lines must occupy consecutive target lines): |
| | | 8 | | /// - the FIRST line of a multi-line block may be truncated at the START (the target line |
| | | 9 | | /// ends with the search line — the model lost the leading characters); |
| | | 10 | | /// - the LAST line may be truncated at the END (the target line starts with the search |
| | | 11 | | /// line — the model cut the tail mid-token); |
| | | 12 | | /// - MIDDLE lines must match the target line exactly; |
| | | 13 | | /// - a SINGLE-line search matches as a substring of the target line; |
| | | 14 | | /// - empty/whitespace-only search lines match empty/whitespace-only target lines; |
| | | 15 | | /// - an all-empty search block matches the first empty target line. |
| | | 16 | | /// Full search (hint = -1) prefers a block where every line matches exactly over a |
| | | 17 | | /// fragment match on an earlier line. A hint restricts the preferred range to |
| | | 18 | | /// [hint - 1 - tol, hint - 1 + tol] (1-based, inclusive) with a fallback to the first |
| | | 19 | | /// match anywhere in the file. |
| | | 20 | | /// |
| | | 21 | | /// REPLACEMENT (ApplyEdit, in place): |
| | | 22 | | /// - a fully matched line is replaced VERBATIM by its replacement line (the replacement |
| | | 23 | | /// keeps its own indentation, e.g. a re-nested block); |
| | | 24 | | /// - a truncated boundary line: only the matched fragment is removed/replaced — the rest |
| | | 25 | | /// of the line (leading indentation and the trailing part) is preserved. For the first |
| | | 26 | | /// boundary line the matched fragment is the RIGHTMOST occurrence of the search text |
| | | 27 | | /// (the suffix of the line); the trailing part of the last matched line stays attached |
| | | 28 | | /// to the last emitted line (after extra replacement lines, when present), or — when |
| | | 29 | | /// the whole matched block is deleted — to the preceding text (or becomes the first |
| | | 30 | | /// line if the block starts the file); |
| | | 31 | | /// - a single-line search whose fragment starts the line while the line continues after |
| | | 32 | | /// it replaces the WHOLE line (the model cut the end of the line); |
| | | 33 | | /// - a missing replacement line (replace shorter than search) DELETES the matched line; |
| | | 34 | | /// - extra replacement lines are inserted after the last matched line; |
| | | 35 | | /// - an all-empty search block replaces the matched empty line with the replacement block. |
| | | 36 | | /// </summary> |
| | | 37 | | public static class EditApplier |
| | | 38 | | { |
| | | 39 | | /// <summary> |
| | | 40 | | /// Searches for occurrences of string list in target file. |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="target">File lines to search in</param> |
| | | 43 | | /// <param name="search">Lines to search for</param> |
| | | 44 | | /// <param name="hint">1-based position hint (or -1 for full search)</param> |
| | | 45 | | /// <param name="tol">Offset tolerance from hint</param> |
| | | 46 | | /// <returns>0-based index of first match or -1 if not found</returns> |
| | | 47 | | public static int FindInFile(List<string>? target, List<string>? search, int hint, int tol) |
| | | 48 | | { |
| | 138 | 49 | | if (target == null || search == null || search.Count == 0 || search.Count > target.Count) |
| | 0 | 50 | | return -1; |
| | | 51 | | |
| | 138 | 52 | | var searchTrimmed = search.Select(l => l.Trim()).ToArray(); |
| | 138 | 53 | | return FindMatchTrimmed(target, searchTrimmed, hint, tol) ?? -1; |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Applies a single edit to the target lines in place: finds the search block |
| | | 58 | | /// (fuzzy, case-insensitive) and replaces it with the replace block. |
| | | 59 | | /// </summary> |
| | | 60 | | /// <param name="target">File lines (modified in place)</param> |
| | | 61 | | /// <param name="search">Lines to search for</param> |
| | | 62 | | /// <param name="replace">Replacement lines</param> |
| | | 63 | | /// <param name="hint">1-based position hint (or -1 for full search)</param> |
| | | 64 | | /// <param name="tol">Offset tolerance from hint</param> |
| | | 65 | | /// <returns>0-based index where the replacement was applied, or -1 if not found</returns> |
| | | 66 | | public static int ApplyEdit(List<string>? target, List<string>? search, List<string>? replace, int hint, int tol) |
| | | 67 | | { |
| | 50 | 68 | | if (target == null || search == null || replace == null) |
| | 6 | 69 | | return -1; |
| | 44 | 70 | | if (search.Count == 0 || search.Count > target.Count) |
| | 0 | 71 | | return -1; |
| | | 72 | | |
| | 44 | 73 | | var searchTrimmed = search.Select(l => l.Trim()).ToArray(); |
| | | 74 | | |
| | 44 | 75 | | var start = FindMatchTrimmed(target, searchTrimmed, hint, tol); |
| | 44 | 76 | | if (start == null) |
| | 2 | 77 | | return -1; |
| | | 78 | | |
| | | 79 | | // All search lines are empty: replace the matched empty line with the replacement block. |
| | 42 | 80 | | if (searchTrimmed.All(s => s.Length == 0)) |
| | | 81 | | { |
| | 0 | 82 | | target.RemoveAt(start.Value); |
| | 0 | 83 | | for (var j = replace.Count - 1; j >= 0; j--) |
| | 0 | 84 | | target.Insert(start.Value, replace[j]); |
| | 0 | 85 | | return start.Value; |
| | | 86 | | } |
| | | 87 | | |
| | 42 | 88 | | var result = new List<string>(target.Count); |
| | 196 | 89 | | for (var i = 0; i < start.Value; i++) |
| | 56 | 90 | | result.Add(target[i]); |
| | | 91 | | |
| | 42 | 92 | | string? lastSuffix = null; |
| | 224 | 93 | | for (var j = 0; j < search.Count; j++) |
| | | 94 | | { |
| | 70 | 95 | | var raw = target[start.Value + j]; |
| | 70 | 96 | | var s = searchTrimmed[j]; |
| | 70 | 97 | | var hasReplacement = j < replace.Count; |
| | | 98 | | |
| | | 99 | | // Single-line search whose fragment starts the line while the line continues |
| | | 100 | | // after it: the model cut the end of the line — replace the WHOLE line. |
| | 70 | 101 | | if (search.Count == 1 && raw.StartsWith(s, StringComparison.OrdinalIgnoreCase) && raw.Length > s.Length) |
| | | 102 | | { |
| | 4 | 103 | | if (hasReplacement) |
| | 4 | 104 | | result.Add(replace[0]); |
| | 4 | 105 | | continue; |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | // Whole-line match: the replacement is used VERBATIM (a complete line with its |
| | | 109 | | // own indentation, e.g. a re-nested block). A missing replacement DELETES the line. |
| | 66 | 110 | | if (string.Equals(raw.Trim(), s, StringComparison.OrdinalIgnoreCase)) |
| | | 111 | | { |
| | 42 | 112 | | if (hasReplacement) |
| | 28 | 113 | | result.Add(replace[j]); |
| | 28 | 114 | | continue; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // Fragment (truncated boundary line): only the matched part is removed/replaced; |
| | | 118 | | // the rest of the line (leading indentation and the trailing part) is preserved. |
| | 24 | 119 | | var pos = FragmentPosition(raw, s, search.Count, j); |
| | 24 | 120 | | var prefix = raw.Substring(0, pos); |
| | 24 | 121 | | var suffix = raw.Substring(pos + s.Length); |
| | | 122 | | |
| | 24 | 123 | | if (hasReplacement) |
| | | 124 | | { |
| | 16 | 125 | | result.Add(prefix + replace[j].TrimStart()); |
| | 16 | 126 | | if (j == search.Count - 1) |
| | 12 | 127 | | lastSuffix = suffix; |
| | | 128 | | } |
| | 8 | 129 | | else if (j == search.Count - 1 && search.Count > 1) |
| | | 130 | | { |
| | | 131 | | // Last boundary line without a replacement: the prefix is the leading |
| | | 132 | | // indentation — it is absorbed and the suffix joins the last emitted line |
| | | 133 | | // (legacy semantics, no whitespace-only lines are introduced). |
| | 8 | 134 | | lastSuffix = suffix; |
| | | 135 | | } |
| | | 136 | | else |
| | | 137 | | { |
| | | 138 | | // First boundary line or single-line fragment without a replacement: |
| | | 139 | | // only the fragment is deleted — the rest of the line stays on its own line. |
| | 0 | 140 | | var rest = prefix + suffix; |
| | 0 | 141 | | if (rest.Trim().Length > 0) |
| | 0 | 142 | | result.Add(rest); |
| | | 143 | | } |
| | | 144 | | } |
| | | 145 | | |
| | | 146 | | // Extra replacement lines are inserted after the last matched line. |
| | 104 | 147 | | for (var j = search.Count; j < replace.Count; j++) |
| | 10 | 148 | | result.Add(replace[j]); |
| | | 149 | | |
| | | 150 | | // The trailing part of the last matched line stays attached to the last emitted |
| | | 151 | | // line (an extra replacement line, when present); when the whole matched block |
| | | 152 | | // was deleted, it attaches to the preceding text (or becomes the first line). |
| | 42 | 153 | | if (lastSuffix != null) |
| | | 154 | | { |
| | 20 | 155 | | if (result.Count > 0) |
| | 18 | 156 | | result[result.Count - 1] += lastSuffix; |
| | | 157 | | else |
| | 2 | 158 | | result.Add(lastSuffix); |
| | | 159 | | } |
| | | 160 | | |
| | 136 | 161 | | for (var i = start.Value + search.Count; i < target.Count; i++) |
| | 26 | 162 | | result.Add(target[i]); |
| | | 163 | | |
| | 42 | 164 | | target.Clear(); |
| | 42 | 165 | | target.AddRange(result); |
| | 42 | 166 | | return start.Value; |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Position of the matched fragment within the raw target line: |
| | | 171 | | /// single-line search — the leftmost occurrence (legacy semantics, consistent |
| | | 172 | | /// with FindInFile); first boundary line (suffix match) — the rightmost occurrence |
| | | 173 | | /// (the fragment ends the line); last boundary line (prefix match) — right after |
| | | 174 | | /// the leading indentation (the fragment starts the line). |
| | | 175 | | /// </summary> |
| | | 176 | | private static int FragmentPosition(string raw, string s, int searchCount, int j) |
| | | 177 | | { |
| | 24 | 178 | | if (searchCount == 1) |
| | 8 | 179 | | return raw.IndexOf(s, StringComparison.OrdinalIgnoreCase); |
| | 16 | 180 | | if (j == 0) |
| | 4 | 181 | | return raw.LastIndexOf(s, StringComparison.OrdinalIgnoreCase); |
| | 12 | 182 | | return raw.Length - raw.TrimStart().Length; |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | /// <summary> |
| | | 186 | | /// Finds the first match of the (trimmed) search block. When hint is given, prefers |
| | | 187 | | /// matches within the tolerance range around the hint line; otherwise prefers a match |
| | | 188 | | /// where every search line occupies its whole line (exact match) over a partial |
| | | 189 | | /// (fragment) match on an earlier line. |
| | | 190 | | /// </summary> |
| | | 191 | | /// <returns>0-based start line of the match, or null if not found.</returns> |
| | | 192 | | private static int? FindMatchTrimmed(List<string> target, string[] searchTrimmed, int hint, int tol) |
| | | 193 | | { |
| | 182 | 194 | | if (searchTrimmed.Length > target.Count) |
| | 0 | 195 | | return null; |
| | 182 | 196 | | if (tol < 0) |
| | 4 | 197 | | tol = 0; |
| | | 198 | | |
| | | 199 | | // All search lines are empty: match the first empty/whitespace-only line |
| | | 200 | | // (within the hint tolerance range when a hint is given). |
| | 182 | 201 | | if (searchTrimmed.All(s => s.Length == 0)) |
| | 10 | 202 | | return FindEmptyLine(target, hint, tol); |
| | | 203 | | |
| | 172 | 204 | | int? fallback = null; |
| | 172 | 205 | | var minLine = hint < 0 ? 0 : Math.Max(0, hint - 1 - tol); |
| | 172 | 206 | | var maxLine = hint < 0 ? int.MaxValue : hint - 1 + tol; |
| | | 207 | | |
| | 920 | 208 | | for (var i = 0; i + searchTrimmed.Length <= target.Count; i++) |
| | | 209 | | { |
| | 386 | 210 | | if (!LinesMatch(target, i, searchTrimmed)) |
| | | 211 | | continue; |
| | | 212 | | |
| | 156 | 213 | | fallback ??= i; |
| | | 214 | | |
| | 156 | 215 | | if (hint >= 0) |
| | | 216 | | { |
| | | 217 | | // Hint-based search: the first match within the tolerance range around the |
| | | 218 | | // hint wins; if none, fall back to the first match anywhere in the file. |
| | 54 | 219 | | if (i >= minLine && i <= maxLine) |
| | 50 | 220 | | return i; |
| | | 221 | | } |
| | 102 | 222 | | else if (IsWholeLineBlock(target, i, searchTrimmed)) |
| | | 223 | | { |
| | | 224 | | // Full search: prefer a match where every line occupies its whole line |
| | | 225 | | // (exact match) — a fragment match on an earlier line must not shadow it. |
| | 48 | 226 | | return i; |
| | | 227 | | } |
| | | 228 | | } |
| | | 229 | | |
| | 74 | 230 | | return fallback; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// Checks whether the search block matches the target lines starting at <paramref name="start"/>. |
| | | 235 | | /// </summary> |
| | | 236 | | private static bool LinesMatch(List<string> target, int start, string[] searchTrimmed) |
| | | 237 | | { |
| | 1348 | 238 | | for (var j = 0; j < searchTrimmed.Length; j++) |
| | | 239 | | { |
| | 518 | 240 | | var t = target[start + j].Trim(); |
| | 518 | 241 | | var s = searchTrimmed[j]; |
| | | 242 | | |
| | | 243 | | // Empty search line ↔ empty/whitespace-only target line. |
| | 518 | 244 | | if (s.Length == 0) |
| | | 245 | | { |
| | 10 | 246 | | if (t.Length != 0) |
| | 4 | 247 | | return false; |
| | | 248 | | continue; |
| | | 249 | | } |
| | | 250 | | |
| | 508 | 251 | | if (searchTrimmed.Length == 1) |
| | | 252 | | { |
| | | 253 | | // Single-line search: substring match. |
| | 172 | 254 | | if (t.IndexOf(s, StringComparison.OrdinalIgnoreCase) < 0) |
| | 88 | 255 | | return false; |
| | | 256 | | } |
| | 336 | 257 | | else if (j == 0) |
| | | 258 | | { |
| | | 259 | | // First boundary line: may be truncated at the START (suffix match). |
| | 214 | 260 | | if (!t.EndsWith(s, StringComparison.OrdinalIgnoreCase)) |
| | 122 | 261 | | return false; |
| | | 262 | | } |
| | 122 | 263 | | else if (j == searchTrimmed.Length - 1) |
| | | 264 | | { |
| | | 265 | | // Last boundary line: may be truncated at the END (prefix match). |
| | 78 | 266 | | if (!t.StartsWith(s, StringComparison.OrdinalIgnoreCase)) |
| | 6 | 267 | | return false; |
| | | 268 | | } |
| | 44 | 269 | | else if (!string.Equals(t, s, StringComparison.OrdinalIgnoreCase)) |
| | | 270 | | { |
| | | 271 | | // Middle lines must match exactly. |
| | 10 | 272 | | return false; |
| | | 273 | | } |
| | | 274 | | } |
| | | 275 | | |
| | 156 | 276 | | return true; |
| | | 277 | | } |
| | | 278 | | |
| | | 279 | | /// <summary> |
| | | 280 | | /// Checks whether every search line of the block matches its target line exactly. |
| | | 281 | | /// </summary> |
| | | 282 | | private static bool IsWholeLineBlock(List<string> target, int start, string[] searchTrimmed) |
| | | 283 | | { |
| | 432 | 284 | | for (var j = 0; j < searchTrimmed.Length; j++) |
| | | 285 | | { |
| | 168 | 286 | | if (!string.Equals(target[start + j].Trim(), searchTrimmed[j], StringComparison.OrdinalIgnoreCase)) |
| | 54 | 287 | | return false; |
| | | 288 | | } |
| | 48 | 289 | | return true; |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | /// <summary>0-based index of the first empty/whitespace-only line, or null.</summary> |
| | | 293 | | private static int? FindEmptyLine(List<string> target, int hint, int tol) |
| | | 294 | | { |
| | 10 | 295 | | if (hint < 0) |
| | | 296 | | { |
| | 10 | 297 | | var idx = target.FindIndex(string.IsNullOrWhiteSpace); |
| | 10 | 298 | | return idx < 0 ? null : idx; |
| | | 299 | | } |
| | | 300 | | |
| | 0 | 301 | | var min = Math.Max(0, hint - 1 - tol); |
| | 0 | 302 | | var max = hint - 1 + tol; |
| | 0 | 303 | | for (var i = min; i <= max && i < target.Count; i++) |
| | | 304 | | { |
| | 0 | 305 | | if (string.IsNullOrWhiteSpace(target[i])) |
| | 0 | 306 | | return i; |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | // Fall back to the first empty line anywhere. |
| | 0 | 310 | | var fallback = target.FindIndex(string.IsNullOrWhiteSpace); |
| | 0 | 311 | | return fallback < 0 ? null : fallback; |
| | | 312 | | } |
| | | 313 | | } |