< Summary

Information
Class: ToolCore.EditApplier
Assembly: ToolCore
File(s): /home/runner/work/InvAit/InvAit/ToolCore/EditApplier.cs
Tag: 194_44631168438
Line coverage
84%
Covered lines: 94
Uncovered lines: 17
Coverable lines: 111
Total lines: 313
Line coverage: 84.6%
Branch coverage
80%
Covered branches: 98
Total branches: 122
Branch coverage: 80.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
FindInFile(...)50%9875%
ApplyEdit(...)80%595084.61%
FragmentPosition(...)100%44100%
FindMatchTrimmed(...)95.83%242494.44%
LinesMatch(...)100%2020100%
IsWholeLineBlock(...)100%44100%
FindEmptyLine(...)25%611230%

File(s)

/home/runner/work/InvAit/InvAit/ToolCore/EditApplier.cs

#LineLine coverage
 1namespace 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>
 37public 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    {
 13849        if (target == null || search == null || search.Count == 0 || search.Count > target.Count)
 050            return -1;
 51
 13852        var searchTrimmed = search.Select(l => l.Trim()).ToArray();
 13853        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    {
 5068        if (target == null || search == null || replace == null)
 669            return -1;
 4470        if (search.Count == 0 || search.Count > target.Count)
 071            return -1;
 72
 4473        var searchTrimmed = search.Select(l => l.Trim()).ToArray();
 74
 4475        var start = FindMatchTrimmed(target, searchTrimmed, hint, tol);
 4476        if (start == null)
 277            return -1;
 78
 79        // All search lines are empty: replace the matched empty line with the replacement block.
 4280        if (searchTrimmed.All(s => s.Length == 0))
 81        {
 082            target.RemoveAt(start.Value);
 083            for (var j = replace.Count - 1; j >= 0; j--)
 084                target.Insert(start.Value, replace[j]);
 085            return start.Value;
 86        }
 87
 4288        var result = new List<string>(target.Count);
 19689        for (var i = 0; i < start.Value; i++)
 5690            result.Add(target[i]);
 91
 4292        string? lastSuffix = null;
 22493        for (var j = 0; j < search.Count; j++)
 94        {
 7095            var raw = target[start.Value + j];
 7096            var s = searchTrimmed[j];
 7097            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.
 70101            if (search.Count == 1 && raw.StartsWith(s, StringComparison.OrdinalIgnoreCase) && raw.Length > s.Length)
 102            {
 4103                if (hasReplacement)
 4104                    result.Add(replace[0]);
 4105                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.
 66110            if (string.Equals(raw.Trim(), s, StringComparison.OrdinalIgnoreCase))
 111            {
 42112                if (hasReplacement)
 28113                    result.Add(replace[j]);
 28114                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.
 24119            var pos = FragmentPosition(raw, s, search.Count, j);
 24120            var prefix = raw.Substring(0, pos);
 24121            var suffix = raw.Substring(pos + s.Length);
 122
 24123            if (hasReplacement)
 124            {
 16125                result.Add(prefix + replace[j].TrimStart());
 16126                if (j == search.Count - 1)
 12127                    lastSuffix = suffix;
 128            }
 8129            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).
 8134                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.
 0140                var rest = prefix + suffix;
 0141                if (rest.Trim().Length > 0)
 0142                    result.Add(rest);
 143            }
 144        }
 145
 146        // Extra replacement lines are inserted after the last matched line.
 104147        for (var j = search.Count; j < replace.Count; j++)
 10148            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).
 42153        if (lastSuffix != null)
 154        {
 20155            if (result.Count > 0)
 18156                result[result.Count - 1] += lastSuffix;
 157            else
 2158                result.Add(lastSuffix);
 159        }
 160
 136161        for (var i = start.Value + search.Count; i < target.Count; i++)
 26162            result.Add(target[i]);
 163
 42164        target.Clear();
 42165        target.AddRange(result);
 42166        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    {
 24178        if (searchCount == 1)
 8179            return raw.IndexOf(s, StringComparison.OrdinalIgnoreCase);
 16180        if (j == 0)
 4181            return raw.LastIndexOf(s, StringComparison.OrdinalIgnoreCase);
 12182        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    {
 182194        if (searchTrimmed.Length > target.Count)
 0195            return null;
 182196        if (tol < 0)
 4197            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).
 182201        if (searchTrimmed.All(s => s.Length == 0))
 10202            return FindEmptyLine(target, hint, tol);
 203
 172204        int? fallback = null;
 172205        var minLine = hint < 0 ? 0 : Math.Max(0, hint - 1 - tol);
 172206        var maxLine = hint < 0 ? int.MaxValue : hint - 1 + tol;
 207
 920208        for (var i = 0; i + searchTrimmed.Length <= target.Count; i++)
 209        {
 386210            if (!LinesMatch(target, i, searchTrimmed))
 211                continue;
 212
 156213            fallback ??= i;
 214
 156215            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.
 54219                if (i >= minLine && i <= maxLine)
 50220                    return i;
 221            }
 102222            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.
 48226                return i;
 227            }
 228        }
 229
 74230        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    {
 1348238        for (var j = 0; j < searchTrimmed.Length; j++)
 239        {
 518240            var t = target[start + j].Trim();
 518241            var s = searchTrimmed[j];
 242
 243            // Empty search line ↔ empty/whitespace-only target line.
 518244            if (s.Length == 0)
 245            {
 10246                if (t.Length != 0)
 4247                    return false;
 248                continue;
 249            }
 250
 508251            if (searchTrimmed.Length == 1)
 252            {
 253                // Single-line search: substring match.
 172254                if (t.IndexOf(s, StringComparison.OrdinalIgnoreCase) < 0)
 88255                    return false;
 256            }
 336257            else if (j == 0)
 258            {
 259                // First boundary line: may be truncated at the START (suffix match).
 214260                if (!t.EndsWith(s, StringComparison.OrdinalIgnoreCase))
 122261                    return false;
 262            }
 122263            else if (j == searchTrimmed.Length - 1)
 264            {
 265                // Last boundary line: may be truncated at the END (prefix match).
 78266                if (!t.StartsWith(s, StringComparison.OrdinalIgnoreCase))
 6267                    return false;
 268            }
 44269            else if (!string.Equals(t, s, StringComparison.OrdinalIgnoreCase))
 270            {
 271                // Middle lines must match exactly.
 10272                return false;
 273            }
 274        }
 275
 156276        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    {
 432284        for (var j = 0; j < searchTrimmed.Length; j++)
 285        {
 168286            if (!string.Equals(target[start + j].Trim(), searchTrimmed[j], StringComparison.OrdinalIgnoreCase))
 54287                return false;
 288        }
 48289        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    {
 10295        if (hint < 0)
 296        {
 10297            var idx = target.FindIndex(string.IsNullOrWhiteSpace);
 10298            return idx < 0 ? null : idx;
 299        }
 300
 0301        var min = Math.Max(0, hint - 1 - tol);
 0302        var max = hint - 1 + tol;
 0303        for (var i = min; i <= max && i < target.Count; i++)
 304        {
 0305            if (string.IsNullOrWhiteSpace(target[i]))
 0306                return i;
 307        }
 308
 309        // Fall back to the first empty line anywhere.
 0310        var fallback = target.FindIndex(string.IsNullOrWhiteSpace);
 0311        return fallback < 0 ? null : fallback;
 312    }
 313}