< Summary

Information
Class: RoleRadar.Domain.Notes.MarkdownImportParser
Assembly: RoleRadar.Domain
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Domain/Notes/MarkdownImportParser.cs
Line coverage
88%
Covered lines: 176
Uncovered lines: 23
Coverable lines: 199
Total lines: 435
Line coverage: 88.4%
Branch coverage
82%
Covered branches: 117
Total branches: 142
Branch coverage: 82.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
ValidateUtf8(...)100%11100%
ParseBytes(...)50%2280%
Parse(...)80.76%312681.17%
get_LineIndex()100%11100%
get_LineIndex()100%11100%
SplitLines(...)100%2424100%
FindSplitHeadings(...)100%1616100%
IsIndentedCodeLine(...)75%8887.5%
TryParseAtxHeading(...)80.76%262695.23%
StripTrailingClosingHashes(...)50%352066.66%
ExtractSectionProvenance(...)90%2020100%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Domain/Notes/MarkdownImportParser.cs

#LineLine coverage
 1using System.Text;
 2using System.Text.RegularExpressions;
 3using RoleRadar.Domain.Common;
 4
 5namespace RoleRadar.Domain.Notes;
 6
 7public sealed record ParsedImportSection(
 8    string SourceFileId,
 9    string HeadingPath,
 10    int OccurrenceIndex,
 11    int SectionOrderIndex,
 12    string Title,
 13    string Body,
 14    ProvenanceMarker Provenance,
 15    string BodyHash,
 16    string ImportKey);
 17
 18public static partial class MarkdownImportParser
 19{
 820    private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: t
 21
 22    [GeneratedRegex(@"\[(stated|researched|inferred)(?:\s+(\d{4}-\d{2}-\d{2})(?:\s+([^\]]+?))?)?\]", RegexOptions.Compil
 23    private static partial Regex ProvenanceTagRegex();
 24
 25    public static bool ValidateUtf8(ReadOnlySpan<byte> bytes)
 26    {
 27        try
 28        {
 7429            _ = StrictUtf8.GetCharCount(bytes);
 7030            return true;
 31        }
 432        catch (DecoderFallbackException)
 33        {
 434            return false;
 35        }
 7436    }
 37
 38    public static IReadOnlyList<ParsedImportSection> ParseBytes(
 39        string sourceFileId,
 40        byte[] bytes,
 41        string defaultDate)
 42    {
 3443        ArgumentNullException.ThrowIfNull(bytes);
 44
 3445        if (!ValidateUtf8(bytes))
 46        {
 047            throw new DecoderFallbackException($"File '{sourceFileId}' contains invalid UTF-8 byte sequences.");
 48        }
 49
 3450        var markdown = StrictUtf8.GetString(bytes);
 3451        return Parse(sourceFileId, markdown, defaultDate);
 52    }
 53
 54    public static IReadOnlyList<ParsedImportSection> Parse(
 55        string sourceFileId,
 56        string markdown,
 57        string defaultDate)
 58    {
 6459        ArgumentNullException.ThrowIfNull(sourceFileId);
 6460        ArgumentNullException.ThrowIfNull(markdown);
 61
 6462        if (string.IsNullOrWhiteSpace(defaultDate) || !ProvenanceMarker.IsValidIsoDate(defaultDate))
 63        {
 064            throw new ArgumentException($"Default date '{defaultDate}' must be a valid ISO-8601 date in 'YYYY-MM-DD' for
 65        }
 66
 6467        var normalizedSourceId = sourceFileId.Trim();
 6468        var lines = SplitLines(markdown);
 69
 6470        var headingLocations = FindSplitHeadings(markdown, lines);
 71
 6472        var sections = new List<ParsedImportSection>();
 6473        var headingPathOccurrences = new Dictionary<string, int>(StringComparer.Ordinal);
 6474        var bareHeadingCounter = 0;
 6475        var sectionOrderIndex = 0;
 76
 6477        string? currentH1Path = null;
 78
 6479        if (headingLocations.Count == 0)
 80        {
 081            if (markdown.Length > 0)
 82            {
 083                var prov = ExtractSectionProvenance(markdown, lines, 0, lines.Count, defaultDate);
 084                var hash = Sha256Hasher.ComputeLowerHex(markdown);
 85                const string path = "$preamble";
 086                var importKey = $"{normalizedSourceId}#{path}#0";
 87
 088                sections.Add(new ParsedImportSection(
 089                    SourceFileId: normalizedSourceId,
 090                    HeadingPath: path,
 091                    OccurrenceIndex: 0,
 092                    SectionOrderIndex: 0,
 093                    Title: "Preamble",
 094                    Body: markdown,
 095                    Provenance: prov,
 096                    BodyHash: hash,
 097                    ImportKey: importKey));
 98            }
 99
 0100            return sections;
 101        }
 102
 103        // Check if there is preamble text before the first # or ## heading
 64104        var firstHeadingStart = headingLocations[0].StartCharIndex;
 64105        if (firstHeadingStart > 0)
 106        {
 16107            var preambleBody = markdown[..firstHeadingStart];
 16108            var firstHeadingLineIndex = headingLocations[0].LineIndex;
 16109            var prov = ExtractSectionProvenance(markdown, lines, 0, firstHeadingLineIndex, defaultDate);
 16110            var hash = Sha256Hasher.ComputeLowerHex(preambleBody);
 111            const string path = "$preamble";
 16112            var importKey = $"{normalizedSourceId}#{path}#0";
 113
 16114            sections.Add(new ParsedImportSection(
 16115                SourceFileId: normalizedSourceId,
 16116                HeadingPath: path,
 16117                OccurrenceIndex: 0,
 16118                SectionOrderIndex: sectionOrderIndex++,
 16119                Title: "Preamble",
 16120                Body: preambleBody,
 16121                Provenance: prov,
 16122                BodyHash: hash,
 16123                ImportKey: importKey));
 124        }
 125
 3372126        for (var i = 0; i < headingLocations.Count; i++)
 127        {
 1622128            var current = headingLocations[i];
 1622129            var nextStart = (i + 1 < headingLocations.Count)
 1622130                ? headingLocations[i + 1].StartCharIndex
 1622131                : markdown.Length;
 132
 1622133            var sectionBody = markdown[current.StartCharIndex..nextStart];
 1622134            var nextLineIndex = (i + 1 < headingLocations.Count)
 1622135                ? headingLocations[i + 1].LineIndex
 1622136                : lines.Count;
 137
 1622138            var prov = ExtractSectionProvenance(markdown, lines, current.LineIndex, nextLineIndex, defaultDate);
 139
 140            string title;
 1622141            if (string.IsNullOrWhiteSpace(current.RawTitle))
 142            {
 14143                bareHeadingCounter++;
 14144                title = $"(Untitled Heading #{bareHeadingCounter})";
 145            }
 146            else
 147            {
 1608148                title = current.RawTitle;
 149            }
 150
 1622151            var markerTitle = string.IsNullOrWhiteSpace(current.RawTitle)
 1622152                ? new string('#', current.Level)
 1622153                : $"{new string('#', current.Level)} {current.RawTitle}";
 154
 155            string headingPath;
 1622156            if (current.Level == 1)
 157            {
 64158                headingPath = markerTitle;
 64159                currentH1Path = headingPath;
 160            }
 161            else // Level == 2
 162            {
 1558163                headingPath = currentH1Path is not null
 1558164                    ? $"{currentH1Path} / {markerTitle}"
 1558165                    : markerTitle;
 166            }
 167
 1622168            if (!headingPathOccurrences.TryGetValue(headingPath, out var count))
 169            {
 1606170                count = 0;
 171            }
 172
 1622173            headingPathOccurrences[headingPath] = count + 1;
 1622174            var occurrenceIndex = count;
 175
 1622176            var hash = Sha256Hasher.ComputeLowerHex(sectionBody);
 1622177            var importKey = $"{normalizedSourceId}#{headingPath}#{occurrenceIndex}";
 178
 1622179            sections.Add(new ParsedImportSection(
 1622180                SourceFileId: normalizedSourceId,
 1622181                HeadingPath: headingPath,
 1622182                OccurrenceIndex: occurrenceIndex,
 1622183                SectionOrderIndex: sectionOrderIndex++,
 1622184                Title: title,
 1622185                Body: sectionBody,
 1622186                Provenance: prov,
 1622187                BodyHash: hash,
 1622188                ImportKey: importKey));
 189        }
 190
 64191        return sections;
 192    }
 193
 42168194    private sealed record LineInfo(int LineIndex, int StartCharIndex, int EndCharIndex, string Text, bool InFrontMatter)
 195
 17766196    private sealed record HeadingLocation(int LineIndex, int Level, string RawTitle, int StartCharIndex);
 197
 198    private static List<LineInfo> SplitLines(string markdown)
 199    {
 64200        var lines = new List<LineInfo>();
 64201        var pos = 0;
 64202        var len = markdown.Length;
 64203        var lineIndex = 0;
 64204        var inFrontMatter = false;
 205
 10440206        while (pos < len)
 207        {
 10376208            var lineStart = pos;
 659204209            while (pos < len && markdown[pos] != '\r' && markdown[pos] != '\n')
 210            {
 648828211                pos++;
 212            }
 213
 10376214            var contentEnd = pos;
 10376215            if (pos < len)
 216            {
 10372217                if (markdown[pos] == '\r' && pos + 1 < len && markdown[pos + 1] == '\n')
 218                {
 7922219                    pos += 2;
 220                }
 221                else
 222                {
 2450223                    pos += 1;
 224                }
 225            }
 226
 10376227            var lineText = markdown[lineStart..contentEnd];
 228
 10376229            if (lineIndex == 0 && lineText.Trim() == "---")
 230            {
 2231                inFrontMatter = true;
 2232                lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: true));
 2233                continue;
 234            }
 235
 10374236            if (inFrontMatter)
 237            {
 8238                lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: true));
 8239                if (lineText.Trim() == "---")
 240                {
 2241                    inFrontMatter = false;
 242                }
 2243                continue;
 244            }
 245
 10366246            lines.Add(new LineInfo(lineIndex++, lineStart, pos, lineText, InFrontMatter: false));
 247        }
 248
 64249        return lines;
 250    }
 251
 252    private static List<HeadingLocation> FindSplitHeadings(string markdown, List<LineInfo> lines)
 253    {
 64254        var headings = new List<HeadingLocation>();
 64255        var inFence = false;
 64256        var fenceChar = '\0';
 64257        var fenceLen = 0;
 258
 20880259        foreach (var line in lines)
 260        {
 10376261            if (line.InFrontMatter)
 262            {
 263                continue;
 264            }
 265
 10366266            var span = line.Text.AsSpan();
 10366267            if (MarkdownSectionParser.TryUpdateFenceState(span, ref inFence, ref fenceChar, ref fenceLen))
 268            {
 269                continue;
 270            }
 271
 10358272            if (inFence)
 273            {
 274                continue;
 275            }
 276
 277            // Indented code block: 4 or more leading spaces or tab
 10350278            if (IsIndentedCodeLine(span))
 279            {
 280                continue;
 281            }
 282
 10346283            if (TryParseAtxHeading(span, out var level, out var title))
 284            {
 285                // We split ONLY on level 1 (#) and level 2 (##)
 2016286                if (level is 1 or 2)
 287                {
 1622288                    headings.Add(new HeadingLocation(line.LineIndex, level, title, line.StartCharIndex));
 289                }
 290            }
 291        }
 292
 64293        return headings;
 294    }
 295
 296    private static bool IsIndentedCodeLine(ReadOnlySpan<char> span)
 297    {
 10350298        if (span.IsEmpty)
 299        {
 3810300            return false;
 301        }
 302
 6540303        if (span[0] == '\t')
 304        {
 0305            return true;
 306        }
 307
 6540308        var spaces = 0;
 6644309        while (spaces < span.Length && span[spaces] == ' ')
 310        {
 104311            spaces++;
 312        }
 313
 6540314        return spaces >= 4;
 315    }
 316
 317    private static bool TryParseAtxHeading(ReadOnlySpan<char> span, out int level, out string title)
 318    {
 10346319        level = 0;
 10346320        title = string.Empty;
 321
 10346322        var spaces = 0;
 10434323        while (spaces < span.Length && spaces < 3 && span[spaces] == ' ')
 324        {
 88325            spaces++;
 326        }
 327
 10346328        var trimmedLeading = span[spaces..];
 10346329        if (trimmedLeading.IsEmpty || trimmedLeading[0] != '#')
 330        {
 7754331            return false;
 332        }
 333
 2592334        var hashes = 0;
 7532335        while (hashes < trimmedLeading.Length && trimmedLeading[hashes] == '#')
 336        {
 4940337            hashes++;
 338        }
 339
 2592340        if (hashes is < 1 or > 6)
 341        {
 0342            return false;
 343        }
 344
 2592345        var rest = trimmedLeading[hashes..];
 2592346        if (!rest.IsEmpty && rest[0] != ' ' && rest[0] != '\t')
 347        {
 576348            return false;
 349        }
 350
 2016351        level = hashes;
 352
 2016353        var rawTitle = rest.Trim();
 354        // Check for optional closing sequence of # preceded by space/tab
 2016355        var titleStr = StripTrailingClosingHashes(rawTitle);
 2016356        title = titleStr;
 2016357        return true;
 358    }
 359
 360    private static string StripTrailingClosingHashes(ReadOnlySpan<char> span)
 361    {
 2016362        if (span.IsEmpty)
 363        {
 14364            return string.Empty;
 365        }
 366
 2002367        var end = span.Length;
 2002368        while (end > 0 && (span[end - 1] == ' ' || span[end - 1] == '\t'))
 369        {
 0370            end--;
 371        }
 372
 2002373        var trailingHashes = 0;
 2002374        while (end - trailingHashes > 0 && span[end - trailingHashes - 1] == '#')
 375        {
 0376            trailingHashes++;
 377        }
 378
 2002379        if (trailingHashes > 0 && end - trailingHashes > 0 && (span[end - trailingHashes - 1] == ' ' || span[end - trail
 380        {
 0381            var beforeHashes = span[..(end - trailingHashes)].Trim();
 0382            return beforeHashes.ToString();
 383        }
 384
 2002385        return span.Trim().ToString();
 386    }
 387
 388    private static ProvenanceMarker ExtractSectionProvenance(
 389        string markdown,
 390        List<LineInfo> lines,
 391        int startLineIndex,
 392        int endLineIndex,
 393        string defaultDate)
 394    {
 1638395        var inFence = false;
 1638396        var fenceChar = '\0';
 1638397        var fenceLen = 0;
 398
 5436399        for (var i = startLineIndex; i < endLineIndex && i < lines.Count; i++)
 400        {
 2614401            var line = lines[i];
 2614402            if (line.InFrontMatter)
 403            {
 404                continue;
 405            }
 406
 2604407            var span = line.Text.AsSpan();
 2604408            if (MarkdownSectionParser.TryUpdateFenceState(span, ref inFence, ref fenceChar, ref fenceLen))
 409            {
 410                continue;
 411            }
 412
 2596413            if (inFence)
 414            {
 415                continue;
 416            }
 417
 2588418            var match = ProvenanceTagRegex().Match(line.Text);
 2588419            if (match.Success)
 420            {
 1534421                var kind = ProvenanceKindExtensions.FromWireString(match.Groups[1].Value);
 1534422                var date = match.Groups[2].Success && !string.IsNullOrWhiteSpace(match.Groups[2].Value)
 1534423                    ? match.Groups[2].Value.Trim()
 1534424                    : defaultDate;
 1534425                var qualifier = match.Groups[3].Success && !string.IsNullOrWhiteSpace(match.Groups[3].Value)
 1534426                    ? match.Groups[3].Value.Trim()
 1534427                    : null;
 428
 1534429                return new ProvenanceMarker(kind, date, qualifier);
 430            }
 431        }
 432
 104433        return new ProvenanceMarker(ProvenanceKind.Inferred, defaultDate);
 434    }
 435}