| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | namespace RoleRadar.Domain.Notes; |
| | | 4 | | |
| | | 5 | | public enum SectionReplacementStatus |
| | | 6 | | { |
| | | 7 | | Success, |
| | | 8 | | SectionNotFound, |
| | | 9 | | AmbiguousHeading |
| | | 10 | | } |
| | | 11 | | |
| | 22 | 12 | | public sealed record SectionReplacementOutcome( |
| | 30 | 13 | | SectionReplacementStatus Status, |
| | 32 | 14 | | string? UpdatedBody, |
| | 8 | 15 | | IReadOnlyList<string> AvailableHeadings, |
| | 24 | 16 | | IReadOnlyList<string> MatchingHeadings); |
| | | 17 | | |
| | | 18 | | public sealed record ParsedMarkdownHeading( |
| | | 19 | | int Level, |
| | | 20 | | string RawHeadingLine, |
| | | 21 | | string TitleText, |
| | | 22 | | string NormalizedMarkerTitle, |
| | | 23 | | string HeadingPath, |
| | | 24 | | int StartCharIndex, |
| | | 25 | | int HeadingLineEndCharIndex, |
| | | 26 | | int SectionEndCharIndex, |
| | | 27 | | string LineEnding); |
| | | 28 | | |
| | | 29 | | public static class MarkdownSectionParser |
| | | 30 | | { |
| | | 31 | | public static SectionReplacementOutcome ReplaceSection( |
| | | 32 | | string originalBody, |
| | | 33 | | string targetHeading, |
| | | 34 | | string newSectionBody) |
| | | 35 | | { |
| | | 36 | | ArgumentNullException.ThrowIfNull(originalBody); |
| | | 37 | | ArgumentNullException.ThrowIfNull(newSectionBody); |
| | | 38 | | |
| | | 39 | | if (string.IsNullOrWhiteSpace(targetHeading)) |
| | | 40 | | { |
| | | 41 | | return new SectionReplacementOutcome( |
| | | 42 | | SectionReplacementStatus.SectionNotFound, |
| | | 43 | | null, |
| | | 44 | | [], |
| | | 45 | | []); |
| | | 46 | | } |
| | | 47 | | |
| | | 48 | | var headings = ParseHeadings(originalBody); |
| | | 49 | | var availablePaths = headings.Select(h => h.HeadingPath).ToArray(); |
| | | 50 | | |
| | | 51 | | if (headings.Count == 0) |
| | | 52 | | { |
| | | 53 | | return new SectionReplacementOutcome( |
| | | 54 | | SectionReplacementStatus.SectionNotFound, |
| | | 55 | | null, |
| | | 56 | | availablePaths, |
| | | 57 | | []); |
| | | 58 | | } |
| | | 59 | | |
| | | 60 | | var trimmedTarget = targetHeading.Trim(); |
| | | 61 | | var matches = FindMatchingHeadings(headings, trimmedTarget); |
| | | 62 | | |
| | | 63 | | if (matches.Count == 0) |
| | | 64 | | { |
| | | 65 | | return new SectionReplacementOutcome( |
| | | 66 | | SectionReplacementStatus.SectionNotFound, |
| | | 67 | | null, |
| | | 68 | | availablePaths, |
| | | 69 | | []); |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | if (matches.Count > 1) |
| | | 73 | | { |
| | | 74 | | return new SectionReplacementOutcome( |
| | | 75 | | SectionReplacementStatus.AmbiguousHeading, |
| | | 76 | | null, |
| | | 77 | | availablePaths, |
| | | 78 | | matches.Select(m => m.HeadingPath).ToArray()); |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | var target = matches[0]; |
| | | 82 | | var dominantNewline = DetectDominantLineEnding(originalBody, target.LineEnding); |
| | | 83 | | var formattedReplacement = BuildReplacementSectionText(target, newSectionBody, dominantNewline); |
| | | 84 | | |
| | | 85 | | var sb = new StringBuilder(originalBody.Length + formattedReplacement.Length); |
| | | 86 | | sb.Append(originalBody.AsSpan(0, target.StartCharIndex)); |
| | | 87 | | sb.Append(formattedReplacement); |
| | | 88 | | sb.Append(originalBody.AsSpan(target.SectionEndCharIndex)); |
| | | 89 | | |
| | | 90 | | return new SectionReplacementOutcome( |
| | | 91 | | SectionReplacementStatus.Success, |
| | | 92 | | sb.ToString(), |
| | | 93 | | availablePaths, |
| | | 94 | | [target.HeadingPath]); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | public static IReadOnlyList<ParsedMarkdownHeading> ParseHeadings(string markdown) |
| | | 98 | | { |
| | | 99 | | ArgumentNullException.ThrowIfNull(markdown); |
| | | 100 | | |
| | | 101 | | var rawHeadings = new List<(int Level, string RawLine, string TitleText, int StartIdx, int LineEndIdx, string Li |
| | | 102 | | var inFence = false; |
| | | 103 | | var fenceChar = '\0'; |
| | | 104 | | var fenceLen = 0; |
| | | 105 | | |
| | | 106 | | var pos = 0; |
| | | 107 | | var len = markdown.Length; |
| | | 108 | | |
| | | 109 | | while (pos < len) |
| | | 110 | | { |
| | | 111 | | var lineStart = pos; |
| | | 112 | | while (pos < len && markdown[pos] != '\r' && markdown[pos] != '\n') |
| | | 113 | | { |
| | | 114 | | pos++; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | var contentEnd = pos; |
| | | 118 | | var lineEnding = "\n"; |
| | | 119 | | if (pos < len) |
| | | 120 | | { |
| | | 121 | | if (markdown[pos] == '\r' && pos + 1 < len && markdown[pos + 1] == '\n') |
| | | 122 | | { |
| | | 123 | | lineEnding = "\r\n"; |
| | | 124 | | pos += 2; |
| | | 125 | | } |
| | | 126 | | else |
| | | 127 | | { |
| | | 128 | | lineEnding = markdown[pos].ToString(); |
| | | 129 | | pos += 1; |
| | | 130 | | } |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | var lineSpan = markdown.AsSpan(lineStart, contentEnd - lineStart); |
| | | 134 | | if (TryUpdateFenceState(lineSpan, ref inFence, ref fenceChar, ref fenceLen)) |
| | | 135 | | { |
| | | 136 | | continue; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | if (inFence) |
| | | 140 | | { |
| | | 141 | | continue; |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | if (TryParseAtxHeading(lineSpan, out var level, out var titleText)) |
| | | 145 | | { |
| | | 146 | | rawHeadings.Add(( |
| | | 147 | | Level: level, |
| | | 148 | | RawLine: lineSpan.ToString(), |
| | | 149 | | TitleText: titleText, |
| | | 150 | | StartIdx: lineStart, |
| | | 151 | | LineEndIdx: pos, |
| | | 152 | | LineEnding: lineEnding)); |
| | | 153 | | } |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | if (rawHeadings.Count == 0) |
| | | 157 | | { |
| | | 158 | | return []; |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | var result = new List<ParsedMarkdownHeading>(rawHeadings.Count); |
| | | 162 | | var ancestorStack = new List<(int Level, string NormalizedMarkerTitle)>(); |
| | | 163 | | |
| | | 164 | | for (var i = 0; i < rawHeadings.Count; i++) |
| | | 165 | | { |
| | | 166 | | var current = rawHeadings[i]; |
| | | 167 | | var hashes = new string('#', current.Level); |
| | | 168 | | var normalizedMarkerTitle = string.IsNullOrEmpty(current.TitleText) |
| | | 169 | | ? hashes |
| | | 170 | | : $"{hashes} {current.TitleText}"; |
| | | 171 | | |
| | | 172 | | while (ancestorStack.Count > 0 && ancestorStack[^1].Level >= current.Level) |
| | | 173 | | { |
| | | 174 | | ancestorStack.RemoveAt(ancestorStack.Count - 1); |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | ancestorStack.Add((current.Level, normalizedMarkerTitle)); |
| | | 178 | | var headingPath = string.Join(" / ", ancestorStack.Select(a => a.NormalizedMarkerTitle)); |
| | | 179 | | |
| | | 180 | | var sectionEndIdx = len; |
| | | 181 | | for (var j = i + 1; j < rawHeadings.Count; j++) |
| | | 182 | | { |
| | | 183 | | if (rawHeadings[j].Level <= current.Level) |
| | | 184 | | { |
| | | 185 | | sectionEndIdx = rawHeadings[j].StartIdx; |
| | | 186 | | break; |
| | | 187 | | } |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | result.Add(new ParsedMarkdownHeading( |
| | | 191 | | Level: current.Level, |
| | | 192 | | RawHeadingLine: current.RawLine, |
| | | 193 | | TitleText: current.TitleText, |
| | | 194 | | NormalizedMarkerTitle: normalizedMarkerTitle, |
| | | 195 | | HeadingPath: headingPath, |
| | | 196 | | StartCharIndex: current.StartIdx, |
| | | 197 | | HeadingLineEndCharIndex: current.LineEndIdx, |
| | | 198 | | SectionEndCharIndex: sectionEndIdx, |
| | | 199 | | LineEnding: current.LineEnding)); |
| | | 200 | | } |
| | | 201 | | |
| | | 202 | | return result; |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | private static List<ParsedMarkdownHeading> FindMatchingHeadings( |
| | | 206 | | IReadOnlyList<ParsedMarkdownHeading> headings, |
| | | 207 | | string targetHeading) |
| | | 208 | | { |
| | | 209 | | if (targetHeading.Contains('/', StringComparison.Ordinal)) |
| | | 210 | | { |
| | | 211 | | var normalizedSegments = targetHeading |
| | | 212 | | .Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
| | | 213 | | |
| | | 214 | | return headings |
| | | 215 | | .Where(h => HeadingPathMatches(h.HeadingPath, normalizedSegments)) |
| | | 216 | | .ToList(); |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | var strippedTarget = StripLeadingHashes(targetHeading); |
| | | 220 | | var hasExplicitHashes = targetHeading.StartsWith('#'); |
| | | 221 | | |
| | | 222 | | return headings |
| | | 223 | | .Where(h => |
| | | 224 | | { |
| | | 225 | | if (hasExplicitHashes) |
| | | 226 | | { |
| | | 227 | | return string.Equals(h.NormalizedMarkerTitle, NormalizeMarkerHeading(targetHeading), StringCompariso |
| | | 228 | | } |
| | | 229 | | |
| | | 230 | | return string.Equals(h.TitleText, strippedTarget, StringComparison.OrdinalIgnoreCase) || |
| | | 231 | | string.Equals(h.NormalizedMarkerTitle, targetHeading, StringComparison.OrdinalIgnoreCase); |
| | | 232 | | }) |
| | | 233 | | .ToList(); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | private static bool HeadingPathMatches(string headingPath, string[] querySegments) |
| | | 237 | | { |
| | | 238 | | var pathSegments = headingPath.Split(" / ", StringSplitOptions.None); |
| | | 239 | | if (querySegments.Length > pathSegments.Length) |
| | | 240 | | { |
| | | 241 | | return false; |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | var offset = pathSegments.Length - querySegments.Length; |
| | | 245 | | for (var i = 0; i < querySegments.Length; i++) |
| | | 246 | | { |
| | | 247 | | var candidate = pathSegments[offset + i]; |
| | | 248 | | var querySeg = querySegments[i]; |
| | | 249 | | if (querySeg.StartsWith('#')) |
| | | 250 | | { |
| | | 251 | | if (!string.Equals(candidate, NormalizeMarkerHeading(querySeg), StringComparison.OrdinalIgnoreCase)) |
| | | 252 | | { |
| | | 253 | | return false; |
| | | 254 | | } |
| | | 255 | | } |
| | | 256 | | else |
| | | 257 | | { |
| | | 258 | | var candidateStripped = StripLeadingHashes(candidate); |
| | | 259 | | if (!string.Equals(candidateStripped, querySeg, StringComparison.OrdinalIgnoreCase)) |
| | | 260 | | { |
| | | 261 | | return false; |
| | | 262 | | } |
| | | 263 | | } |
| | | 264 | | } |
| | | 265 | | |
| | | 266 | | return true; |
| | | 267 | | } |
| | | 268 | | |
| | | 269 | | private static string NormalizeMarkerHeading(string input) |
| | | 270 | | { |
| | | 271 | | var trimmed = input.Trim(); |
| | | 272 | | var i = 0; |
| | | 273 | | while (i < trimmed.Length && trimmed[i] == '#') |
| | | 274 | | { |
| | | 275 | | i++; |
| | | 276 | | } |
| | | 277 | | |
| | | 278 | | var hashes = trimmed[..i]; |
| | | 279 | | var rest = trimmed[i..].Trim(); |
| | | 280 | | return string.IsNullOrEmpty(rest) ? hashes : $"{hashes} {rest}"; |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | private static string StripLeadingHashes(string input) |
| | | 284 | | { |
| | | 285 | | var trimmed = input.Trim(); |
| | | 286 | | var i = 0; |
| | | 287 | | while (i < trimmed.Length && trimmed[i] == '#') |
| | | 288 | | { |
| | | 289 | | i++; |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | return trimmed[i..].Trim(); |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | private static string BuildReplacementSectionText( |
| | | 296 | | ParsedMarkdownHeading target, |
| | | 297 | | string newSectionBody, |
| | | 298 | | string newline) |
| | | 299 | | { |
| | | 300 | | var startsWithHeading = StartsWithSameHeading(newSectionBody, target); |
| | | 301 | | var builder = new StringBuilder(newSectionBody.Length + target.RawHeadingLine.Length + 4); |
| | | 302 | | |
| | | 303 | | if (!startsWithHeading) |
| | | 304 | | { |
| | | 305 | | builder.Append(target.RawHeadingLine).Append(newline); |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | builder.Append(newSectionBody); |
| | | 309 | | if (builder.Length > 0 && builder[^1] != '\n' && builder[^1] != '\r') |
| | | 310 | | { |
| | | 311 | | builder.Append(newline); |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | return builder.ToString(); |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | private static bool StartsWithSameHeading(string newSectionBody, ParsedMarkdownHeading target) |
| | | 318 | | { |
| | | 319 | | var span = newSectionBody.AsSpan().TrimStart(); |
| | | 320 | | var lineEnd = 0; |
| | | 321 | | while (lineEnd < span.Length && span[lineEnd] != '\r' && span[lineEnd] != '\n') |
| | | 322 | | { |
| | | 323 | | lineEnd++; |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | var firstLine = span[..lineEnd]; |
| | | 327 | | if (!TryParseAtxHeading(firstLine, out var level, out var titleText)) |
| | | 328 | | { |
| | | 329 | | return false; |
| | | 330 | | } |
| | | 331 | | |
| | | 332 | | return level == target.Level && |
| | | 333 | | string.Equals(titleText, target.TitleText, StringComparison.OrdinalIgnoreCase); |
| | | 334 | | } |
| | | 335 | | |
| | | 336 | | private static string DetectDominantLineEnding(string body, string fallback) |
| | | 337 | | { |
| | | 338 | | var idx = body.IndexOf('\n'); |
| | | 339 | | if (idx > 0 && body[idx - 1] == '\r') |
| | | 340 | | { |
| | | 341 | | return "\r\n"; |
| | | 342 | | } |
| | | 343 | | |
| | | 344 | | if (idx >= 0) |
| | | 345 | | { |
| | | 346 | | return "\n"; |
| | | 347 | | } |
| | | 348 | | |
| | | 349 | | return fallback; |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | public static bool TryUpdateFenceState( |
| | | 353 | | ReadOnlySpan<char> lineSpan, |
| | | 354 | | ref bool inFence, |
| | | 355 | | ref char fenceChar, |
| | | 356 | | ref int fenceLen) |
| | | 357 | | { |
| | | 358 | | var leadingSpaces = 0; |
| | | 359 | | while (leadingSpaces < lineSpan.Length && leadingSpaces < 3 && lineSpan[leadingSpaces] == ' ') |
| | | 360 | | { |
| | | 361 | | leadingSpaces++; |
| | | 362 | | } |
| | | 363 | | |
| | | 364 | | var trimmed = lineSpan[leadingSpaces..]; |
| | | 365 | | if (trimmed.Length < 3) |
| | | 366 | | { |
| | | 367 | | return false; |
| | | 368 | | } |
| | | 369 | | |
| | | 370 | | var first = trimmed[0]; |
| | | 371 | | if (first != '`' && first != '~') |
| | | 372 | | { |
| | | 373 | | return false; |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | var run = 0; |
| | | 377 | | while (run < trimmed.Length && trimmed[run] == first) |
| | | 378 | | { |
| | | 379 | | run++; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | if (run < 3) |
| | | 383 | | { |
| | | 384 | | return false; |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | if (!inFence) |
| | | 388 | | { |
| | | 389 | | inFence = true; |
| | | 390 | | fenceChar = first; |
| | | 391 | | fenceLen = run; |
| | | 392 | | return true; |
| | | 393 | | } |
| | | 394 | | |
| | | 395 | | if (first == fenceChar && run >= fenceLen && trimmed[run..].Trim().IsEmpty) |
| | | 396 | | { |
| | | 397 | | inFence = false; |
| | | 398 | | fenceChar = '\0'; |
| | | 399 | | fenceLen = 0; |
| | | 400 | | return true; |
| | | 401 | | } |
| | | 402 | | |
| | | 403 | | return false; |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | public static bool TryParseAtxHeading( |
| | | 407 | | ReadOnlySpan<char> lineSpan, |
| | | 408 | | out int level, |
| | | 409 | | out string titleText) |
| | | 410 | | { |
| | | 411 | | level = 0; |
| | | 412 | | titleText = string.Empty; |
| | | 413 | | |
| | | 414 | | var leadingSpaces = 0; |
| | | 415 | | while (leadingSpaces < lineSpan.Length && leadingSpaces < 3 && lineSpan[leadingSpaces] == ' ') |
| | | 416 | | { |
| | | 417 | | leadingSpaces++; |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | var span = lineSpan[leadingSpaces..]; |
| | | 421 | | if (span.IsEmpty || span[0] != '#') |
| | | 422 | | { |
| | | 423 | | return false; |
| | | 424 | | } |
| | | 425 | | |
| | | 426 | | var hashes = 0; |
| | | 427 | | while (hashes < span.Length && span[hashes] == '#') |
| | | 428 | | { |
| | | 429 | | hashes++; |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | if (hashes is < 1 or > 6) |
| | | 433 | | { |
| | | 434 | | return false; |
| | | 435 | | } |
| | | 436 | | |
| | | 437 | | var rest = span[hashes..]; |
| | | 438 | | if (!rest.IsEmpty && rest[0] != ' ' && rest[0] != '\t') |
| | | 439 | | { |
| | | 440 | | return false; |
| | | 441 | | } |
| | | 442 | | |
| | | 443 | | level = hashes; |
| | | 444 | | titleText = rest.Trim().ToString(); |
| | | 445 | | return true; |
| | | 446 | | } |
| | | 447 | | } |