* Show release notes in the update popup, sourced from CHANGELOG.md The update banner only linked out to the online changelog, so there was no way to see what an update contains before taking it. Add CHANGELOG.md at the repo root as the source of release notes. Studio reads it from the default branch, so editing the file updates the popup without a release or rebuild, and falls back to the copy bundled in the install when the repo is unreachable. Notes are matched to one exact version. The popup asks for the version it is offering and gets that section or nothing, so an older release's notes can never appear next to a newer update. When there is no match the popup links out to the online changelog instead. The collapsed popup previews the top bullets with the leading sentence highlighted; "Show release notes" expands the full notes in a scrollable panel. Applies to both the browser and desktop banners, and the desktop updater's own release body is used when CHANGELOG.md has no matching section. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Address review: fence matching, nested bullets, BOM, updater notes field Track the opening fence marker and length so a ``` sample inside a ```` block does not close it early and let the sample's heading be indexed as a real release. Preserve list indentation in the preview and take only top-level bullets, so nested detail no longer consumes the four headline slots. Strip a UTF-8 BOM before parsing. An editor on Windows can leave one on the first line, which hid a section whose heading started the file. Read `notes`/`pub_date` from latest.json in the manual Linux updater path, with aliases for the older `body`/`date`. The workflow publishes Tauri's field names, so the manual path's release body was always empty. Also loop the preview tag strip until stable for CodeQL js/incomplete-multi-character -sanitization; the value renders as text, so this is defence in depth. * Address review: bare fence closers, HTML comments, underscores, notes URL A closing fence must carry nothing after the delimiter, so a ```` line with trailing text inside a ```` block is content rather than the end of it. Both the parser and the preview extractor follow that rule now. Skip headings inside HTML comments. A commented-out section is not rendered by Markdown, so it must not be indexed as a release. Strip only paired emphasis and park code spans first, so identifiers keep their underscores: UNSLOTH_DISABLE_UPDATE_CHECK was previewing as UNSLOTHDISABLEUPDATECHECK. Prefer the caller's release URL over the API's generic changelog link, so the desktop fallback points at the release page for the version being offered. Look at the repo-root CHANGELOG.md before the packaging snapshot, and remove the snapshot after build.sh, so an edited root file is never shadowed by a stale copy. Also nudge the notes container radius from 16px to 14px. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Address review: comparison operators, hidden comments, remote failures Require a name character after "<" when stripping tags. A bullet reading "Support Python <3.15 and >3.9" previewed as "Support Python 3.9", because the operators were consumed as if they were a tag. Track HTML comments while collecting preview lines. A commented-out bullet was previewed as a published change even though Markdown never renders it. Report a remote lookup failure whenever nothing matched. The bundled changelog cannot know a version newer than the install, so discarding the error made an offline lookup read as "no notes were published". The hook now treats a reported failure as its retryable error state. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Address review: code-span delimiters, stale notes, retry past cached failures Treat an HTML comment delimiter inside inline code as literal. A note reading "Type `<!--` to begin a comment" put the parser into comment state, so every release below it was swallowed into the entry above and became unfindable. Applied to the preview extractor too. Return no notes while the offered version differs from the fetched one. On the render where the version changes, the hook still held the previous release's notes, which the panel would show for a frame. Let retry bypass a cached remote failure via a refresh flag on the endpoint. Failures are cached for five minutes, so the visible Retry action could not recover until the TTL expired. A cached success is still reused, so retries cannot hammer the remote. * Address review: CommonMark indentation, desktop release notes link Allow up to three leading spaces on release headings and fences, and treat four as indented code. An indented heading was unreachable and its notes were appended to the release above, while an indented backtick line opened a fence that swallowed later headings. Link desktop release notes to the release page for the offered version on every platform. The existing URL is built only in manual Linux package mode, so in-app updates on macOS, Windows and AppImage fell back to the generic changelog. The install button keeps using the manual URL. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Address review: wrapped prose, autolinks, abbreviations in the preview Accumulate contiguous prose lines into one preview item. A paragraph wrapped across source lines renders as one block but previewed as three fragments, which also ate the four-item limit. Keep Markdown autolinks. <https://example.com/notes> was stripped as if it were a tag, so "See <https://example.com/notes> for details" previewed as "See for details". Do not split the lead sentence at an abbreviation. "Supports several formats, e.g. GGUF and Safetensors." highlighted only up to "e.g." and dimmed the actual change; known abbreviations and single initials are skipped now. * Address review: park code spans first, skip indented code blocks Park code spans before any other inline transformation. Tags, links, images and emphasis inside a span are literal, but the strips ran first, so "Use `<button>` for actions" previewed as "Use for actions". Skip lines inside an indented code block when collecting bullets. A "- pip install ..." line in a four-space-indented block became the headline and pushed out the real prose, though Markdown renders it as code. Continuation lines of an open bullet are unaffected. * Studio: skip raw HTML blocks when reading release notes A <pre>, <script>, <style> or <textarea> block renders literally, so a sample '## 9.9.9' heading inside one was indexed as a release and cut the real section's body short. The preview had the same gap and listed sample bullets as notes. Both readers now track type 1 HTML blocks and skip their contents. Blocks open only at the start of a line, so a tag named mid-sentence stays inline text, and <details> is type 6 so its Markdown still parses. * Studio: read HTML blocks the way CommonMark renders them A fence inside a <pre> block was treated as a real fence, so the block's closing tag was swallowed and every release below it disappeared. Raw HTML state is now checked before fences, in both readers. Type 6 and 7 blocks (<details>, <div>, a bare tag on its own line) run to the next blank line, so a heading pressed against the opening tag is not a release either. Type 7 cannot interrupt a paragraph, so prose followed by a bare tag is unaffected. Checked against a CommonMark reference: 20000 generated well-formed changelogs now agree exactly on which headings are releases, and every previewed note is text the renderer really shows. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: restore preview types dropped in the scanner refactor The previous commit's refactor removed the Bullet and preview item interfaces, so tsc -b failed and every job that builds the frontend stopped there. * Studio: fix release-notes preview and packaging review findings Preview: a code span now closes on a run of the same length, so a note containing backticks keeps them; thematic breaks no longer take a preview slot; a quoted list is example output, so it stays out of the headline bullets and is only used when a section has none of its own. Popup: a failed lookup keeps the changelog link beside Retry, which the web banner always offered before, and the desktop popup waits briefly for the auto-auth token instead of recording a failure the user has to clear. Packaging: the changelog snapshot is made by the build backend, so python -m build, pip install . and sdist builds all ship the offline copy, not only build.sh. * Studio: scope the changelog fallback and hide staged sections Installed, the levels above studio/ are site-packages, so a stray CHANGELOG.md left there by another package outranked the bundled snapshot. Those levels are now searched only when a checkout marker (pyproject.toml or .git) is present, so a source checkout still serves the editable file. A section staged as only an HTML comment renders as nothing but was reported as matched, leaving an empty notes surface. Notes that render nothing now read as unpublished, so the popup links out instead. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: cover the remaining raw block forms and repository links Parser and preview: processing instructions, declarations and CDATA are literal like <pre>, so a sample heading or bullet inside one is no longer read as a release. ATX headings now need a space or tab after the hashes, matching CommonMark, so a pasted non-breaking space no longer truncates the release above it. Popup: the notes region follows the viewport and the card scrolls as a backstop, so a window under about 430px high no longer pushes the title and dismiss control off screen. Relative links in the notes resolve against the repository instead of Studio's origin, where the renderer blocked them. * Studio: reference-style images, empty previews and version queries Reference definitions now resolve against the raw host when the label is used as an image, so ![alt][arch] loads the file instead of its HTML page on GitHub. Labels are matched the way CommonMark compares them, and a reference written inside a fenced block does not count. Notes that preview as nothing, such as a lone command block, no longer leave an empty muted strip in the collapsed popup; expanding still shows them. A version query that cannot parse is rejected up front rather than looked up and reported as no notes. * Studio: Markdown scanning fixes across the release notes path Code spans are now scanned rather than matched by pattern, so a run of backticks closes only on a run of the same length. The preview and the link resolver share that scanner, so a link inside `a``b [x](y.md)` stays literal in both. Also: a closing fence may carry only spaces or tabs, so a delimiter with a non-breaking space after it stays code in all three scanners; escaped parentheses in a link target resolve to the literal path instead of being mangled; the collapsed preview decodes entities the way the expanded view renders them, while code spans stay literal; and release notes are fetched through authFetch so an expired access token is refreshed and retried. * Changelog: real 2026.7.5 notes, led by the AMD release Fills the section the popup reads with the actual headline changes, so the collapsed preview shows real content instead of placeholder notes. Leads with AMD support and covers the 23 July update: RDNA2 and Gorgon Halo, Strix Halo detection, RDNA4 and ROCm failure recovery, 2x faster unified memory loading, whisper.cpp dictation, and rollback environment cleanup. * Studio: fix release-notes text handling found by adversarial testing Line endings are normalised first: a CRLF body from the desktop updater no longer hides fences, so a code sample cannot become a headline bullet, and lone CR text splits into bullets. Preview: reference links and images render as their text, a definition line renders as nothing, parentheses in a destination no longer truncate the sentence, escaped punctuation stays literal, and a fence indented into a list item is treated as the block it is. Links: a badge resolves both its image and its outer link, indented code and code spans that cross a line are left alone, a definition cannot interrupt a paragraph, and image alt text no longer decides a label's host. Also: an escaped backtick cannot open a code span, park sentinels in the source cannot swap content, two in-flight requests for one version resolve in order, and repeated bullets no longer share a React key. Comment scanning no longer rescans code spans per delimiter and span lookup is a binary search: the worst inputs measured drop from 96ms to 1ms at the 20k cap, and from 544ms to 15ms at 200k. * Studio: parser and fetch fixes found by adversarial testing A comment marker written in prose no longer swallows the rest of the file. Only a comment that starts a line opens a block; one written mid-sentence is inline HTML and hides its own line at most. This was the worst case found: a single stray marker made every release below it unreachable and served their notes under the newer version's heading. Also in the parser: a closing delimiter takes its whole line, so a heading glued after it is not a release; an exact heading is never shadowed by a zero-padded one; setext headings are release boundaries; any heading, rule or definition ends a paragraph; and the code-span guard is a linear scan rather than a backtracking pattern, so 20k backticks parse in a millisecond instead of over a minute. Fetching: one deadline for the whole response with chunked reads, so a trickling server cannot hold a worker for minutes, waiters give up instead of queueing behind a stalled fetch, and identity encoding is requested so a compressing proxy cannot produce mojibake notes. Truncated notes close an open fence. UI: images and the renderer's own link dialog are held inside the card, which the shared preview's blanket max-width reset had let escape, and only the notes region scrolls so the dismiss control stays reachable on a short viewport. The developer update override no longer beats the documented opt-out, and its value has to parse as a version. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: CommonMark paragraph and block rules across the notes path Setext detection now requires plain paragraph text above the underline. A list item followed by --- is a list and a rule, not a heading: reading it as one discarded the bullet and every note after it. A backtick fence whose info string holds a backtick is not a fence, so such a line no longer swallows the releases below it in the parser, the preview and the link resolver. Preview: only an ordered list starting at 1 interrupts a paragraph, an unresolved reference keeps its brackets, a comment written mid-sentence hides its own line at most instead of the rest of the document, a raw block closer takes its whole line, and a code span closer after a backslash still closes, since escapes do not apply inside a span. Links: raw HTML blocks are literal, an escaped opener is not a link, and a definition under a heading is a definition. The overlay stack is capped to the viewport and both overlays can give up height, so a long download list no longer pushes the update card's title and dismiss control off screen. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: desktop notes by backend version, desktop stack cap, fetch budget latest.json now publishes the backend release the desktop build pins, and both desktop paths carry it: the manual metadata check through Rust, and the in-app updater through the raw metadata it already exposes. The popup looks release notes up by that version, so desktop stops asking CHANGELOG.md for an app SemVer it never contains and falling back to the generic installer text. Metadata without the field still parses and behaves as before. The desktop overlay stack is capped to the viewport like the browser one, since the download panel shares it and the card's own cap cannot see a sibling. The fetch budget now bounds each read, not just the gap between reads. Slow headers followed by a slow body held a worker for 5.6s against a 3s budget; it is 3.0s now, and a timeout is reported as one. * Studio: keep list-nested headings out of the release index A `## <version>` heading indented to a list item's content column is inside that item in CommonMark, not a release boundary. Reading it as one truncated the real release and indexed a version that does not exist. parse_changelog now tracks the open list items by the column their content starts at, and only counts a heading left of that column. Supporting rules, each checked against markdown-it (commonmark preset): a marker needs whitespace after it, so `2.0` stays a setext version; an item interrupts a paragraph only when it has content, and an ordered one only when it starts at 1; an empty item takes one blank line; a dedented fence, break or heading closes the item; and `- ## 2.0` is a heading inside the item. * Studio: whole-paragraph setext headings, uppercase declarations, escaped marks Three CommonMark conformance fixes on the notes path, each checked against markdown-it (commonmark preset). A setext heading is the whole paragraph above the underline, so a heading that wraps kept its version only on the first line while the parser read the last: `2026.7.5 - Release` over `July 25` left that release unindexed and its notes unreachable. The parser now tracks every line of the open paragraph, including lazy continuations, and stops at whatever really interrupts it: a quote marker, a bullet, or an ordered marker starting at 1. A type 4 HTML block needs an uppercase letter after `<!`, so prose mentioning `<!note` was hiding every release below it until the next `>`. In the link resolver, `\![alt][label]` renders as a link, so its definition resolves to the file's page on GitHub rather than the raw-content host. * Studio: the preview needs the uppercase declaration rule too The backend parser stopped treating `<!note` as an HTML block, but the collapsed preview still did, so prose mentioning one emptied the preview of every bullet below it while the expanded notes rendered them. A shipped test now pins the two to the same rule. * Treat an empty HTML comment as closed and always release the changelog fetch flag <!--> and <!---> are complete comments in CommonMark: the closer overlaps the opener, so searching for --> past the opener never found it and the scanner stayed in comment state for the rest of the file. An empty comment used as a section marker hid every release below it, in both the backend parser and the frontend preview. get_remote_changelog cleared its single-flight flag only after except Exception, so a BaseException stranded it and every later caller waited out the full deadline for the life of the process. Move the release into a finally. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Compare resolved changelog paths instead of a hardcoded checkout name The ordering assertion matched the string suffix /unsloth/CHANGELOG.md, so it raised StopIteration in any checkout not literally named unsloth, and on Windows the separator is a backslash so the suffix never matched there either. Both are unrelated to the ordering under test. Verified failing on ubuntu-24.04, macos-14-arm64 and windows-2025 alike, and passing after. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Scan backtick runs once instead of rescanning the suffix per opener Every unmatched opener rescanned the rest of the line and the outer loop then advanced by a single run, so a line of runs of 1, 2, 3 ... backticks was quadratic: 321 KB took 7.688s, and release notes are reparsed on every popup request, so one malformed remote changelog could tie up backend workers across installed clients. Collect the runs in one pass and walk a cursor per run length, since a length that runs out of partners stays out. Same 321 KB now takes 0.013s and 5 MB takes 0.205s. Verified identical output against the old implementation on 30000 randomized lines. * Read type 6 and 7 HTML containers in the link resolver too The resolver masked only type 1 blocks (pre, script, style, textarea), while the backend parser and the collapsed preview already apply the type 6 and 7 rules, so the three disagreed on the same notes. A <details> or <div> with no blank line inside is a type 6 block whose contents render verbatim, so two things went wrong there: a relative link was rewritten into text the reader sees literally, and a fence inside the block was taken for a real fence, which silently stopped every link below it from resolving. A blank line, not the closing tag, ends these blocks, so the common '<div align="center">' followed by a blank line still holds Markdown and still resolves. * Mask comments before fences, split only on Markdown line endings, stage the snapshot Three separate reports, all confirmed against head. The link resolver tracked no comment state, so a fence delimiter hidden inside an HTML comment was read as a real fence. The fence then stayed open and every visible line below was classified as code, so none of its links resolved: one commented-out draft containing a stray backtick run silently broke the rest of the notes. Comments are masked now, but only outside a fence, since fenced content is literal and a comment opener in it is not one. Commented ranges join the code spans, so a link the reader cannot see is not rewritten either. Verified with 9 cases under node; 2 fail on the previous file. str.splitlines also breaks on U+2028, U+2029, NEL, vertical tab and form feed, none of which end a line in CommonMark. A separator sitting in prose ahead of "## 9.9.9" made the parser index a release that renders nowhere and truncate the notes above it: measured, the version list went from 2.0, 9.9.9, 1.0 to 2.0, 1.0 and the 2.0 body stopped being cut at the separator. The build wrote the snapshot beside the checked-in sources, so a PEP 517 build against an immutable checkout (Nix, Bazel, a read-only container mount) raised PermissionError before build_py started and produced no wheel at all. The source-tree copy is best effort now and the wheel takes its copy from the staging directory. Reproduced both ways against a read-only package dir. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use the backend's heading and quote marker rules in the preview An ATX heading needs an ASCII space or tab after the marker, which is exactly what _HEADING_PATTERN requires. The \s class also matches a non-breaking space, so prose beginning "## Important change" with one was classified as a heading and discarded by collectBullets, and a prose-only release then had no collapsed preview at all rather than a wrong one. A blockquote marker takes at most three leading spaces, like every other marker in this file. Accepting any run let an indented code sample containing "> - sample output" shed its indentation and enter the collector, so a release with no real bullets showed code as its summary. Both reproduced under node against the real module: the two cases fail on the previous file and pass now, with a real heading, a real quoted bullet and an ordinary bullet unchanged. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Collect preview reference labels only from lines that can be definitions A definition-shaped line inside an indented code block or a deep fence is literal text, so CommonMark leaves a later "[Beta] support" unresolved with its brackets showing. The pre-scan ran over every line regardless, so the label was recorded and toPlainText stripped the brackets: the collapsed preview claimed a resolved reference the expanded notes do not have. It now skips the same code the collector pass skips. A real definition takes at most three spaces of indentation, so the indent test cannot reject one, which the second case checks. Reproduced under node: the indented-code definition resolved "Beta support" before and keeps its brackets now. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Let a document-level HTML block close an open list item CommonMark HTML blocks of types 1 to 6 interrupt a paragraph, so a "<div>" to the left of an open list item closes it and a following one-to-three-space indented "## 2.0" is a real document heading. Two things stopped that: the block opener was blanked before the list tracker saw it, so it read as a blank line, and _may_be_lazy treated it as ordinary text that could continue the item's paragraph. The item therefore stayed open and the release below the block was swallowed entirely. The opener's indentation is now taken before it is hidden, the way a fence opener's already was, and an HTML block opener is no longer a candidate for lazy continuation. Type 7 cannot interrupt a paragraph and is deliberately excluded, since after_paragraph is the only state this helper is asked about. Measured on the reported shape: the version list went from 3.0, 1.0 to 3.0, 2.0, 1.0. The test also pins the two cases that must not change, an indented heading genuinely nested in an item and an ordinary lazy continuation, both of which still suppress the heading. * Let the download panel shrink inside the capped overlay stack The bottom-right stack is capped to the viewport, but a flex item defaults to min-height:auto, so the download panel's outer wrapper could not shrink below its own content. min-h-0 had been added to the nested panel and not to this wrapper, so on a short viewport the cap was absorbed by the update card, whose header and actions are fixed, instead of by the download list, which scrolls. Only the shared-stack branch takes it. Standalone is positioned fixed and is not a flex item at all. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten release notes comments Shorten the comments and docs added with the update popup release notes so each explains its line in as few words as possible. Comments only, no behaviour change. * Measure release-notes indentation from the container CommonMark measures a block's indentation from its container, not from the left margin (spec 0.31.2 sections 4.4 and 5.2). The three changelog scanners measured from the margin in different places, so they disagreed with the renderer and with each other. Under "- Details:" the content column is 2, so a four-space line is two columns in: a paragraph holding a link. The link resolver read it as an indented code block and left the destination relative, so it resolved against Studio's own origin instead of the repository. At document level the same four spaces really are code, and a top-level bullet is not indented enough to continue the block. The preview promoted an indented line that looked like a fence opener to a list-contained fence, so with no later closer every bullet below it was skipped and the collapsed popup lost its summary. A fence is scoped to its container too: with no closing line it runs to the end of the containing block, not the end of the document (section 4.5). A dedented "## 2.0" closes the list item the fence sits in, so it is a real release heading. Document-wide fence state kept the block open, so one missing closing line hid every release below it. Both frontend scanners now read their list columns from one module ported from the backend's own tracker, which keeps the three in step. Two smaller fixes ride along. A release body written as a GFM table rendered as a grid but previewed as its raw "| Change | Detail | | --- | --- |" delimiters, so table rows are now dropped from the collapsed summary the way a code block already is. The comment scanner restarted its code-span search at the first span for every opener, so a line of N spans and N openers cost N squared: a 203 KiB line, well inside the 2 MiB the fetcher accepts, took 10.9s and now takes 41ms. Differential fuzzing against a CommonMark reference implementation puts the parser's heading mismatches at 11 of 14275 documents, down from 617, and the link resolver's at 147 of 6000, down from 217. * Keep Retry reachable when the release notes fetch fails The panel took fallbackMarkdown for every response that did not match, error included, so markdown was always truthy on desktop and the error branch that carries the Retry button was unreachable. The fallback there is the updater's static install blurb, not this release's notes, so a transient failure showed "Download the Apple Silicon .dmg" where the notes should be, with no way to ask again until the cache expired. The hook already separates the two: a reported failure is error and retryable, "no section for this version" is ready and is not. The fallback now applies only to the second, which is the case its prop documents. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Scope an unclosed comment to its block and end a release on a bare ## Two CommonMark rules the changelog scanners read too strictly. An HTML block only opens when the line itself begins with a comment marker (spec 0.31.2 section 4.6, type 2). One written mid-sentence is inline raw HTML and, unclosed, is ordinary text. The link resolver carried the open state to every line below instead, so a note reading "- Type <!-- to begin a comment" masked the relative links under it and they resolved against Studio's own origin rather than the repository. maskComments now separates the block form from the inline one and skips an opener sitting inside a code span, the way _strip_comments and stripCommentSpans already do. The spans are scanned only once an opener turns up, so a line without one costs what it did before. An ATX heading's opening sequence may also be followed by the end of the line (section 4.2), so a bare ## is an empty level-two heading. Both heading patterns required whitespace after the hashes, so everything below such a line stayed inside the release above it and the popup could show unrelated notes under that version. An empty heading carries no version, so it ends the release without indexing one of its own. Differential runs against markdown-it-py: section bodies 7769 to 0 mismatches over 36069 generated documents, comment-heavy link resolution 705 to 53 over 6000, and previews leaking a bare marker as headline text 22484 to 0 over 40000. The residual link cases are all one shape, a comment block opened inside a list item that outlives the item, which the fence tracker scopes and the comment tracker does not, in all three scanners alike. * Give a hidden comment its own column and balance link destinations A comment is an HTML block, so one written at the margin under a bullet is not indented enough to continue that item and closes the list. All three scanners blanked the line before list tracking saw it, which reads as a blank line and leaves the item open, so a release heading below it looked like nested item content and the new release merged into the one above. A hidden line now keeps its own column through _hidden_structure and hiddenStructure, and only its column, since the text a comment or a raw block hides is not Markdown and must not open a list of its own. A line inside a block already open is that block's content and still keeps nothing. A link destination may hold parentheses while they balance, so [x]((draft).md) points at (draft).md. The resolver stopped at the first paren, matched an empty destination and left the markdown alone, so the link resolved against Studio's own origin. The balanced form counts only while a closing paren or a title still ends the link, so the stray paren in [x](a(b.md) stays the closer the way CommonMark reads it rather than being swallowed into a link across lines. * Scope paragraph state to the container a line is written in Two lines the parser read as block starts are lazy paragraph text, so the list they were written under closed early and the heading indented to the item's content column was indexed as a release the renderer never shows. A setext underline may never be a lazy continuation line (spec 0.31.2 section 4.3), so `===` written left of an open item is more of that item's paragraph. Rejecting every underline-shaped line ended the list there. A row of three dashes is still a thematic break, which does end it. Lazy continuation runs the other way too: a marker written outside a blockquote is not text of the quote's paragraph, so `2. item` under `> quote` opens a list even though an ordered marker past 1 may not interrupt a paragraph. Paragraph state is now scoped to its container: a quote line leaves open only the quote's own paragraph, an underline needs one in its own container, a definition ends one only when there is none to continue, and a line four columns past its container is code, which may not interrupt. The frontend pair reads the same tracker, so both scanners now carry the quote state and a fence inside a list item ends with the item in the preview the way it already did on the backend. Measured against markdown-it-py (CommonMark 0.31.2) over 264k generated documents: 3368 sections now match the renderer, none regressed, and every list and quote corpus is exact. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read a fence and an HTML block from the container it opens in A block is measured from its container and not from the left margin (spec 0.31.2 sections 4.5 and 5.2), but the link resolver's fence, raw HTML and type 6 expressions all started at the margin, so a fence behind a quote marker and one three columns under a nested bullet opened nothing. The sample inside was then read as prose, and a relative link written in a code block or a details body was rewritten into text the reader is shown verbatim. Matching runs of backticks hid some of it by accident, since the code span scanner pairs them across lines, but a tilde fence, a closer of a different length and every HTML block went through. Each line is now read from the container it is written in, which the list tracker already knew, and a block is scoped to that container the way a fence inside an item already was: a line to the left of the item, or outside the quote, ends the block along with it, and a bare quote marker is the blank line that ends a type 6 block. A destination holds parentheses while they balance, and a path may nest them, so [x](((draft)).md) points at ((draft)).md. One nesting level was all the expression allowed, so anything deeper fell through to the plain form, matched an empty destination and left the link resolving against Studio's own origin. The pairs are unrolled to the 32 levels cmark counts, and the balanced form is still gated on a closer following it, so the stray paren in [x](a(b.md) stays the closer the way CommonMark reads it rather than inventing a link across lines. Measured against markdown-it-py (CommonMark 0.31.2) over 66k generated documents, comparing the rendered HTML rather than the destinations alone: 7286 documents in the parenthesis corpus and 313 in the container corpus now match the renderer, and the link and definition corpora are unchanged. One container document regresses, where closing the HTML block correctly exposes an unrelated gap of its own: a link reference definition still leaves a paragraph open, so the indented line below it reads as prose rather than as code. The list tracker still matches the backend on every step, the repo's own CHANGELOG resolves identically, and the pathological inputs measure the same. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read a block from the item its marker opens, and let a comment reach its paragraph Four things the three changelog scanners read differently from a renderer. A fence written straight after a list marker is the item's own first content, measured from the column that content starts, so "- ```md" opens one. All three scanners matched the whole line and saw nothing, so the code sample below it was prose: the resolver rewrote a destination the reader sees verbatim, and the preview offered the info string as a headline bullet. A shared itemContent / _item_content reads past a marker that really opens an item, capping the padding the way the list tracker caps it so an over-indented line is still indented code. An HTML block opener is read the same way, and its marker survives into the structural line so the item it opens is still tracked. An HTML block holds no lazy continuation line, so one opened on an item's continuation line ends where the item does, exactly as a fence there already did. The backend and the preview ended it only on a blank line, so it ran past the item and swallowed the next release heading, which made those notes unreachable and dropped every bullet below it from the collapsed popup. A raw block inside an item ends on a blank line too, which is where cmark puts it. A comment written mid-sentence is inline raw HTML belonging to the paragraph around it, so its "-->" may arrive on a later line of that same paragraph. Ending it at its own line left a backtick inside it pairing with a real one below, which hid a following link from the resolver, and left the preview quoting text the popup body does not show. A shared commentClosesBelow answers whether the closer arrives before the paragraph breaks; where it does not, the opener stays the ordinary text a renderer shows, so a note that merely mentions "<!--" still hides nothing. Only ASCII punctuation is escapable, so the backslash in "docs\alpha.md" is a character of the path. Dropping every backslash rewrote it to a path that does not exist, and a URL parser reads what survives as a separator, so a Windows or namespaced path pointed at the wrong file either way. The destination expression now escapes only punctuation, which also means a space still ends a destination: "[x](a b.md)" and "[x](a(b.md)" are not links, so their paths are left alone rather than half-rewritten. A destination that runs out of line still resolves, since its closer is on the line below. Fuzzed against markdown-it (CommonMark 0.31.2) over 20k-document corpora, with the whole rewritten document rendered and compared, not just its destinations. Release headings: 117 to 16 on containers, 88 to 10 on markers, 17 to 12, nothing new anywhere. Link destinations: 8823 to 104 on markers, 114 to 98 on comments, nothing new. Whole-document renders: 9271 to 220, 5116 to 245, 1265 to 671. The Python and TypeScript list trackers still agree over 26861 steps, and itemContent and hiddenStructure agree over another 6335. 321 KB of unmatched backticks still measures the same. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Let a definition follow a definition, and read a comment from the item it opens in Three CommonMark conformance fixes in the changelog scanners. A link reference definition is a block of its own that may not interrupt a paragraph, so it opens none either: definitions are allowed to run consecutively (spec 0.31.2 section 4.7). The link resolver counted one as paragraph text, so every definition after the first fell outside the set of lines a definition may start on and kept its relative destination, which then resolved against Studio's own origin. The backend already read the line this way. The guard asking whether a `-->` is reachable from an opener read any line whose first character was punctuation as the start of a new block. A `-->` written on a line of its own is how a multiline comment is ordinarily closed, and a wrapped line may open with emphasis, so neither counted as more of the paragraph carrying the comment. The comment never closed and the collapsed popup showed the author's internal note to the reader. It now tests for a block that may actually interrupt a paragraph. A comment is an HTML block too (section 4.6, type 2), so one written as a list item's first content opens inside that item exactly as a fence written there does. All three scanners looked for the opener at the margin of the line as written, so a marker in front of it hid the block: the resolver rewrote a destination inside raw HTML, which Streamdown then shows the reader as a literal URL, and the preview quoted the hidden note back at them as though the bullet were Markdown. The opener is now read from the item's content, the marker survives into the structural line so the item it opens is still tracked, and the block is scoped to that item the way a fence there is. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the release notes comments without losing the reasons they record --------- Co-authored-by: Unsloth <michaelhan@Michaels-MacBook-Pro.local> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <danielhanchen@gmail.com>
1056 lines
43 KiB
Python
1056 lines
43 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
||
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
||
|
||
"""Release notes for the update popup, sourced from CHANGELOG.md.
|
||
|
||
Notes are keyed to one exact version: the popup asks for the version it is
|
||
offering and gets that section or nothing, so an older release's notes can
|
||
never appear next to a newer update.
|
||
|
||
The remote copy on the default branch wins over the bundled one, since the
|
||
offered version is newer than the installed checkout. Both reads are lazy,
|
||
cached and skipped when update checks are off.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from packaging.version import InvalidVersion, Version
|
||
|
||
from .update_status import DISABLE_ENV_VAR, RELEASE_NOTES_URL
|
||
|
||
CHANGELOG_FILENAME = "CHANGELOG.md"
|
||
CHANGELOG_RAW_URL = "https://raw.githubusercontent.com/unslothai/unsloth/main/CHANGELOG.md"
|
||
CHANGELOG_URL_ENV_VAR = "UNSLOTH_CHANGELOG_URL"
|
||
CHANGELOG_PATH_ENV_VAR = "UNSLOTH_CHANGELOG_PATH"
|
||
CHANGELOG_TIMEOUT_SECONDS = 3
|
||
CHANGELOG_MAX_BYTES = 2 * 1024 * 1024
|
||
_CHANGELOG_CHUNK_BYTES = 64 * 1024
|
||
_CHANGELOG_MIN_READ_SECONDS = 0.05
|
||
CHANGELOG_SUCCESS_TTL_SECONDS = 30 * 60
|
||
CHANGELOG_FAILURE_TTL_SECONDS = 5 * 60
|
||
RELEASE_NOTES_MAX_CHARS = 20_000
|
||
|
||
# CommonMark requires a space, tab or line end after the hashes: a non-breaking
|
||
# space copied from rich text renders as text, not a heading, but a bare `##` is
|
||
# an empty heading and still ends the release above.
|
||
_HEADING_PATTERN = re.compile(r"^ {0,3}##(?:[ \t]+(?P<title>.*?))?[ \t]*$")
|
||
_FENCE_PATTERN = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})(?P<rest>.*)$")
|
||
# CommonMark type 1 HTML blocks: contents are literal until a closing tag,
|
||
# which the spec says need not be the one that opened the block.
|
||
_RAW_HTML_OPEN = re.compile(r"^ {0,3}<(pre|script|style|textarea)(?=[\s>]|$)", re.IGNORECASE)
|
||
_RAW_HTML_CLOSE = re.compile(r"</(pre|script|style|textarea)\s*>", re.IGNORECASE)
|
||
# Types 3 to 5 (processing instructions, declarations, CDATA) are literal too,
|
||
# each ending on its own delimiter. Comments open mid-line, so are separate.
|
||
_RAW_BLOCKS = (
|
||
(_RAW_HTML_OPEN, _RAW_HTML_CLOSE),
|
||
(re.compile(r"^ {0,3}<\?"), re.compile(r"\?>")),
|
||
(re.compile(r"^ {0,3}<!\[CDATA\["), re.compile(r"\]\]>")),
|
||
# A declaration needs an uppercase letter, so `<!note` stays ordinary text.
|
||
(re.compile(r"^ {0,3}<![A-Z]"), re.compile(r">")),
|
||
)
|
||
# Type 6 blocks run to the next blank line, so `<details>` only holds Markdown
|
||
# once a blank line has closed the block. Open and close tags both start one.
|
||
_HTML_BLOCK_OPEN = re.compile(r"^ {0,3}</?([a-zA-Z][a-zA-Z0-9-]*)(?=[\s/>]|$)")
|
||
# Blocks that break into an open paragraph, so none is open after them and one
|
||
# they are written below is closed rather than continued.
|
||
_INTERRUPTS = re.compile(
|
||
r"^ {0,3}(?:#{1,6}([ \t]|$)|(?:\*[ \t]*){3,}$|(?:-[ \t]*){3,}$|(?:_[ \t]*){3,}$)"
|
||
)
|
||
# A definition is a block of its own but may not interrupt a paragraph, so it
|
||
# ends the one above it only when there is none to continue.
|
||
_LINK_DEFINITION = re.compile(r"^ {0,3}\[(?:[^\[\]\\]|\\.)+\]:")
|
||
# Blocks that are not paragraph text, so a following underline is not setext.
|
||
_PARAGRAPH_TEXT = re.compile(r"^ {0,3}(?|\d{1,9}[.)]([ \t]|$))\S")
|
||
# A line of = or - under a paragraph line makes that line a heading.
|
||
_SETEXT_UNDERLINE = re.compile(r"^ {0,3}(=+|-+)[ \t]*$")
|
||
# A quoted paragraph continues on unmarked lines, which belong to the quote.
|
||
_BLOCK_QUOTE = re.compile(r"^ {0,3}>")
|
||
_QUOTE_MARKER = re.compile(r"^ {0,3}>[ \t]?")
|
||
# A heading at an item's content column belongs to that item, not the document.
|
||
# The marker needs whitespace after it, so `2.0` is a version, not an item.
|
||
_LIST_ITEM = re.compile(r"^[ \t]*(?P<marker>[-*+]|\d{1,9}[.)])(?P<space>[ \t]+|$)")
|
||
_THEMATIC_BREAK = re.compile(r"^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$")
|
||
# Content indented more than this after a marker is an indented code block, so
|
||
# the item's content starts one column past the marker instead.
|
||
_MAX_ITEM_PADDING = 4
|
||
_HTML_BLOCK_TAGS = frozenset(
|
||
"""
|
||
address article aside base basefont blockquote body caption center col colgroup
|
||
dd details dialog dir div dl dt fieldset figcaption figure footer form frame
|
||
frameset h1 h2 h3 h4 h5 h6 head header hr html iframe legend li link main menu
|
||
menuitem nav noframes ol optgroup option p param search section summary table
|
||
tbody td tfoot th thead title tr track ul
|
||
""".split()
|
||
)
|
||
# Type 7: any other complete tag alone on a line. It cannot interrupt a
|
||
# paragraph, so it only counts after a break.
|
||
_HTML_ATTRIBUTE = (
|
||
r"""(?:\s+[a-zA-Z_:][a-zA-Z0-9_.:-]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)"""
|
||
)
|
||
_HTML_TAG_ONLY_LINE = re.compile(
|
||
rf"^ {{0,3}}(?:<[a-zA-Z][a-zA-Z0-9-]*{_HTML_ATTRIBUTE}*\s*/?>|</[a-zA-Z][a-zA-Z0-9-]*\s*>)\s*$"
|
||
)
|
||
# Levels above studio/ are the repo root in a checkout and site-packages in an
|
||
# install, so they are searched only when one of these markers is present.
|
||
_CHECKOUT_ONLY_LEVELS = (3, 4)
|
||
_CHECKOUT_MARKERS = ("pyproject.toml", ".git")
|
||
_COMMENT_BLOCK_OPEN = re.compile(r"^ {0,3}<!--")
|
||
_COMMENT_OPEN = "<!--"
|
||
_COMMENT_CLOSE = "-->"
|
||
# Stands in for a line the renderer hides. `#` is a block of its own, so list
|
||
# tracking reads it like a comment: never a marker, never a lazy continuation.
|
||
_HIDDEN_BLOCK = "#"
|
||
_VERSION_TOKEN_PATTERN = re.compile(r"^[\[(]?v?(?P<version>[0-9][0-9A-Za-z.!+-]*?)[\])]?$")
|
||
_SAFE_VERSION_PATTERN = re.compile(r"^[0-9A-Za-z][0-9A-Za-z.!+-]{0,63}$")
|
||
|
||
|
||
@dataclass(frozen = True)
|
||
class _ListState:
|
||
"""The open list items, innermost last, by the column their content starts."""
|
||
|
||
columns: tuple[int, ...] = ()
|
||
# True while the innermost item has had no content since its marker.
|
||
empty_item: bool = False
|
||
|
||
|
||
@dataclass(frozen = True)
|
||
class ChangelogEntry:
|
||
"""One `## <version>` section of the changelog."""
|
||
|
||
version: str
|
||
heading: str
|
||
body: str
|
||
|
||
|
||
@dataclass(frozen = True)
|
||
class ChangelogSource:
|
||
text: str | None
|
||
source: str | None
|
||
error: str | None = None
|
||
|
||
|
||
@dataclass
|
||
class _ChangelogCacheEntry:
|
||
source: ChangelogSource
|
||
expires_at: float
|
||
|
||
|
||
_cache_condition = threading.Condition()
|
||
_remote_cache: _ChangelogCacheEntry | None = None
|
||
_remote_fetching = False
|
||
|
||
|
||
def reset_changelog_cache() -> None:
|
||
"""Clear the in-process changelog cache. Intended for tests."""
|
||
global _remote_cache, _remote_fetching
|
||
with _cache_condition:
|
||
_remote_cache = None
|
||
_remote_fetching = False
|
||
_cache_condition.notify_all()
|
||
|
||
|
||
def is_supported_version_query(version: str) -> bool:
|
||
"""Whether `version` is shaped like something we can look up at all.
|
||
|
||
Sections are indexed only when their version parses, so a query that does
|
||
not parse (`latest`, `main`) can never match and is rejected outright."""
|
||
candidate = version.strip()
|
||
if not _SAFE_VERSION_PATTERN.match(candidate):
|
||
return False
|
||
return _parse_version(candidate) is not None
|
||
|
||
|
||
def _markdown_lines(text: str) -> list[str]:
|
||
"""``text`` split the way CommonMark ends lines.
|
||
|
||
str.splitlines also breaks on U+2028, U+2029, NEL, vertical tab and form
|
||
feed, none of which end a line in Markdown. A separator sitting in prose
|
||
before "## 9.9.9" would otherwise index a release the renderer never shows
|
||
and truncate the notes above it.
|
||
"""
|
||
return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
||
|
||
|
||
def parse_changelog(text: str) -> list[ChangelogEntry]:
|
||
"""Parse `## <version>` sections, in file order.
|
||
|
||
Headings whose first token is not a version (`## Unreleased`, `## Format`)
|
||
end the previous section but are not indexed.
|
||
"""
|
||
# A Windows editor can leave a BOM on the first line, hiding a heading.
|
||
text = text.lstrip("")
|
||
entries: list[ChangelogEntry] = []
|
||
heading: str | None = None
|
||
version: str | None = None
|
||
body: list[str] = []
|
||
open_fence: str | None = None
|
||
# Content column of the list item the open block belongs to, 0 at document
|
||
# level. A fence and an HTML block are scoped to their container, so the
|
||
# item's end closes them. Only one of the three is ever open.
|
||
block_column = 0
|
||
in_comment = False
|
||
in_raw_html: int | None = None
|
||
in_html_block = False
|
||
after_paragraph = False
|
||
paragraph: list[str] = []
|
||
in_quote = False
|
||
quoted = False
|
||
lists = _ListState()
|
||
|
||
def flush() -> None:
|
||
if version is not None and heading is not None:
|
||
entries.append(
|
||
ChangelogEntry(
|
||
version = version,
|
||
heading = heading,
|
||
body = "\n".join(body).strip(),
|
||
)
|
||
)
|
||
|
||
for line in _markdown_lines(text):
|
||
# The line as list tracking sees it: blank wherever nothing renders.
|
||
structural = ""
|
||
opened_block = False
|
||
in_block = open_fence is not None or in_html_block or in_raw_html is not None or in_comment
|
||
# A fence, comment or HTML block inside a list item runs only to the end
|
||
# of that item, so a line dedented out of the item closes both. Lazy
|
||
# continuation reaches into none of them. A raw block or comment inside an
|
||
# item also ends on a blank line: the item takes the break, so what
|
||
# follows is a block of the item's own.
|
||
leaves = (
|
||
_indent_width(line) < block_column
|
||
if line.strip()
|
||
else in_raw_html is not None or in_comment
|
||
)
|
||
if in_block and block_column and leaves:
|
||
open_fence = None
|
||
in_html_block = False
|
||
in_raw_html = None
|
||
in_comment = False
|
||
block_column = 0
|
||
# The paragraph the line could have continued is block content, so
|
||
# it closes the item rather than reading as more of it.
|
||
after_paragraph = False
|
||
# A fence written as a list item's first content opens inside that item, so
|
||
# an opener is read past a marker on the same line. Only an opener: fenced
|
||
# content is literal and a closer carries no marker.
|
||
fence_line = line if open_fence else _item_content(line, after_paragraph)
|
||
# Raw HTML first: its contents are literal, so a fence in it is not one.
|
||
if in_raw_html is not None:
|
||
visible, in_raw_html = _strip_raw_html(line, in_raw_html)
|
||
elif in_html_block:
|
||
# A blank line is the only thing that ends a type 6 block.
|
||
in_html_block = line.strip() != ""
|
||
visible = ""
|
||
elif (fence := _FENCE_PATTERN.match(fence_line)) and not in_comment:
|
||
was_open = open_fence
|
||
open_fence = _next_fence_state(open_fence, fence.group("marker"), fence.group("rest"))
|
||
opened_block = was_open is None and open_fence is not None
|
||
# Hidden from heading matching, but its indent still closes items.
|
||
visible = ""
|
||
structural = line
|
||
elif open_fence:
|
||
visible = ""
|
||
else:
|
||
# A block already open owns this line, so it is content rather than a
|
||
# block written at the column it happens to start in.
|
||
hidden = in_comment or in_raw_html is not None
|
||
# A comment is an HTML block too, so one written as a list item's first
|
||
# content opens inside it exactly as a fence does: the opener is read
|
||
# past a marker on the same line.
|
||
block_open = (
|
||
not in_comment
|
||
and _COMMENT_BLOCK_OPEN.match(_item_content(line, after_paragraph)) is not None
|
||
)
|
||
# Commented-out sections are not rendered, so they are not releases.
|
||
visible, in_comment = _strip_comments(line, in_comment, block_open)
|
||
# An HTML block written as a list item's first content opens inside
|
||
# that item, as a fence does, so an opener is read past a marker on the
|
||
# same line. The marker stays, so its item is still tracked. A comment
|
||
# blanks its own line, so that line is read as written: the block
|
||
# renders as nothing, but the item it is content of still opens.
|
||
source = line if block_open else visible
|
||
content = _item_content(source, after_paragraph)
|
||
marker = source[: len(source) - len(content)]
|
||
# Nor is anything inside a raw HTML block such as <pre>.
|
||
stripped, in_raw_html = _strip_raw_html(content, in_raw_html)
|
||
opened_block = in_raw_html is not None or (block_open and in_comment)
|
||
# Taken before the opener is hidden: it renders as nothing, but its
|
||
# indent still closes a list item it sits left of, and a marker on its
|
||
# line still opens one. A comment or raw block keeps only those, since
|
||
# the text it hides is not Markdown and must open no list.
|
||
if block_open or stripped != content:
|
||
if not hidden:
|
||
structural = _hidden_structure(line, marker)
|
||
visible = ""
|
||
else:
|
||
visible = marker + stripped
|
||
if visible.strip():
|
||
structural = visible
|
||
elif not hidden:
|
||
structural = _hidden_structure(line)
|
||
if stripped and _opens_html_block(stripped, after_paragraph):
|
||
in_html_block = True
|
||
opened_block = True
|
||
visible = ""
|
||
# A `##` inside a fenced block is sample markdown, not a real heading.
|
||
match = _HEADING_PATTERN.match(visible) if visible else None
|
||
# `1.0` over a line of dashes is the same heading written setext style.
|
||
setext = (
|
||
after_paragraph
|
||
and match is None
|
||
and paragraph != []
|
||
and _SETEXT_UNDERLINE.match(visible) is not None
|
||
and (visible.strip()[:1] == "-")
|
||
# Never a boundary inside a list item: dedented the dashes are a
|
||
# thematic break, and at the content column the heading is nested.
|
||
and not lists.columns
|
||
)
|
||
if setext:
|
||
if version is not None:
|
||
# The whole paragraph is the heading, read as body on arrival.
|
||
del body[len(body) - len(paragraph) :]
|
||
flush()
|
||
# A wrapped heading keeps every line, so token one is the version.
|
||
heading = "\n".join(paragraph)
|
||
version = _version_from_heading(heading)
|
||
body = []
|
||
paragraph = []
|
||
after_paragraph = False
|
||
continue
|
||
# A dashed underline is not a list marker, so track lists after setext.
|
||
lazy_marker = _lazy_marker(structural, lists, after_paragraph, quoted)
|
||
lists = _open_lists(structural, lists, after_paragraph, quoted)
|
||
# Taken after the opening line closed the items it is dedented out of,
|
||
# so the block belongs to the item it is really written inside.
|
||
if opened_block:
|
||
block_column = lists.columns[-1] if lists.columns else 0
|
||
elif open_fence is None and not in_html_block and in_raw_html is None and not in_comment:
|
||
block_column = 0
|
||
# At an open item's content column a heading is nested, not a boundary.
|
||
if lists.columns and _indent_width(visible) >= lists.columns[0]:
|
||
match = None
|
||
# The line at its own nesting level: past the container's indentation
|
||
# and past a marker on the same line, so `- ## 2.0` reads as a heading.
|
||
column = lists.columns[-1] if lists.columns else 0
|
||
content = _strip_indent(visible, column)
|
||
if (item := _LIST_ITEM.match(content)) is not None:
|
||
content = content[item.end() :]
|
||
# Only ordinary text continues a paragraph. Indented code counts four
|
||
# spaces past the container, so an item's own indent does not count.
|
||
indented_code = not after_paragraph and _indent_width(visible) - column >= 4
|
||
# An underline ends the paragraph it underlines, so it needs one open in
|
||
# its own container: the quote above owns its own, and a row left of an
|
||
# open item is lazy text of the item's paragraph. Three dashes are a
|
||
# thematic break either way, which `_INTERRUPTS` already ends on.
|
||
underline = (
|
||
_SETEXT_UNDERLINE.match(visible) is not None
|
||
and after_paragraph
|
||
and not quoted
|
||
and _indent_width(visible) >= column
|
||
)
|
||
after_paragraph = (
|
||
# Read inside its container, so an empty item and a fence written as an
|
||
# item's own content leave no paragraph open below them. A marker the
|
||
# paragraph above swallows is its text, not an item.
|
||
(bool(content.strip()) or lazy_marker)
|
||
and match is None
|
||
and _HEADING_PATTERN.match(content) is None
|
||
and _FENCE_PATTERN.match(content) is None
|
||
and not indented_code
|
||
and _INTERRUPTS.match(visible) is None
|
||
and (after_paragraph or _LINK_DEFINITION.match(visible) is None)
|
||
and not underline
|
||
)
|
||
# A quote's paragraph runs on over plain text and owns every line of it.
|
||
# An empty quote holds none, so the line below starts the document's.
|
||
flush_left = visible.lstrip(" \t")
|
||
quote_line = _BLOCK_QUOTE.match(visible) is not None
|
||
in_quote = (
|
||
_may_be_lazy(_quote_content(visible))
|
||
if quote_line
|
||
else in_quote and _continues_paragraph(visible, column)
|
||
)
|
||
if quote_line:
|
||
# The only paragraph a quote line leaves open is the quote's own,
|
||
# and a quote holding a heading or nothing at all leaves none.
|
||
after_paragraph = in_quote
|
||
# Whose paragraph the line below would continue. A quote owns the one its
|
||
# own lines hold, so a marker outside the quote is a block of its own
|
||
# rather than more of the text above it.
|
||
quoted = quote_line or in_quote
|
||
# The lines a later underline turns into one heading. A paragraph opens
|
||
# only on plain text and then runs on until something interrupts it.
|
||
continues = (
|
||
not _interrupts_paragraph(flush_left)
|
||
if paragraph
|
||
else _PARAGRAPH_TEXT.match(flush_left) is not None
|
||
)
|
||
# A paragraph inside an open item is that item's, and only one written
|
||
# at document level can be the heading a later underline makes of it.
|
||
if after_paragraph and not in_quote and not lists.columns and continues:
|
||
paragraph = [*paragraph, visible.strip()]
|
||
else:
|
||
paragraph = []
|
||
if match is None:
|
||
if version is not None:
|
||
body.append(line)
|
||
continue
|
||
|
||
flush()
|
||
# An empty heading has no title, so it ends the release above without
|
||
# indexing one: `_version_from_heading` finds no version and `flush` skips.
|
||
heading = match.group("title") or ""
|
||
version = _version_from_heading(heading)
|
||
body = []
|
||
|
||
flush()
|
||
return entries
|
||
|
||
|
||
def find_release_notes(text: str, version: str) -> ChangelogEntry | None:
|
||
"""Return the section for exactly `version`, or None.
|
||
|
||
Equality is version-aware (`2026.07.5` matches `2026.7.5`) but never fuzzy:
|
||
a near-miss returns None so the caller shows no notes, not the wrong ones.
|
||
"""
|
||
entries = parse_changelog(text)
|
||
for entry in entries:
|
||
# An exact heading wins, so `## 1.0` is never shadowed by `## 1.0.0`.
|
||
if entry.version == version:
|
||
return entry
|
||
|
||
wanted = _parse_version(version)
|
||
for entry in entries:
|
||
if wanted is not None:
|
||
candidate = _parse_version(entry.version)
|
||
if candidate is not None and candidate == wanted:
|
||
return entry
|
||
return None
|
||
|
||
|
||
def get_release_notes(version: str, refresh: bool = False) -> dict[str, Any]:
|
||
"""Return release notes for exactly `version` for the update popup.
|
||
|
||
`refresh` retries a cached remote failure, so the UI's retry action is not
|
||
stuck behind the failure TTL once connectivity returns.
|
||
"""
|
||
version = version.strip()
|
||
if not is_supported_version_query(version):
|
||
return _notes_response(version = version, error = "Unsupported version.")
|
||
|
||
local = _read_local_changelog()
|
||
remote = ChangelogSource(text = None, source = None)
|
||
if os.environ.get(DISABLE_ENV_VAR) != "1":
|
||
remote = get_remote_changelog(refresh = refresh)
|
||
|
||
# Remote first: the offered version is newer than the local copy.
|
||
for candidate in (remote, local):
|
||
if not candidate.text:
|
||
continue
|
||
entry = find_release_notes(candidate.text, version)
|
||
if entry is not None:
|
||
return _notes_response(
|
||
version = version,
|
||
markdown = entry.body,
|
||
heading = entry.heading,
|
||
source = candidate.source,
|
||
)
|
||
|
||
# Nothing matched: the bundled copy cannot know a version newer than the
|
||
# install, so report a remote failure and let the UI offer a retry.
|
||
return _notes_response(version = version, error = remote.error)
|
||
|
||
|
||
def get_remote_changelog(refresh: bool = False) -> ChangelogSource:
|
||
"""Fetch CHANGELOG.md from the repo using a small in-process TTL cache."""
|
||
global _remote_cache, _remote_fetching
|
||
|
||
if refresh:
|
||
# Only a cached failure is dropped, so retries cannot hammer the remote.
|
||
with _cache_condition:
|
||
if _remote_cache and _remote_cache.source.text is None:
|
||
_remote_cache = None
|
||
|
||
# A caller waits for an in-flight fetch only as long as it may take, then
|
||
# answers locally rather than holding a worker behind a stalled upstream.
|
||
deadline = time.monotonic() + CHANGELOG_TIMEOUT_SECONDS + 1
|
||
while True:
|
||
now = time.monotonic()
|
||
with _cache_condition:
|
||
if _remote_cache and _remote_cache.expires_at > now:
|
||
return _remote_cache.source
|
||
if not _remote_fetching:
|
||
_remote_fetching = True
|
||
break
|
||
if now >= deadline:
|
||
return ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Release notes are still loading.",
|
||
)
|
||
_cache_condition.wait(timeout = deadline - now)
|
||
|
||
try:
|
||
try:
|
||
source = _fetch_remote_changelog()
|
||
except Exception:
|
||
source = ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Could not fetch release notes.",
|
||
)
|
||
|
||
ttl = CHANGELOG_SUCCESS_TTL_SECONDS if source.text else CHANGELOG_FAILURE_TTL_SECONDS
|
||
with _cache_condition:
|
||
_remote_cache = _ChangelogCacheEntry(source = source, expires_at = time.monotonic() + ttl)
|
||
return source
|
||
finally:
|
||
# Released here, not on the Exception path: stranding the single-flight
|
||
# flag on BaseException makes every later caller wait out the deadline.
|
||
with _cache_condition:
|
||
_remote_fetching = False
|
||
_cache_condition.notify_all()
|
||
|
||
|
||
def _fetch_remote_changelog() -> ChangelogSource:
|
||
url = os.environ.get(CHANGELOG_URL_ENV_VAR, "").strip() or CHANGELOG_RAW_URL
|
||
if not url.startswith(("http://", "https://")):
|
||
return ChangelogSource(text = None, source = None, error = "Invalid changelog URL.")
|
||
|
||
request = urllib.request.Request(
|
||
url,
|
||
headers = {
|
||
"User-Agent": "unsloth-studio-update-check",
|
||
# Or a compressing proxy hands back bytes we would decode as notes.
|
||
"Accept-Encoding": "identity",
|
||
},
|
||
)
|
||
deadline = time.monotonic() + CHANGELOG_TIMEOUT_SECONDS
|
||
try:
|
||
with urllib.request.urlopen(request, timeout = CHANGELOG_TIMEOUT_SECONDS) as response:
|
||
chunks: list[bytes] = []
|
||
received = 0
|
||
while received <= CHANGELOG_MAX_BYTES:
|
||
remaining = deadline - time.monotonic()
|
||
if remaining <= 0:
|
||
return ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Release notes took too long to load.",
|
||
)
|
||
# The socket timeout is per operation, so re-cap it each read.
|
||
_limit_read(response, remaining)
|
||
chunk = response.read1(_CHANGELOG_CHUNK_BYTES)
|
||
if not chunk:
|
||
break
|
||
chunks.append(chunk)
|
||
received += len(chunk)
|
||
body = b"".join(chunks)
|
||
if len(body) > CHANGELOG_MAX_BYTES:
|
||
return ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Release notes response was too large.",
|
||
)
|
||
return ChangelogSource(text = body.decode("utf-8", errors = "replace"), source = "remote")
|
||
except TimeoutError:
|
||
return ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Release notes took too long to load.",
|
||
)
|
||
except OSError:
|
||
return ChangelogSource(
|
||
text = None,
|
||
source = None,
|
||
error = "Could not reach the changelog for release notes.",
|
||
)
|
||
except UnicodeError:
|
||
return ChangelogSource(text = None, source = None, error = "Malformed changelog.")
|
||
|
||
|
||
def _limit_read(response: Any, remaining: float) -> None:
|
||
"""Cap the next socket read at the time left in the fetch budget."""
|
||
sock = getattr(getattr(response, "fp", None), "raw", None)
|
||
sock = getattr(sock, "_sock", None)
|
||
if sock is None:
|
||
return
|
||
try:
|
||
sock.settimeout(max(remaining, _CHANGELOG_MIN_READ_SECONDS))
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _read_local_changelog() -> ChangelogSource:
|
||
"""Read the CHANGELOG.md bundled with this install, if there is one."""
|
||
for path in _local_changelog_candidates():
|
||
try:
|
||
if not path.is_file():
|
||
continue
|
||
if path.stat().st_size > CHANGELOG_MAX_BYTES:
|
||
continue
|
||
return ChangelogSource(
|
||
text = path.read_text(encoding = "utf-8", errors = "replace"),
|
||
source = "local",
|
||
)
|
||
except OSError:
|
||
continue
|
||
return ChangelogSource(text = None, source = None)
|
||
|
||
|
||
def _is_source_checkout(root: Path) -> bool:
|
||
"""Whether `root` is this repository rather than an install directory."""
|
||
try:
|
||
return any((root / marker).exists() for marker in _CHECKOUT_MARKERS)
|
||
except OSError:
|
||
return False
|
||
|
||
|
||
def _local_changelog_candidates() -> list[Path]:
|
||
override = os.environ.get(CHANGELOG_PATH_ENV_VAR, "").strip()
|
||
candidates: list[Path] = []
|
||
if override:
|
||
candidates.append(Path(override).expanduser())
|
||
|
||
# changelog.py -> utils -> backend -> studio -> repo root. Repo root first
|
||
# so a checkout's editable file beats the snapshot packaging writes into
|
||
# studio/. Installed, those outer levels are site-packages, hence the marker.
|
||
parents = Path(__file__).resolve().parents
|
||
for index in (3, 2, 1, 4):
|
||
if index >= len(parents):
|
||
continue
|
||
root = parents[index]
|
||
if index in _CHECKOUT_ONLY_LEVELS and not _is_source_checkout(root):
|
||
continue
|
||
candidates.append(root / CHANGELOG_FILENAME)
|
||
|
||
seen: set[Path] = set()
|
||
unique: list[Path] = []
|
||
for candidate in candidates:
|
||
if candidate not in seen:
|
||
seen.add(candidate)
|
||
unique.append(candidate)
|
||
return unique
|
||
|
||
|
||
def _opens_fence(marker: str, rest: str) -> bool:
|
||
"""A backtick fence's info string may not contain a backtick."""
|
||
return marker[0] != "`" or "`" not in rest
|
||
|
||
|
||
def _next_fence_state(open_fence: str | None, marker: str, rest: str) -> str | None:
|
||
"""Track the open fence marker.
|
||
|
||
A closer must be the same character, at least as long, and carry nothing
|
||
after it. So neither a ``` sample nor a ```` line with trailing text ends
|
||
a ```` block early, while an opening fence may still have an info string.
|
||
Only spaces and tabs count as nothing: other Unicode whitespace is content.
|
||
"""
|
||
if open_fence is None:
|
||
return marker if _opens_fence(marker, rest) else None
|
||
closes = marker[0] == open_fence[0] and len(marker) >= len(open_fence)
|
||
if closes and not rest.strip(" \t"):
|
||
return None
|
||
return open_fence
|
||
|
||
|
||
def _code_span_ranges(line: str) -> list[tuple[int, int]]:
|
||
"""Code span bounds. A run of backticks closes only on a run of its length."""
|
||
# Collect the runs once: rescanning per opener is quadratic on a line of
|
||
# distinct unmatched runs, and notes are reparsed on every request.
|
||
runs: list[tuple[int, int]] = []
|
||
index = 0
|
||
while index < len(line):
|
||
if line[index] != "`" or _is_escaped(line, index):
|
||
index += 1
|
||
continue
|
||
ticks = _run_length(line, index)
|
||
runs.append((index, ticks))
|
||
index += ticks
|
||
|
||
# A run closes only on a later run of its length, so one cursor per length.
|
||
by_length: dict[int, list[int]] = {}
|
||
for position, (_, ticks) in enumerate(runs):
|
||
by_length.setdefault(ticks, []).append(position)
|
||
|
||
spans: list[tuple[int, int]] = []
|
||
cursors: dict[int, int] = {}
|
||
current = 0
|
||
while current < len(runs):
|
||
start, ticks = runs[current]
|
||
same = by_length[ticks]
|
||
cursor = cursors.get(ticks, 0)
|
||
while cursor < len(same) and same[cursor] <= current:
|
||
cursor += 1
|
||
cursors[ticks] = cursor
|
||
if cursor >= len(same):
|
||
# Nothing closes this run, so it is literal text.
|
||
current += 1
|
||
continue
|
||
closer = same[cursor]
|
||
cursors[ticks] = cursor + 1
|
||
spans.append((start, runs[closer][0] + ticks))
|
||
current = closer + 1
|
||
return spans
|
||
|
||
|
||
def _run_length(line: str, index: int) -> int:
|
||
end = index
|
||
while end < len(line) and line[end] == "`":
|
||
end += 1
|
||
return end - index
|
||
|
||
|
||
def _is_escaped(line: str, index: int) -> bool:
|
||
slashes = 0
|
||
while index - 1 - slashes >= 0 and line[index - 1 - slashes] == "\\":
|
||
slashes += 1
|
||
return slashes % 2 == 1
|
||
|
||
|
||
def _strip_comments(line: str, in_comment: bool, block_open: bool) -> tuple[str, bool]:
|
||
"""Return the line with HTML-comment spans removed, and the trailing state.
|
||
|
||
Only a comment that starts a line opens a block and hides the lines below
|
||
it. One written mid-sentence is inline HTML: it hides the rest of its own
|
||
line at most, so a note mentioning `<!--` cannot swallow later releases.
|
||
Delimiters inside inline code are literal and hide nothing.
|
||
|
||
"Starts a line" is read inside the container, so `block_open` is decided by
|
||
the caller from the item's content rather than from the raw line.
|
||
"""
|
||
if in_comment:
|
||
close = line.find(_COMMENT_CLOSE)
|
||
# The closing line belongs to the block, tail included.
|
||
return ("", False) if close != -1 else ("", True)
|
||
|
||
if block_open:
|
||
# `<!-->` and `<!--->` are complete comments, so the closer may overlap
|
||
# the opener; searching past it would swallow every later release.
|
||
return ("", _COMMENT_CLOSE not in line)
|
||
|
||
visible: list[str] = []
|
||
index = 0
|
||
spans = _code_span_ranges(line)
|
||
# Spans are ordered and disjoint and each opener sits at or past the one
|
||
# before, so the search resumes rather than restarts: restarting per opener is
|
||
# quadratic, and a long line of code spans is reparsed on every request.
|
||
cursor = 0
|
||
while index < len(line):
|
||
opening = line.find(_COMMENT_OPEN, index)
|
||
if opening == -1:
|
||
visible.append(line[index:])
|
||
break
|
||
|
||
while cursor < len(spans) and spans[cursor][1] <= opening:
|
||
cursor += 1
|
||
if cursor < len(spans) and spans[cursor][0] <= opening:
|
||
visible.append(line[index : spans[cursor][1]])
|
||
index = spans[cursor][1]
|
||
continue
|
||
|
||
visible.append(line[index:opening])
|
||
close = line.find(_COMMENT_CLOSE, opening + len(_COMMENT_OPEN))
|
||
if close == -1:
|
||
# Unterminated inline comment: it hides this line and no more.
|
||
break
|
||
index = close + len(_COMMENT_CLOSE)
|
||
return "".join(visible), False
|
||
|
||
|
||
def _hidden_structure(line: str, marker: str = "") -> str:
|
||
"""`line` as list tracking sees it once the renderer hides its text.
|
||
|
||
A comment or a raw HTML block renders nothing, but it is still a block
|
||
written at its own column, so it closes the items it sits to the left of.
|
||
Only the indentation survives: what is inside the block is not Markdown and
|
||
must not open a list of its own. `marker` is the part of the line that opens
|
||
a list item the block is the content of, which survives with it."""
|
||
if marker:
|
||
return marker + _HIDDEN_BLOCK
|
||
if not line.strip():
|
||
return ""
|
||
return line[: len(line) - len(line.lstrip(" \t"))] + _HIDDEN_BLOCK
|
||
|
||
|
||
def _indent_width(line: str) -> int:
|
||
"""Columns of leading whitespace, counting a tab to the next stop of four."""
|
||
width = 0
|
||
for char in line:
|
||
if char == " ":
|
||
width += 1
|
||
elif char == "\t":
|
||
width += 4 - width % 4
|
||
else:
|
||
break
|
||
return width
|
||
|
||
|
||
def _strip_indent(line: str, columns: int) -> str:
|
||
"""`line` with up to `columns` columns of leading whitespace removed."""
|
||
width = 0
|
||
index = 0
|
||
while index < len(line) and width < columns and line[index] in " \t":
|
||
width += 1 if line[index] == " " else 4 - width % 4
|
||
index += 1
|
||
return line[index:]
|
||
|
||
|
||
def _interrupts_paragraph(line: str) -> bool:
|
||
"""Whether `line` starts a block that can break into an open paragraph.
|
||
|
||
A quote marker always can. A list item can only when it has content, and an
|
||
ordered one only when it starts at 1: anything else is text of the
|
||
paragraph it appears to interrupt."""
|
||
if _BLOCK_QUOTE.match(line):
|
||
return True
|
||
item = None if _THEMATIC_BREAK.match(line) else _LIST_ITEM.match(line)
|
||
if item is None:
|
||
return False
|
||
marker = item.group("marker")
|
||
if not line[item.end() :].strip():
|
||
return False
|
||
return marker[-1] not in ".)" or marker[:-1] == "1"
|
||
|
||
|
||
def _item_content(line: str, after_paragraph: bool) -> str:
|
||
"""`line` read from the content column of a list item that opens on it.
|
||
|
||
A block written as an item's first content sits inside that item, so
|
||
``- ```` opens a fence even though its marker is not within three columns of
|
||
the container. The padding is capped the way `_open_lists` caps it, or
|
||
``- ```` would read as a fence rather than the indented code it is. A
|
||
marker the paragraph above swallows opens no item, so its line is returned
|
||
whole, as is one four columns past its container. Ported to the frontend as
|
||
`itemContent` in markdown-list-columns.ts."""
|
||
if _indent_width(line) >= 4 or (after_paragraph and not _interrupts_paragraph(line)):
|
||
return line
|
||
item = None if _THEMATIC_BREAK.match(line) else _LIST_ITEM.match(line)
|
||
if item is None:
|
||
return line
|
||
padding = _indent_width(item.group("space"))
|
||
# Over-indented content starts one column past the marker; the rest of the
|
||
# padding is the content's own indentation.
|
||
over = padding - 1 if padding > _MAX_ITEM_PADDING else 0
|
||
return " " * over + line[item.end() :]
|
||
|
||
|
||
def _quote_content(line: str) -> str:
|
||
"""What a blockquote line holds, with its markers stripped."""
|
||
while (marker := _QUOTE_MARKER.match(line)) is not None:
|
||
line = line[marker.end() :]
|
||
return line
|
||
|
||
|
||
def _may_be_lazy(line: str) -> bool:
|
||
"""Whether `line` can continue a paragraph it is indented out of.
|
||
|
||
Only plain text can: a heading, a fence, a break or an HTML block starts a
|
||
block of its own, which closes the item instead. An underline is not one of
|
||
them: it may never be lazy, so `===` written left of an open item is read as
|
||
more of the item's paragraph. Nor is a definition, which is a block of its
|
||
own but may not interrupt a paragraph. A row of dashes still closes the
|
||
item, as `_INTERRUPTS` reads three or more as the thematic break they are."""
|
||
return (
|
||
_PARAGRAPH_TEXT.match(line) is not None
|
||
and _INTERRUPTS.match(line) is None
|
||
and _FENCE_PATTERN.match(line) is None
|
||
# Types 1 to 6 interrupt a paragraph, so a `<div>` left of an open item
|
||
# closes it. Type 7 cannot, and is deliberately excluded.
|
||
and not _opens_html_block(line, True)
|
||
)
|
||
|
||
|
||
def _continues_paragraph(line: str, column: int) -> bool:
|
||
"""Whether `line` reads as more of a paragraph open in its container.
|
||
|
||
Measured from `column`, where that container's content starts: four columns
|
||
past it the line is an indented code block, which may not interrupt a
|
||
paragraph, so indentation alone never closes the one above it."""
|
||
inner = _strip_indent(line, column)
|
||
return _indent_width(inner) >= 4 or _may_be_lazy(inner)
|
||
|
||
|
||
def _close_dedented(
|
||
columns: tuple[int, ...], line: str, indent: int, after_paragraph: bool
|
||
) -> tuple[int, ...]:
|
||
"""`columns` with every item `line` is written to the left of closed.
|
||
|
||
Read inside the container the item sits in, not from the margin: a line that
|
||
only looks indented there is lazy text of the item's paragraph, which leaves
|
||
the item open rather than closing it."""
|
||
while columns and indent < columns[-1]:
|
||
outer = columns[-2] if len(columns) > 1 else 0
|
||
if after_paragraph and _continues_paragraph(line, outer):
|
||
break
|
||
columns = columns[:-1]
|
||
return columns
|
||
|
||
|
||
def _lazy_marker(line: str, state: _ListState, after_paragraph: bool, quoted: bool) -> bool:
|
||
"""Whether a marker-shaped `line` is really text of the paragraph above it.
|
||
|
||
Only a marker inside the paragraph's own item interrupts it; one to the left
|
||
closes that item and opens a sibling. A quote owns the paragraph its lines
|
||
hold, so a marker written outside the quote opens a list of its own."""
|
||
item = None if _THEMATIC_BREAK.match(line) else _LIST_ITEM.match(line)
|
||
columns = state.columns
|
||
return (
|
||
item is not None
|
||
and after_paragraph
|
||
and not quoted
|
||
and (not columns or _indent_width(line) >= columns[-1])
|
||
and not _interrupts_paragraph(line)
|
||
)
|
||
|
||
|
||
def _open_lists(
|
||
line: str,
|
||
state: _ListState,
|
||
after_paragraph: bool,
|
||
quoted: bool = False,
|
||
) -> _ListState:
|
||
"""The list items still open after `line`.
|
||
|
||
A dedented line closes an item, unless it is a lazy paragraph continuation.
|
||
A new marker nests under a deeper column and replaces a sibling. `quoted`
|
||
marks a paragraph the blockquote above owns: a marker written outside the
|
||
quote is not text of it, so it opens a list of its own.
|
||
"""
|
||
columns = state.columns
|
||
if not line.strip():
|
||
# A blank line leaves the list open, unless the item is still empty: an
|
||
# item may begin with one blank line, and later content is outside it.
|
||
return _ListState(columns[:-1] if state.empty_item else columns)
|
||
indent = _indent_width(line)
|
||
item = None if _THEMATIC_BREAK.match(line) else _LIST_ITEM.match(line)
|
||
empty = item is not None and not line[item.end() :].strip()
|
||
if _lazy_marker(line, state, after_paragraph, quoted):
|
||
# A lazy continuation or an underline, so the open items are untouched.
|
||
return state
|
||
columns = _close_dedented(columns, line, indent, after_paragraph)
|
||
# Four columns past its container the marker is an indented code block, or
|
||
# lazy text of the paragraph above it, so it opens no list of its own.
|
||
if item is None or indent - (columns[-1] if columns else 0) >= 4:
|
||
return _ListState(columns)
|
||
marker = item.group("marker")
|
||
padding = _indent_width(item.group("space"))
|
||
if padding == 0 or padding > _MAX_ITEM_PADDING:
|
||
# An empty or over-indented item still holds one column of content.
|
||
padding = 1
|
||
while columns and columns[-1] > indent:
|
||
columns = columns[:-1]
|
||
return _ListState((*columns, indent + len(marker) + padding), empty_item = empty)
|
||
|
||
|
||
def _opens_html_block(line: str, after_paragraph: bool) -> bool:
|
||
"""True if `line` starts a CommonMark type 6 or type 7 HTML block."""
|
||
match = _HTML_BLOCK_OPEN.match(line)
|
||
if match is not None and match.group(1).lower() in _HTML_BLOCK_TAGS:
|
||
return True
|
||
return not after_paragraph and _HTML_TAG_ONLY_LINE.match(line) is not None
|
||
|
||
|
||
def _strip_raw_html(line: str, open_block: int | None) -> tuple[str, int | None]:
|
||
"""Drop the parts of a line inside a raw block, and return the open block.
|
||
|
||
The state is the index of the open block in `_RAW_BLOCKS`, or None."""
|
||
if open_block is not None:
|
||
close = _RAW_BLOCKS[open_block][1].search(line)
|
||
return ("", None) if close else ("", open_block)
|
||
|
||
# A block only opens at the start of a line; mid-line tags are inline HTML.
|
||
for index, (opener, closer) in enumerate(_RAW_BLOCKS):
|
||
opening = opener.match(line)
|
||
if opening is None:
|
||
continue
|
||
rest = line[opening.end() :]
|
||
close = closer.search(rest)
|
||
return ("", None) if close else ("", index)
|
||
return line, None
|
||
|
||
|
||
def _version_from_heading(heading: str) -> str | None:
|
||
token = heading.split()[0] if heading.split() else ""
|
||
match = _VERSION_TOKEN_PATTERN.match(token)
|
||
if match is None:
|
||
return None
|
||
version = match.group("version")
|
||
return version if _parse_version(version) is not None else None
|
||
|
||
|
||
def _parse_version(version: str) -> Version | None:
|
||
try:
|
||
return Version(version)
|
||
except InvalidVersion:
|
||
return None
|
||
|
||
|
||
def _close_open_fence(markdown: str) -> str:
|
||
"""Close a fence the truncation cut in half, so the rest still renders."""
|
||
open_fence: str | None = None
|
||
for line in _markdown_lines(markdown):
|
||
fence = _FENCE_PATTERN.match(line)
|
||
if fence:
|
||
open_fence = _next_fence_state(open_fence, fence.group("marker"), fence.group("rest"))
|
||
return f"{markdown}\n{open_fence}" if open_fence else markdown
|
||
|
||
|
||
def _renders_visibly(markdown: str) -> bool:
|
||
"""Whether a section body renders anything at all."""
|
||
in_comment = False
|
||
for line in _markdown_lines(markdown):
|
||
opens_raw = any(opener.match(line) for opener, _ in _RAW_BLOCKS)
|
||
if not in_comment and (_FENCE_PATTERN.match(line) or opens_raw):
|
||
# A code block or raw HTML block renders even when it is empty.
|
||
return True
|
||
# No containers are tracked here, so the opener is read at the margin. The
|
||
# answer does not turn on it: an item renders its marker whatever the block
|
||
# inside hides, so a commented-out item renders something either way.
|
||
visible, in_comment = _strip_comments(
|
||
line, in_comment, _COMMENT_BLOCK_OPEN.match(line) is not None
|
||
)
|
||
if visible.strip():
|
||
return True
|
||
return False
|
||
|
||
|
||
def _notes_response(
|
||
*,
|
||
version: str,
|
||
markdown: str | None = None,
|
||
heading: str | None = None,
|
||
source: str | None = None,
|
||
error: str | None = None,
|
||
) -> dict[str, Any]:
|
||
# A section that renders as nothing counts as unpublished, not as empty.
|
||
if markdown and not _renders_visibly(markdown):
|
||
markdown = None
|
||
source = None
|
||
|
||
truncated = False
|
||
if markdown and len(markdown) > RELEASE_NOTES_MAX_CHARS:
|
||
markdown = _close_open_fence(markdown[:RELEASE_NOTES_MAX_CHARS].rstrip())
|
||
truncated = True
|
||
|
||
return {
|
||
"version": version,
|
||
"markdown": markdown or None,
|
||
"heading": heading,
|
||
# False means no notes for this exact version; the UI links out.
|
||
"matched": bool(markdown),
|
||
"truncated": truncated,
|
||
"source": source,
|
||
"release_notes_url": RELEASE_NOTES_URL,
|
||
"error": error,
|
||
}
|