Skip to main content

babyrite/expand/
github.rs

1//! GitHub Permalink expansion.
2//!
3//! This module provides functionality for parsing GitHub permalink URLs
4//! and fetching raw file content to display as code blocks.
5
6use futures_util::future::join_all;
7use regex::Regex;
8use std::sync::LazyLock;
9
10use super::{ExpandContext, ExpandError, ExpandedContent, LinkExpander};
11use crate::config::BabyriteConfig;
12use crate::utils::{escape_markdown, inline_code, language_for_path};
13
14/// Regex pattern for matching GitHub blob URLs.
15///
16/// Captures: owner, repo, git_ref (commit SHA or branch name), path, and optional line range fragment.
17///
18/// Supported patterns:
19/// - `https://github.com/{owner}/{repo}/blob/{ref}/{path}`
20/// - `https://github.com/{owner}/{repo}/blob/{ref}/{path}#L{line}`
21/// - `https://github.com/{owner}/{repo}/blob/{ref}/{path}#L{start}-L{end}`
22///
23/// The `{ref}` can be a commit SHA (e.g., `abcdef1234567`) or a branch/tag name (e.g., `main`, `feature/foo`).
24///
25/// An optional query string (e.g., `?plain=1`) is consumed but discarded — GitHub's blob query
26/// parameters control browser rendering only and do not affect the raw content served by
27/// `raw.githubusercontent.com`.
28static GITHUB_PERMALINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
29    Regex::new(
30        r"https://github\.com/([^/]+)/([^/]+)/blob/([^/]+)/([^#\s?]+)(?:\?[^#\s]*)?(?:#L(\d+)(?:-L(\d+))?)?",
31    )
32    .unwrap()
33});
34
35/// Maximum number of body bytes read from a raw response.
36///
37/// Why not `Content-Length`: `raw.githubusercontent.com` may respond with chunked
38/// transfer encoding, where the header is absent and any pre-check against it would
39/// pass unconditionally (#625). The limit is enforced on bytes actually received.
40const MAX_BODY_BYTES: usize = 1_048_576;
41
42/// Maximum number of bytes discarded before the first displayed line.
43///
44/// Skipped bytes are not retained, so [`MAX_BODY_BYTES`] does not apply to them (#732).
45/// They still have to be downloaded to find the line boundary, so this bounds the
46/// transfer; the client timeout bounds the time.
47const MAX_SKIPPED_BYTES: usize = 8 * 1_048_576;
48
49/// Number of leading bytes needed to tell a UTF-16 BOM from anything else.
50const BOM_SNIFF_BYTES: usize = 2;
51
52/// Number of bytes read past the last needed line to tell whether more follows.
53///
54/// Why not one byte: lines are counted at the `0A` byte, and in UTF-16LE the byte
55/// after it is the `00` completing the same `\n` code unit, so a single probe byte
56/// never reaches the next line.
57const PROBE_BYTES: usize = 2;
58
59/// A parsed GitHub permalink.
60#[derive(Debug)]
61pub struct GitHubPermalink {
62    /// Repository owner.
63    pub owner: String,
64    /// Repository name.
65    pub repo: String,
66    /// Git ref (commit SHA or branch/tag name).
67    pub git_ref: String,
68    /// File path within the repository.
69    pub path: String,
70    /// Optional line range specification.
71    pub line_range: Option<LineRange>,
72}
73
74/// A line range extracted from a GitHub permalink fragment.
75#[derive(Debug, Clone, Copy)]
76pub struct LineRange {
77    /// Start line (1-indexed).
78    pub start: usize,
79    /// End line (1-indexed, inclusive). Same as `start` for single-line references.
80    pub end: usize,
81}
82
83/// GitHub permalink expander.
84pub struct GitHubExpander;
85
86#[async_trait::async_trait]
87impl LinkExpander for GitHubExpander {
88    fn enabled(&self, config: &BabyriteConfig) -> bool {
89        config.features.github_permalink
90    }
91
92    /// Expands GitHub permalinks into code blocks.
93    #[cfg_attr(coverage_nightly, coverage(off))]
94    async fn expand_all(&self, cx: &ExpandContext<'_>) -> Vec<ExpandedContent> {
95        let permalinks = GitHubPermalink::parse_all(&cx.message.content);
96        if permalinks.is_empty() {
97            return Vec::new();
98        }
99        tracing::debug!(count = permalinks.len(), "parsed GitHub permalinks");
100
101        join_all(permalinks.iter().map(|p| p.fetch(&cx.ctx.github)))
102            .await
103            .into_iter()
104            .filter_map(|result| match result {
105                Ok(content) => Some(content),
106                // Logged at `debug` by `fetch`, where the permalink's span is active.
107                Err(ExpandError::GitHub(GitHubExpandError::ContentEmpty)) => None,
108                Err(e) => {
109                    tracing::error!(error = %e, "failed to expand GitHub permalink");
110                    None
111                }
112            })
113            .collect()
114    }
115}
116
117/// Errors that can occur when expanding a GitHub permalink.
118#[derive(thiserror::Error, Debug)]
119pub enum GitHubExpandError {
120    /// Failed to fetch the raw file content.
121    #[error("Failed to fetch raw content: {0}")]
122    Fetch(String),
123    /// The fetched content exceeds the maximum allowed size.
124    #[error("Content exceeds size limit")]
125    ContentTooLarge,
126    /// The lines to show are empty or whitespace-only, e.g. an empty file or a line
127    /// range that selects no lines or only blank ones.
128    #[error("Content is empty")]
129    ContentEmpty,
130    /// An HTTP error occurred.
131    #[error(transparent)]
132    Http(#[from] reqwest::Error),
133}
134
135impl GitHubPermalink {
136    /// Parses all GitHub permalink URLs from the given text.
137    ///
138    /// Matches URLs with commit SHAs, branch names, or tag names.
139    /// The shared link policy applies (see [`super::parse_links`]): angle-bracket
140    /// wrapped and duplicate URLs are ignored, and at most 3 links are returned.
141    pub fn parse_all(text: &str) -> Vec<GitHubPermalink> {
142        super::parse_links(text, &GITHUB_PERMALINK_REGEX, |captures| {
143            let line_range = match captures.get(5) {
144                Some(start) => {
145                    let start: usize = start.as_str().parse().ok()?;
146                    // A missing end (e.g. `#L42`) means a single-line reference.
147                    let end = match captures.get(6) {
148                        Some(end) => end.as_str().parse().ok()?,
149                        None => start,
150                    };
151                    // GitHub displays a reversed range (`#L3-L1`) as if it were ordered.
152                    Some(LineRange {
153                        start: start.min(end),
154                        end: start.max(end),
155                    })
156                }
157                None => None,
158            };
159
160            Some(GitHubPermalink {
161                owner: captures.get(1)?.as_str().to_string(),
162                repo: captures.get(2)?.as_str().to_string(),
163                git_ref: captures.get(3)?.as_str().to_string(),
164                path: captures.get(4)?.as_str().to_string(),
165                line_range,
166            })
167        })
168    }
169
170    /// Fetches the raw file content from GitHub and returns a code block.
171    #[cfg_attr(coverage_nightly, coverage(off))]
172    #[tracing::instrument(
173        skip(self, http_client),
174        fields(
175            owner = %self.owner,
176            repo = %self.repo,
177            git_ref = %self.git_ref,
178            path = %self.path,
179        )
180    )]
181    pub async fn fetch(
182        &self,
183        http_client: &reqwest::Client,
184    ) -> Result<ExpandedContent, ExpandError> {
185        let config = BabyriteConfig::get();
186        let max_lines = config.github.max_lines;
187
188        let raw_url = format!(
189            "https://raw.githubusercontent.com/{}/{}/{}/{}",
190            self.owner, self.repo, self.git_ref, self.path
191        );
192
193        tracing::debug!(url = %raw_url, "fetching raw content");
194        let started = std::time::Instant::now();
195        let response = http_client
196            .get(&raw_url)
197            .send()
198            .await
199            .map_err(GitHubExpandError::Http)?;
200
201        tracing::debug!(
202            status = %response.status(),
203            content_length = response.content_length(),
204            elapsed_ms = started.elapsed().as_millis(),
205            "received response"
206        );
207
208        if !response.status().is_success() {
209            tracing::warn!(status = %response.status(), "non-success status fetching raw content");
210            return Err(GitHubExpandError::Fetch(format!(
211                "HTTP {} for {}",
212                response.status(),
213                raw_url
214            ))
215            .into());
216        }
217
218        let limit = self.read_limit(max_lines);
219        let body = read_body_limited(response, limit).await.inspect_err(|e| {
220            tracing::warn!(
221                error = %e,
222                skip_lines = limit.skip_lines,
223                lines = limit.lines,
224                probe_bytes = limit.probe_bytes,
225                "failed to read body"
226            )
227        })?;
228        tracing::debug!(
229            bytes = body.len(),
230            elapsed_ms = started.elapsed().as_millis(),
231            "body read"
232        );
233
234        // Logged here rather than in `ensure_not_empty`: a `tracing` macro in a unit-tested
235        // function leaves a partially covered line, as no subscriber is installed in tests.
236        let content = match ensure_not_empty(self.build_code_block(&body, max_lines)) {
237            Ok(content) => content,
238            Err(e) => {
239                tracing::debug!("skipped permalink with nothing to show");
240                return Err(e.into());
241            }
242        };
243        tracing::debug!("code block built");
244        Ok(content)
245    }
246
247    /// How much of the body [`Self::build_code_block`] can consume.
248    ///
249    /// When `max_lines` caps the display, [`truncate_lines`] tells "exactly at the
250    /// limit" apart from "truncated" by whether a further line exists. The start of
251    /// that line is enough to make it exist, so it is probed rather than read in full.
252    fn read_limit(&self, max_lines: usize) -> ReadLimit {
253        let skip_lines = self
254            .line_range
255            .map_or(0, |range| range.start.saturating_sub(1));
256        let displayed_end = match self.line_range {
257            Some(range) => {
258                let capped = skip_lines.saturating_add(max_lines);
259                if range.end <= capped {
260                    return ReadLimit {
261                        skip_lines,
262                        lines: range.end,
263                        probe_bytes: 0,
264                    };
265                }
266                capped
267            }
268            None => max_lines,
269        };
270        ReadLimit {
271            skip_lines,
272            lines: displayed_end,
273            probe_bytes: PROBE_BYTES,
274        }
275    }
276
277    /// Builds an `ExpandedContent::CodeBlock` from raw file content.
278    ///
279    /// With a line range, `body` starts at the range's first line: the lines before
280    /// it are skipped while reading (see [`ReadLimit::skip_lines`]).
281    fn build_code_block(&self, body: &str, max_lines: usize) -> ExpandedContent {
282        let all_lines: Vec<&str> = body.lines().collect();
283        let (code, line_info) = match self.line_range {
284            Some(range) => {
285                let count = range
286                    .end
287                    .saturating_sub(range.start.saturating_sub(1))
288                    .min(all_lines.len());
289                let selected = &all_lines[..count];
290
291                let (code, truncated) = truncate_lines(selected, max_lines);
292                let info = if truncated {
293                    format!(
294                        "L{}-L{}, truncated to {} lines",
295                        range.start, range.end, max_lines
296                    )
297                } else {
298                    format!("L{}-L{}", range.start, range.end)
299                };
300                (code, info)
301            }
302            None => {
303                let (code, truncated) = truncate_lines(&all_lines, max_lines);
304                let info = if truncated {
305                    format!("truncated to {} lines", max_lines)
306                } else {
307                    String::new()
308                };
309                (code, info)
310            }
311        };
312
313        let display_ref = shorten_ref(&self.git_ref);
314        let language = language_for_path(&self.path);
315
316        let line_part = if line_info.is_empty() {
317            String::new()
318        } else {
319            format!(" ({line_info})")
320        };
321        let metadata = format!(
322            "{}{} - {}/{}@{}",
323            inline_code(&self.path),
324            line_part,
325            escape_markdown(&self.owner),
326            escape_markdown(&self.repo),
327            escape_markdown(display_ref)
328        );
329
330        ExpandedContent::CodeBlock {
331            language: language.to_string(),
332            code,
333            metadata,
334        }
335    }
336}
337
338/// The leading part of a body that needs to be read.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340struct ReadLimit {
341    /// Number of leading lines discarded instead of retained, because they are
342    /// not displayed.
343    skip_lines: usize,
344    /// Number of leading lines (skipped ones included) read in full, including their terminating newline.
345    lines: usize,
346    /// Number of bytes read past those lines, to tell whether more follows.
347    probe_bytes: usize,
348}
349
350/// Reads the response body chunk by chunk, stopping as soon as `limit` is met.
351///
352/// Dropping `response` before the transfer finishes aborts it, so the bytes past
353/// the last displayed line are never downloaded.
354#[cfg_attr(coverage_nightly, coverage(off))]
355async fn read_body_limited(
356    mut response: reqwest::Response,
357    limit: ReadLimit,
358) -> Result<String, GitHubExpandError> {
359    let mut body = LimitedBody::new(limit);
360    while !body.is_complete() {
361        let Some(chunk) = response.chunk().await.map_err(GitHubExpandError::Http)? else {
362            break;
363        };
364        body.push(&chunk)?;
365    }
366    body.finish()
367}
368
369/// Accumulates response chunks until its [`ReadLimit`] is met, [`MAX_BODY_BYTES`] is
370/// exceeded by the retained bytes, or [`MAX_SKIPPED_BYTES`] is exceeded by the
371/// skipped ones.
372struct LimitedBody {
373    buf: Vec<u8>,
374    newlines: usize,
375    probed: usize,
376    skipped_bytes: usize,
377    limit: ReadLimit,
378    /// Lines actually skipped; `limit.skip_lines`, or 0 for a UTF-16 body.
379    skip_lines: usize,
380    /// Leading bytes held back until the encoding is known. Only used while
381    /// skipping, since that is the only time it matters.
382    sniffing: Option<Vec<u8>>,
383}
384
385impl LimitedBody {
386    fn new(limit: ReadLimit) -> Self {
387        Self {
388            buf: Vec::new(),
389            newlines: 0,
390            probed: 0,
391            skipped_bytes: 0,
392            skip_lines: limit.skip_lines,
393            sniffing: (limit.skip_lines > 0).then(Vec::new),
394            limit,
395        }
396    }
397
398    /// Whether enough of the body has been received to build the code block.
399    fn is_complete(&self) -> bool {
400        self.newlines >= self.limit.lines && self.probed >= self.limit.probe_bytes
401    }
402
403    /// Feeds `chunk` to [`Self::consume`], holding back the first bytes while the
404    /// encoding is sniffed.
405    fn push(&mut self, chunk: &[u8]) -> Result<(), GitHubExpandError> {
406        let Some(sniffing) = self.sniffing.as_mut() else {
407            return self.consume(chunk);
408        };
409        let take = (BOM_SNIFF_BYTES - sniffing.len()).min(chunk.len());
410        sniffing.extend_from_slice(&chunk[..take]);
411        if sniffing.len() < BOM_SNIFF_BYTES {
412            return Ok(());
413        }
414        self.resolve_sniffing()?;
415        self.consume(&chunk[take..])
416    }
417
418    /// Ends the sniffing phase and feeds the held-back bytes through [`Self::consume`].
419    ///
420    /// Why not skip right away: lines are counted in raw bytes, so in UTF-16LE the
421    /// `00` completing a `\n` code unit would start the retained body and misalign
422    /// every following code unit. A UTF-16 body is therefore read from its start and
423    /// trimmed after decoding (see [`Self::finish`]).
424    fn resolve_sniffing(&mut self) -> Result<(), GitHubExpandError> {
425        let Some(held) = self.sniffing.take() else {
426            return Ok(());
427        };
428        if held.starts_with(&[0xff, 0xfe]) || held.starts_with(&[0xfe, 0xff]) {
429            self.skip_lines = 0;
430        }
431        self.consume(&held)
432    }
433
434    /// Retains the part of `chunk` that is still needed, up to [`MAX_BODY_BYTES`]
435    /// retained and [`MAX_SKIPPED_BYTES`] skipped.
436    fn consume(&mut self, chunk: &[u8]) -> Result<(), GitHubExpandError> {
437        if self.is_complete() {
438            return Ok(());
439        }
440        let wanted = self.limit.lines - self.newlines;
441        let mut newlines = 0;
442        let mut start = if self.newlines >= self.skip_lines {
443            0
444        } else {
445            chunk.len()
446        };
447        let mut end = 0;
448        if wanted > 0 {
449            end = chunk.len();
450            for (i, byte) in chunk.iter().enumerate() {
451                if *byte == b'\n' {
452                    newlines += 1;
453                    if self.newlines + newlines == self.skip_lines {
454                        start = i + 1;
455                    }
456                    if newlines == wanted {
457                        end = i + 1;
458                        break;
459                    }
460                }
461            }
462        }
463        let mut probed = 0;
464        if newlines == wanted {
465            probed = (self.limit.probe_bytes - self.probed).min(chunk.len() - end);
466            end += probed;
467        }
468
469        // A reversed range (`#L10-L2`) ends before the skip boundary, so the boundary
470        // is never found and `start` would stay past `end`. Nothing is displayed then.
471        let start = start.min(end);
472
473        // The limit is checked against the retained slice, not the whole chunk: a
474        // chunk that overshoots the limit only past the last needed byte is fine.
475        if self.buf.len() + (end - start) > MAX_BODY_BYTES
476            || self.skipped_bytes + start > MAX_SKIPPED_BYTES
477        {
478            return Err(GitHubExpandError::ContentTooLarge);
479        }
480
481        self.skipped_bytes += start;
482        self.buf.extend_from_slice(&chunk[start..end]);
483        self.newlines += newlines;
484        self.probed += probed;
485        Ok(())
486    }
487
488    /// Decodes the accumulated bytes.
489    ///
490    /// Why not decode per chunk: a multi-byte sequence can straddle a chunk boundary,
491    /// so decoding happens once over the joined bytes.
492    ///
493    /// Why `encoding_rs` rather than `String::from_utf8_lossy`: this is the decode
494    /// the replaced `Response::text` performed, so BOM sniffing keeps its behaviour —
495    /// the BOM is dropped instead of showing up as an invisible U+FEFF, and a
496    /// UTF-16 BOM selects UTF-16 instead of decoding to mojibake.
497    ///
498    /// A UTF-16 body only survives being read in full or with a probe: [`Self::push`]
499    /// counts lines in raw bytes, so stopping right at the `0A` of a UTF-16LE `\n`
500    /// (`0A 00`) leaves the final code unit incomplete. Counting lines in decoded text
501    /// instead would mean decoding incrementally, which is not worth it for how rare
502    /// such files are.
503    ///
504    /// Why not read the `Content-Type` charset like `Response::text` does: the header
505    /// is gone by the time chunks are joined. `raw.githubusercontent.com` serves
506    /// `charset=utf-8`, which is also what `text` assumes when the charset is absent.
507    ///
508    /// When lines were skipped the body starts mid-file, so a U+FEFF at its start is
509    /// ordinary content and is decoded as such.
510    ///
511    /// A UTF-16 body was read from its start, so the lines that were not skipped on
512    /// the raw bytes are dropped from the decoded text instead. This keeps the
513    /// contract that the result starts at the first displayed line.
514    fn finish(mut self) -> Result<String, GitHubExpandError> {
515        self.resolve_sniffing()?;
516        if self.skip_lines > 0 {
517            let decoded = encoding_rs::UTF_8.decode_without_bom_handling(&self.buf).0;
518            return Ok(decoded.into_owned());
519        }
520        let decoded = encoding_rs::UTF_8.decode(&self.buf).0;
521        if self.limit.skip_lines == 0 {
522            return Ok(decoded.into_owned());
523        }
524        Ok(decoded
525            .split_inclusive('\n')
526            .skip(self.limit.skip_lines)
527            .collect())
528    }
529}
530
531/// Rejects a code block with nothing to show.
532///
533/// Checked on the built block rather than the body so that a line range past the end
534/// of the file is rejected too. Whitespace-only counts as empty: it renders as a blank
535/// fence that carries only the language name.
536fn ensure_not_empty(content: ExpandedContent) -> Result<ExpandedContent, GitHubExpandError> {
537    match &content {
538        ExpandedContent::CodeBlock { code, .. } if code.trim().is_empty() => {
539            Err(GitHubExpandError::ContentEmpty)
540        }
541        _ => Ok(content),
542    }
543}
544
545/// Returns true if the given string looks like a commit SHA (4-40 hex characters).
546fn is_commit_sha(s: &str) -> bool {
547    (4..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
548}
549
550/// Shortens a git ref for display. Commit SHAs are truncated to 7 characters;
551/// branch/tag names are returned as-is.
552fn shorten_ref(git_ref: &str) -> &str {
553    if is_commit_sha(git_ref) {
554        &git_ref[..7.min(git_ref.len())]
555    } else {
556        git_ref
557    }
558}
559
560/// Truncates lines to the given maximum, returning the joined string and whether truncation occurred.
561fn truncate_lines(lines: &[&str], max: usize) -> (String, bool) {
562    let kept = &lines[..lines.len().min(max)];
563    (kept.join("\n"), lines.len() > max)
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    // --- truncate_lines ---
571
572    #[test]
573    fn truncate_lines_under_limit() {
574        let lines = vec!["a", "b", "c"];
575        let (result, truncated) = truncate_lines(&lines, 5);
576        assert_eq!(result, "a\nb\nc");
577        assert!(!truncated);
578    }
579
580    #[test]
581    fn truncate_lines_at_limit() {
582        let lines = vec!["a", "b", "c"];
583        let (result, truncated) = truncate_lines(&lines, 3);
584        assert_eq!(result, "a\nb\nc");
585        assert!(!truncated);
586    }
587
588    #[test]
589    fn truncate_lines_over_limit() {
590        let lines = vec!["a", "b", "c", "d", "e"];
591        let (result, truncated) = truncate_lines(&lines, 2);
592        assert_eq!(result, "a\nb");
593        assert!(truncated);
594    }
595
596    #[test]
597    fn truncate_lines_empty() {
598        let lines: Vec<&str> = vec![];
599        let (result, truncated) = truncate_lines(&lines, 5);
600        assert_eq!(result, "");
601        assert!(!truncated);
602    }
603
604    // --- GitHubPermalink::parse_all ---
605
606    #[test]
607    fn parse_basic_permalink() {
608        let text = "https://github.com/owner/repo/blob/abcdef1234567890abcdef1234567890abcdef12/src/main.rs";
609        let results = GitHubPermalink::parse_all(text);
610        assert_eq!(results.len(), 1);
611        assert_eq!(results[0].owner, "owner");
612        assert_eq!(results[0].repo, "repo");
613        assert_eq!(
614            results[0].git_ref,
615            "abcdef1234567890abcdef1234567890abcdef12"
616        );
617        assert_eq!(results[0].path, "src/main.rs");
618        assert!(results[0].line_range.is_none());
619    }
620
621    #[test]
622    fn parse_permalink_with_single_line() {
623        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L42";
624        let results = GitHubPermalink::parse_all(text);
625        assert_eq!(results.len(), 1);
626        let range = results[0].line_range.unwrap();
627        assert_eq!(range.start, 42);
628        assert_eq!(range.end, 42);
629    }
630
631    #[test]
632    fn parse_permalink_with_line_range() {
633        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L10-L20";
634        let results = GitHubPermalink::parse_all(text);
635        assert_eq!(results.len(), 1);
636        let range = results[0].line_range.unwrap();
637        assert_eq!(range.start, 10);
638        assert_eq!(range.end, 20);
639    }
640
641    #[test]
642    fn parse_permalink_with_reversed_line_range() {
643        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L20-L10";
644        let results = GitHubPermalink::parse_all(text);
645        assert_eq!(results.len(), 1);
646        let range = results[0].line_range.unwrap();
647        assert_eq!(range.start, 10);
648        assert_eq!(range.end, 20);
649    }
650
651    #[test]
652    fn parse_skips_permalink_with_overflowing_line_start() {
653        let text =
654            "https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L99999999999999999999999";
655        assert!(GitHubPermalink::parse_all(text).is_empty());
656    }
657
658    #[test]
659    fn parse_skips_permalink_with_overflowing_line_end() {
660        let text =
661            "https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L1-L99999999999999999999999";
662        assert!(GitHubPermalink::parse_all(text).is_empty());
663    }
664
665    #[test]
666    fn parse_branch_name() {
667        let text = "https://github.com/owner/repo/blob/main/src/lib.rs";
668        let results = GitHubPermalink::parse_all(text);
669        assert_eq!(results.len(), 1);
670        assert_eq!(results[0].git_ref, "main");
671        assert_eq!(results[0].path, "src/lib.rs");
672    }
673
674    #[test]
675    fn parse_branch_name_with_line_range() {
676        let text = "https://github.com/owner/repo/blob/develop/src/main.rs#L5-L10";
677        let results = GitHubPermalink::parse_all(text);
678        assert_eq!(results.len(), 1);
679        assert_eq!(results[0].git_ref, "develop");
680        let range = results[0].line_range.unwrap();
681        assert_eq!(range.start, 5);
682        assert_eq!(range.end, 10);
683    }
684
685    #[test]
686    fn parse_branch_name_with_single_line() {
687        let text = "https://github.com/owner/repo/blob/main/src/lib.rs#L5";
688        let results = GitHubPermalink::parse_all(text);
689        assert_eq!(results.len(), 1);
690        assert_eq!(results[0].git_ref, "main");
691        let range = results[0].line_range.unwrap();
692        assert_eq!(range.start, 5);
693        assert_eq!(range.end, 5);
694    }
695
696    #[test]
697    fn parse_branch_with_special_characters() {
698        let cases = [
699            (
700                "https://github.com/o/r/blob/release-v1.0/f.rs",
701                "release-v1.0",
702            ),
703            (
704                "https://github.com/o/r/blob/feat_something/f.rs",
705                "feat_something",
706            ),
707            ("https://github.com/o/r/blob/v2.0.0/f.rs", "v2.0.0"),
708        ];
709        for (text, expected_ref) in cases {
710            let results = GitHubPermalink::parse_all(text);
711            assert_eq!(results.len(), 1, "failed for: {text}");
712            assert_eq!(results[0].git_ref, expected_ref);
713        }
714    }
715
716    #[test]
717    fn parse_tag_name() {
718        let text = "https://github.com/owner/repo/blob/v1.0.0/src/main.rs#L1-L10";
719        let results = GitHubPermalink::parse_all(text);
720        assert_eq!(results.len(), 1);
721        assert_eq!(results[0].git_ref, "v1.0.0");
722        let range = results[0].line_range.unwrap();
723        assert_eq!(range.start, 1);
724        assert_eq!(range.end, 10);
725    }
726
727    #[test]
728    fn parse_mixed_sha_and_branch() {
729        let text = "https://github.com/o/r/blob/abcd1234/a.rs \
730                    https://github.com/o/r/blob/main/b.rs";
731        let results = GitHubPermalink::parse_all(text);
732        assert_eq!(results.len(), 2);
733        assert_eq!(results[0].git_ref, "abcd1234");
734        assert_eq!(results[1].git_ref, "main");
735    }
736
737    #[test]
738    fn parse_accepts_short_ref() {
739        // Short refs (e.g., short branch names) should still match
740        let text = "https://github.com/owner/repo/blob/abc/src/lib.rs";
741        let results = GitHubPermalink::parse_all(text);
742        assert_eq!(results.len(), 1);
743        assert_eq!(results[0].git_ref, "abc");
744    }
745
746    #[test]
747    fn parse_deduplicates_urls() {
748        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs \
749                    https://github.com/owner/repo/blob/abcd1234/src/lib.rs";
750        let results = GitHubPermalink::parse_all(text);
751        assert_eq!(results.len(), 1);
752    }
753
754    #[test]
755    fn parse_limits_to_three() {
756        let text = "\
757            https://github.com/o/r/blob/aaaa1111/a.rs \
758            https://github.com/o/r/blob/bbbb2222/b.rs \
759            https://github.com/o/r/blob/cccc3333/c.rs \
760            https://github.com/o/r/blob/dddd4444/d.rs";
761        let results = GitHubPermalink::parse_all(text);
762        assert_eq!(results.len(), 3);
763    }
764
765    #[test]
766    fn parse_multiple_different_urls() {
767        let text = "Check https://github.com/a/b/blob/1111aaaa/x.rs#L1 and \
768                    https://github.com/c/d/blob/2222bbbb/y.py#L5-L10";
769        let results = GitHubPermalink::parse_all(text);
770        assert_eq!(results.len(), 2);
771        assert_eq!(results[0].owner, "a");
772        assert_eq!(results[1].owner, "c");
773        assert_eq!(results[1].path, "y.py");
774    }
775
776    #[test]
777    fn parse_no_match() {
778        let text = "Hello, no links here!";
779        let results = GitHubPermalink::parse_all(text);
780        assert!(results.is_empty());
781    }
782
783    #[test]
784    fn parse_permalink_with_query() {
785        let text = "https://github.com/owner/repo/blob/abcd1234/README.md?plain=1";
786        let results = GitHubPermalink::parse_all(text);
787        assert_eq!(results.len(), 1);
788        assert_eq!(results[0].path, "README.md");
789        assert!(results[0].line_range.is_none());
790    }
791
792    #[test]
793    fn parse_permalink_with_query_and_line_range() {
794        // Regression test for issue #593: the URL reported in the issue.
795        let text = "https://github.com/m1sk9/dotfiles/blob/02962edfa2d9f5e1ed3f9a7cded1055b1a64b03d/private_dot_claude/CLAUDE.md?plain=1#L21-L46";
796        let results = GitHubPermalink::parse_all(text);
797        assert_eq!(results.len(), 1);
798        assert_eq!(results[0].owner, "m1sk9");
799        assert_eq!(results[0].repo, "dotfiles");
800        assert_eq!(
801            results[0].git_ref,
802            "02962edfa2d9f5e1ed3f9a7cded1055b1a64b03d"
803        );
804        assert_eq!(results[0].path, "private_dot_claude/CLAUDE.md");
805        let range = results[0].line_range.unwrap();
806        assert_eq!(range.start, 21);
807        assert_eq!(range.end, 46);
808    }
809
810    #[test]
811    fn parse_permalink_with_query_and_single_line() {
812        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs?plain=1#L10";
813        let results = GitHubPermalink::parse_all(text);
814        assert_eq!(results.len(), 1);
815        assert_eq!(results[0].path, "src/lib.rs");
816        let range = results[0].line_range.unwrap();
817        assert_eq!(range.start, 10);
818        assert_eq!(range.end, 10);
819    }
820
821    #[test]
822    fn parse_permalink_with_multiple_query_params() {
823        let text = "https://github.com/owner/repo/blob/abcd1234/src/lib.rs?foo=bar&baz=qux#L1-L2";
824        let results = GitHubPermalink::parse_all(text);
825        assert_eq!(results.len(), 1);
826        assert_eq!(results[0].path, "src/lib.rs");
827        let range = results[0].line_range.unwrap();
828        assert_eq!(range.start, 1);
829        assert_eq!(range.end, 2);
830    }
831
832    #[test]
833    fn parse_ignores_angle_bracket_link() {
834        let text = "<https://github.com/owner/repo/blob/abcd1234/src/lib.rs#L10-L20>";
835        let results = GitHubPermalink::parse_all(text);
836        assert!(results.is_empty());
837    }
838
839    #[test]
840    fn parse_nested_path() {
841        let text = "https://github.com/owner/repo/blob/abcd1234/src/deeply/nested/path/file.rs";
842        let results = GitHubPermalink::parse_all(text);
843        assert_eq!(results.len(), 1);
844        assert_eq!(results[0].path, "src/deeply/nested/path/file.rs");
845    }
846
847    #[test]
848    fn parse_short_commit_sha() {
849        // 4-character SHA is the minimum
850        let text = "https://github.com/owner/repo/blob/abcd/file.rs";
851        let results = GitHubPermalink::parse_all(text);
852        assert_eq!(results.len(), 1);
853        assert_eq!(results[0].git_ref, "abcd");
854    }
855
856    // --- build_code_block ---
857
858    fn make_permalink(path: &str, line_range: Option<LineRange>) -> GitHubPermalink {
859        GitHubPermalink {
860            owner: "owner".to_string(),
861            repo: "repo".to_string(),
862            git_ref: "abcdef1234567".to_string(),
863            path: path.to_string(),
864            line_range,
865        }
866    }
867
868    #[test]
869    fn build_code_block_full_file() {
870        let permalink = make_permalink("src/main.rs", None);
871        let body = "fn main() {\n    println!(\"hello\");\n}";
872        let result = permalink.build_code_block(body, 50);
873
874        match result {
875            ExpandedContent::CodeBlock {
876                language,
877                code,
878                metadata,
879            } => {
880                assert_eq!(language, "rust");
881                assert_eq!(code, body);
882                assert_eq!(metadata, "`src/main.rs` - owner/repo@abcdef1");
883            }
884            _ => panic!("expected CodeBlock"),
885        }
886    }
887
888    #[test]
889    fn build_code_block_with_line_range() {
890        let permalink = make_permalink("src/lib.rs", Some(LineRange { start: 2, end: 3 }));
891        let body = "line2\nline3\nline4";
892        let result = permalink.build_code_block(body, 50);
893
894        match result {
895            ExpandedContent::CodeBlock {
896                language,
897                code,
898                metadata,
899            } => {
900                assert_eq!(language, "rust");
901                assert_eq!(code, "line2\nline3");
902                assert!(metadata.contains("L2-L3"));
903            }
904            _ => panic!("expected CodeBlock"),
905        }
906    }
907
908    #[test]
909    fn build_code_block_truncated() {
910        let permalink = make_permalink("app.py", None);
911        let body = "a\nb\nc\nd\ne";
912        let result = permalink.build_code_block(body, 2);
913
914        match result {
915            ExpandedContent::CodeBlock { code, metadata, .. } => {
916                assert_eq!(code, "a\nb");
917                assert!(metadata.contains("truncated to 2 lines"));
918            }
919            _ => panic!("expected CodeBlock"),
920        }
921    }
922
923    #[test]
924    fn build_code_block_line_range_truncated() {
925        let permalink = make_permalink("app.py", Some(LineRange { start: 1, end: 5 }));
926        let body = "a\nb\nc\nd\ne";
927        let result = permalink.build_code_block(body, 3);
928
929        match result {
930            ExpandedContent::CodeBlock { code, metadata, .. } => {
931                assert_eq!(code, "a\nb\nc");
932                assert!(metadata.contains("L1-L5"));
933                assert!(metadata.contains("truncated to 3 lines"));
934            }
935            _ => panic!("expected CodeBlock"),
936        }
937    }
938
939    #[test]
940    fn build_code_block_dockerfile_language() {
941        let permalink = make_permalink("docker/Dockerfile", None);
942        let body = "FROM rust:latest";
943        let result = permalink.build_code_block(body, 50);
944
945        match result {
946            ExpandedContent::CodeBlock { language, .. } => {
947                assert_eq!(language, "dockerfile");
948            }
949            _ => panic!("expected CodeBlock"),
950        }
951    }
952
953    #[test]
954    fn build_code_block_short_commit() {
955        let permalink = GitHubPermalink {
956            owner: "o".to_string(),
957            repo: "r".to_string(),
958            git_ref: "abcd".to_string(),
959            path: "f.rs".to_string(),
960            line_range: None,
961        };
962        let result = permalink.build_code_block("x", 50);
963
964        match result {
965            ExpandedContent::CodeBlock { metadata, .. } => {
966                assert!(metadata.contains("o/r@abcd"));
967            }
968            _ => panic!("expected CodeBlock"),
969        }
970    }
971
972    #[test]
973    fn build_code_block_branch_ref() {
974        let permalink = GitHubPermalink {
975            owner: "o".to_string(),
976            repo: "r".to_string(),
977            git_ref: "main".to_string(),
978            path: "f.rs".to_string(),
979            line_range: None,
980        };
981        let result = permalink.build_code_block("x", 50);
982
983        match result {
984            ExpandedContent::CodeBlock { metadata, .. } => {
985                // Branch names should not be truncated
986                assert!(metadata.contains("o/r@main"));
987            }
988            _ => panic!("expected CodeBlock"),
989        }
990    }
991
992    #[test]
993    fn build_code_block_branch_ref_with_line_range() {
994        let permalink = GitHubPermalink {
995            owner: "o".to_string(),
996            repo: "r".to_string(),
997            git_ref: "develop".to_string(),
998            path: "src/lib.rs".to_string(),
999            line_range: Some(LineRange { start: 3, end: 5 }),
1000        };
1001        let body = "c\nd\ne\nf";
1002        let result = permalink.build_code_block(body, 50);
1003
1004        match result {
1005            ExpandedContent::CodeBlock { code, metadata, .. } => {
1006                assert_eq!(code, "c\nd\ne");
1007                assert!(metadata.contains("L3-L5"));
1008                assert!(metadata.contains("o/r@develop"));
1009            }
1010            _ => panic!("expected CodeBlock"),
1011        }
1012    }
1013
1014    fn metadata_of(owner: &str, repo: &str, git_ref: &str, path: &str) -> String {
1015        let permalink = GitHubPermalink {
1016            owner: owner.to_string(),
1017            repo: repo.to_string(),
1018            git_ref: git_ref.to_string(),
1019            path: path.to_string(),
1020            line_range: Some(LineRange { start: 1, end: 2 }),
1021        };
1022        code_block_parts(permalink.build_code_block("a\nb", 50)).2
1023    }
1024
1025    #[test]
1026    fn build_code_block_metadata_keeps_hyphens_and_dots_unescaped() {
1027        assert_eq!(
1028            metadata_of("rust-lang", "rust.vim", "release-v1.0", "src/main.rs"),
1029            "`src/main.rs` (L1-L2) - rust-lang/rust.vim@release-v1.0"
1030        );
1031        assert_eq!(
1032            metadata_of(
1033                "rust-lang",
1034                "cargo",
1035                "v1.0.0",
1036                "private_dot_claude/CLAUDE.md"
1037            ),
1038            "`private_dot_claude/CLAUDE.md` (L1-L2) - rust-lang/cargo@v1.0.0"
1039        );
1040    }
1041
1042    #[test]
1043    fn build_code_block_metadata_escapes_markdown_in_owner_repo_and_ref() {
1044        assert_eq!(
1045            metadata_of("my_org", "**repo**", "[x](https://evil.example)", "f.rs"),
1046            r"`f.rs` (L1-L2) - my\_org/\*\*repo\*\*@\[x\](https\://evil.example)"
1047        );
1048    }
1049
1050    #[test]
1051    fn build_code_block_metadata_stays_on_one_line() {
1052        let metadata = metadata_of("o\n# Announcement", "r", "main\n> quote", "f.rs");
1053
1054        assert_eq!(
1055            metadata,
1056            r"`f.rs` (L1-L2) - o \# Announcement/r@main \> quote"
1057        );
1058    }
1059
1060    #[test]
1061    fn build_code_block_metadata_cannot_be_closed_by_a_backtick_in_the_path() {
1062        // The permalink from the report: everything after `#` in the ref is a
1063        // fragment, so the displayed path is never fetched and can be anything.
1064        let permalink = GitHubPermalink::parse_all(
1065            r"https://github.com/att/repo/blob/main\payload.md#/x`[y](https://evil.example)",
1066        )
1067        .remove(0);
1068
1069        let (_, _, metadata) = code_block_parts(permalink.build_code_block("a", 50));
1070        assert_eq!(
1071            metadata,
1072            r"x\`\[y\](https\://evil.example) - att/repo@main\\payload.md\#"
1073        );
1074    }
1075
1076    // --- GitHubPermalink::read_limit ---
1077
1078    fn full(lines: usize) -> ReadLimit {
1079        ReadLimit {
1080            skip_lines: 0,
1081            lines,
1082            probe_bytes: 0,
1083        }
1084    }
1085
1086    fn probed(lines: usize) -> ReadLimit {
1087        ReadLimit {
1088            skip_lines: 0,
1089            lines,
1090            probe_bytes: PROBE_BYTES,
1091        }
1092    }
1093
1094    fn skipping(skip_lines: usize, limit: ReadLimit) -> ReadLimit {
1095        ReadLimit {
1096            skip_lines,
1097            ..limit
1098        }
1099    }
1100
1101    #[test]
1102    fn read_limit_without_range_probes_past_max_lines() {
1103        let permalink = make_permalink("f.rs", None);
1104        assert_eq!(permalink.read_limit(50), probed(50));
1105    }
1106
1107    #[test]
1108    fn read_limit_with_range_capped_by_range_end_reads_end_in_full() {
1109        let permalink = make_permalink("f.rs", Some(LineRange { start: 3, end: 5 }));
1110        assert_eq!(permalink.read_limit(50), skipping(2, full(5)));
1111    }
1112
1113    #[test]
1114    fn read_limit_with_range_ending_exactly_at_max_lines_reads_end_in_full() {
1115        let permalink = make_permalink("f.rs", Some(LineRange { start: 3, end: 52 }));
1116        assert_eq!(permalink.read_limit(50), skipping(2, full(52)));
1117    }
1118
1119    #[test]
1120    fn read_limit_with_range_capped_by_max_lines_probes_next_line() {
1121        let permalink = make_permalink(
1122            "f.rs",
1123            Some(LineRange {
1124                start: 10,
1125                end: 1000,
1126            }),
1127        );
1128        // Lines 10..=59 are displayed; line 60 only decides the truncation flag.
1129        assert_eq!(permalink.read_limit(50), skipping(9, probed(59)));
1130    }
1131
1132    #[test]
1133    fn read_limit_saturates_on_huge_max_lines() {
1134        let permalink = make_permalink("f.rs", None);
1135        assert_eq!(permalink.read_limit(usize::MAX), probed(usize::MAX));
1136
1137        let ranged = make_permalink("f.rs", Some(LineRange { start: 1, end: 3 }));
1138        assert_eq!(ranged.read_limit(usize::MAX), full(3));
1139    }
1140
1141    // --- LimitedBody ---
1142
1143    /// Feeds `chunks` through a `LimitedBody`, stopping once it reports completion.
1144    fn read_chunks(chunks: &[&[u8]], limit: ReadLimit) -> Result<String, GitHubExpandError> {
1145        let mut body = LimitedBody::new(limit);
1146        for chunk in chunks {
1147            if body.is_complete() {
1148                break;
1149            }
1150            body.push(chunk)?;
1151        }
1152        body.finish()
1153    }
1154
1155    #[test]
1156    fn limited_body_stops_after_needed_newlines() {
1157        let result = read_chunks(&[b"a\nb\nc\nd\n"], full(2)).unwrap();
1158        assert_eq!(result, "a\nb\n");
1159    }
1160
1161    #[test]
1162    fn limited_body_joins_chunk_boundaries() {
1163        let result = read_chunks(&[b"hel", b"lo\nwor", b"ld\n"], full(2)).unwrap();
1164        assert_eq!(result, "hello\nworld\n");
1165    }
1166
1167    #[test]
1168    fn limited_body_handles_newline_at_chunk_boundary() {
1169        let result = read_chunks(&[b"a\n", b"b\n", b"c\n"], full(2)).unwrap();
1170        assert_eq!(result, "a\nb\n");
1171    }
1172
1173    #[test]
1174    fn limited_body_keeps_partial_last_line_without_trailing_newline() {
1175        // Fewer newlines than needed: the whole body is read and the unterminated
1176        // last line is retained.
1177        let result = read_chunks(&[b"a\nb\nc"], full(5)).unwrap();
1178        assert_eq!(result, "a\nb\nc");
1179    }
1180
1181    #[test]
1182    fn limited_body_rejects_over_limit() {
1183        // A single line longer than the limit: no newline ever satisfies the request.
1184        let huge = vec![b'x'; MAX_BODY_BYTES + 1];
1185        let err = read_chunks(&[&huge], full(2)).unwrap_err();
1186        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1187    }
1188
1189    #[test]
1190    fn limited_body_rejects_over_limit_across_chunks() {
1191        let half = vec![b'x'; MAX_BODY_BYTES / 2 + 1];
1192        let err = read_chunks(&[&half, &half], full(2)).unwrap_err();
1193        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1194    }
1195
1196    #[test]
1197    fn limited_body_accepts_when_needed_lines_met_before_limit() {
1198        // The needed line ends one byte before the limit; the rest of the chunk
1199        // would overshoot it but is discarded.
1200        let mut chunk = vec![b'x'; MAX_BODY_BYTES - 1];
1201        chunk.push(b'\n');
1202        chunk.extend_from_slice(&vec![b'y'; MAX_BODY_BYTES]);
1203
1204        let result = read_chunks(&[&chunk], full(1)).unwrap();
1205        assert_eq!(result.len(), MAX_BODY_BYTES);
1206        assert!(result.ends_with('\n'));
1207    }
1208
1209    #[test]
1210    fn limited_body_decodes_utf8_split_across_chunks() {
1211        // "あ" is E3 81 82; split it between two chunks.
1212        let result = read_chunks(&[b"\xe3\x81", b"\x82\n"], full(1)).unwrap();
1213        assert_eq!(result, "あ\n");
1214    }
1215
1216    #[test]
1217    fn limited_body_strips_leading_utf8_bom() {
1218        let result = read_chunks(&[b"\xef\xbb\xbffn main() {}\n"], full(1)).unwrap();
1219        assert_eq!(result, "fn main() {}\n");
1220    }
1221
1222    #[test]
1223    fn limited_body_keeps_bom_appearing_mid_body() {
1224        let result = read_chunks(&["a\n\u{feff}b\n".as_bytes()], full(2)).unwrap();
1225        assert_eq!(result, "a\n\u{feff}b\n");
1226    }
1227
1228    #[test]
1229    fn limited_body_decodes_utf16_read_in_full() {
1230        // UTF-16LE BOM followed by "hi\n". A BOM selects its own encoding, so a body
1231        // read in full decodes rather than turning into replacement characters.
1232        let result = read_chunks(&[b"\xff\xfeh\0i\0\n\0"], full(5)).unwrap();
1233        assert_eq!(result, "hi\n");
1234    }
1235
1236    #[test]
1237    fn limited_body_clips_utf16_when_stopping_early() {
1238        // Known limitation: lines are counted in raw bytes, so stopping at the `0A`
1239        // of a UTF-16LE `\n` (`0A 00`) drops the trailing `00` and leaves the final
1240        // code unit incomplete. Only the boundary line is affected.
1241        let result = read_chunks(&[b"\xff\xfeh\0i\0\n\0j\0\n\0"], full(1)).unwrap();
1242        assert_eq!(result, "hi\u{fffd}");
1243    }
1244
1245    #[test]
1246    fn limited_body_replaces_invalid_utf8() {
1247        let result = read_chunks(&[b"a\xffb\n"], full(1)).unwrap();
1248        assert_eq!(result, "a\u{fffd}b\n");
1249    }
1250
1251    #[test]
1252    fn limited_body_with_zero_lines_reads_nothing() {
1253        let result = read_chunks(&[b"a\nb\n"], full(0)).unwrap();
1254        assert_eq!(result, "");
1255    }
1256
1257    #[test]
1258    fn limited_body_probe_keeps_probe_bytes_past_needed_lines() {
1259        let result = read_chunks(&[b"a\nb\nccc\nd\n"], probed(2)).unwrap();
1260        assert_eq!(result, "a\nb\ncc");
1261    }
1262
1263    #[test]
1264    fn limited_body_probe_takes_bytes_from_next_chunk() {
1265        let result = read_chunks(&[b"a\nb\n", b"ccc\n"], probed(2)).unwrap();
1266        assert_eq!(result, "a\nb\ncc");
1267    }
1268
1269    #[test]
1270    fn limited_body_probe_spans_chunk_boundary() {
1271        let result = read_chunks(&[b"a\nb", b"bb\n"], probed(1)).unwrap();
1272        assert_eq!(result, "a\nbb");
1273    }
1274
1275    #[test]
1276    fn limited_body_probe_skips_empty_chunk() {
1277        let result = read_chunks(&[b"a\n", b"", b"bbb\n"], probed(1)).unwrap();
1278        assert_eq!(result, "a\nbb");
1279    }
1280
1281    #[test]
1282    fn limited_body_probe_keeps_single_trailing_byte() {
1283        let result = read_chunks(&[b"a\nb"], probed(1)).unwrap();
1284        assert_eq!(result, "a\nb");
1285    }
1286
1287    #[test]
1288    fn limited_body_probe_without_further_content_reads_whole_body() {
1289        let result = read_chunks(&[b"a\nb\n"], probed(2)).unwrap();
1290        assert_eq!(result, "a\nb\n");
1291    }
1292
1293    #[test]
1294    fn limited_body_probe_with_zero_lines_reads_only_probe_bytes() {
1295        let result = read_chunks(&[b"abc\n"], probed(0)).unwrap();
1296        assert_eq!(result, "ab");
1297    }
1298
1299    #[test]
1300    fn limited_body_probe_accepts_huge_line_past_needed_lines() {
1301        // #649: the probe line is not displayed, so its size must not matter.
1302        let mut chunk = b"a\nb\n".to_vec();
1303        chunk.extend_from_slice(&vec![b'x'; MAX_BODY_BYTES + 1]);
1304
1305        let result = read_chunks(&[&chunk], probed(2)).unwrap();
1306        assert_eq!(result, "a\nb\nxx");
1307    }
1308
1309    #[test]
1310    fn limited_body_probe_bytes_count_toward_limit() {
1311        let mut chunk = vec![b'x'; MAX_BODY_BYTES - 2];
1312        chunk.extend_from_slice(b"\nyy");
1313
1314        let err = read_chunks(&[&chunk], probed(1)).unwrap_err();
1315        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1316    }
1317
1318    // --- LimitedBody: skipping lines before the range (#732) ---
1319
1320    #[test]
1321    fn limited_body_skip_drops_lines_before_start() {
1322        let result = read_chunks(&[b"a\nb\nc\nd\n"], skipping(2, full(3))).unwrap();
1323        assert_eq!(result, "c\n");
1324    }
1325
1326    #[test]
1327    fn limited_body_skip_boundary_inside_chunk_keeps_rest_of_chunk() {
1328        let result = read_chunks(&[b"a\nb\nc\nd\ne\n"], skipping(1, full(3))).unwrap();
1329        assert_eq!(result, "b\nc\n");
1330    }
1331
1332    #[test]
1333    fn limited_body_skip_boundary_at_chunk_boundary() {
1334        let result = read_chunks(&[b"a\nb\n", b"c\nd\n"], skipping(2, full(3))).unwrap();
1335        assert_eq!(result, "c\n");
1336    }
1337
1338    #[test]
1339    fn limited_body_skip_boundary_across_many_chunks() {
1340        let result = read_chunks(
1341            &[b"aa", b"a\nb", b"", b"bb\nc", b"cc\nd\n"],
1342            skipping(2, full(4)),
1343        )
1344        .unwrap();
1345        assert_eq!(result, "ccc\nd\n");
1346    }
1347
1348    #[test]
1349    fn limited_body_skip_with_single_byte_chunks() {
1350        let chunks: Vec<&[u8]> = b"a\nb\nc\n".chunks(1).collect();
1351        let result = read_chunks(&chunks, skipping(2, full(3))).unwrap();
1352        assert_eq!(result, "c\n");
1353    }
1354
1355    #[test]
1356    fn limited_body_skip_past_end_of_body_retains_nothing() {
1357        let result = read_chunks(&[b"a\nb"], skipping(5, full(8))).unwrap();
1358        assert_eq!(result, "");
1359    }
1360
1361    #[test]
1362    fn limited_body_skip_with_probe_reads_probe_after_last_line() {
1363        let result = read_chunks(&[b"a\nb\nccc\nd\n"], skipping(1, probed(2))).unwrap();
1364        assert_eq!(result, "b\ncc");
1365    }
1366
1367    #[test]
1368    fn limited_body_skip_ignores_huge_skipped_line() {
1369        // #732: a line before the range start is not displayed, so its size must not
1370        // count toward the retained-bytes limit.
1371        let mut chunk = vec![b'x'; MAX_BODY_BYTES + 1];
1372        chunk.extend_from_slice(b"\nb\nc\n");
1373
1374        let result = read_chunks(&[&chunk], skipping(1, full(3))).unwrap();
1375        assert_eq!(result, "b\nc\n");
1376    }
1377
1378    #[test]
1379    fn limited_body_skip_ignores_huge_skipped_line_across_chunks() {
1380        let half = vec![b'x'; MAX_BODY_BYTES / 2 + 1];
1381        let result = read_chunks(&[&half, &half, b"\nb\n"], skipping(1, full(2))).unwrap();
1382        assert_eq!(result, "b\n");
1383    }
1384
1385    #[test]
1386    fn limited_body_skip_applies_body_limit_to_retained_bytes() {
1387        let mut chunk = b"a\n".to_vec();
1388        chunk.extend_from_slice(&vec![b'x'; MAX_BODY_BYTES + 1]);
1389
1390        let err = read_chunks(&[&chunk], skipping(1, full(3))).unwrap_err();
1391        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1392    }
1393
1394    #[test]
1395    fn limited_body_skip_rejects_over_skipped_limit() {
1396        let chunk = vec![b'x'; MAX_SKIPPED_BYTES + 1];
1397        let err = read_chunks(&[&chunk], skipping(1, full(2))).unwrap_err();
1398        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1399    }
1400
1401    #[test]
1402    fn limited_body_skip_rejects_over_skipped_limit_across_chunks() {
1403        let chunk = vec![b'x'; MAX_SKIPPED_BYTES / 2 + 1];
1404        let err = read_chunks(&[&chunk, &chunk, b"\nb\n"], skipping(1, full(2))).unwrap_err();
1405        assert!(matches!(err, GitHubExpandError::ContentTooLarge));
1406    }
1407
1408    #[test]
1409    fn limited_body_skip_accepts_skipped_bytes_up_to_limit() {
1410        let mut chunk = vec![b'x'; MAX_SKIPPED_BYTES - 1];
1411        chunk.extend_from_slice(b"\nb\n");
1412
1413        let result = read_chunks(&[&chunk], skipping(1, full(2))).unwrap();
1414        assert_eq!(result, "b\n");
1415    }
1416
1417    #[test]
1418    fn limited_body_skip_drops_leading_bom_with_the_skipped_line() {
1419        let result = read_chunks(&[b"\xef\xbb\xbfa\nb\n"], skipping(1, full(2))).unwrap();
1420        assert_eq!(result, "b\n");
1421    }
1422
1423    #[test]
1424    fn limited_body_skip_keeps_bom_at_start_of_first_retained_line() {
1425        let result = read_chunks(&["a\n\u{feff}b\n".as_bytes()], skipping(1, full(2))).unwrap();
1426        assert_eq!(result, "\u{feff}b\n");
1427    }
1428
1429    #[test]
1430    fn limited_body_skip_reads_utf16_from_its_start_and_drops_skipped_lines_after_decoding() {
1431        // Skipping at the `0A` of a UTF-16LE `\n` would leave a stray `00` at the
1432        // start of the retained body, so the raw bytes are kept and the BOM still
1433        // applies; the skipped line is dropped from the decoded text.
1434        let result = read_chunks(&[b"\xff\xfeh\0i\0\n\0j\0\n\0"], skipping(1, full(2))).unwrap();
1435        assert_eq!(result, "j\u{fffd}");
1436    }
1437
1438    #[test]
1439    fn limited_body_skip_detects_utf16_bom_split_across_chunks() {
1440        let result =
1441            read_chunks(&[b"\xff", b"\xfeh\0i\0\n\0j\0\n\0"], skipping(1, full(5))).unwrap();
1442        assert_eq!(result, "j\n");
1443    }
1444
1445    // --- early truncation equivalence ---
1446
1447    fn code_block_parts(content: ExpandedContent) -> (String, String, String) {
1448        match content {
1449            ExpandedContent::CodeBlock {
1450                language,
1451                code,
1452                metadata,
1453            } => (language, code, metadata),
1454            _ => panic!("expected CodeBlock"),
1455        }
1456    }
1457
1458    /// Asserts that reading only up to `read_limit` produces the same code block as
1459    /// reading the whole body — this is what makes the early stop safe.
1460    fn assert_truncated_read_matches_full(
1461        permalink: &GitHubPermalink,
1462        body: &str,
1463        max_lines: usize,
1464    ) {
1465        let truncated = read_chunks(&[body.as_bytes()], permalink.read_limit(max_lines)).unwrap();
1466        let skip = permalink
1467            .line_range
1468            .map_or(0, |range| range.start.saturating_sub(1));
1469        let from_start: String = body.split_inclusive('\n').skip(skip).collect();
1470        assert_eq!(
1471            code_block_parts(permalink.build_code_block(&truncated, max_lines)),
1472            code_block_parts(permalink.build_code_block(&from_start, max_lines)),
1473            "body: {body:?}, max_lines: {max_lines}"
1474        );
1475    }
1476
1477    #[test]
1478    fn early_read_matches_full_read_without_range() {
1479        let permalink = make_permalink("f.rs", None);
1480        let body = "a\nb\nc\nd\ne\nf\n";
1481        for max_lines in [1, 2, 5, 6, 50] {
1482            assert_truncated_read_matches_full(&permalink, body, max_lines);
1483        }
1484    }
1485
1486    #[test]
1487    fn early_read_matches_full_read_without_trailing_newline() {
1488        let permalink = make_permalink("f.rs", None);
1489        let body = "a\nb\nc";
1490        for max_lines in [1, 2, 3, 50] {
1491            assert_truncated_read_matches_full(&permalink, body, max_lines);
1492        }
1493    }
1494
1495    #[test]
1496    fn early_read_matches_full_read_with_blank_and_crlf_lines() {
1497        let permalink = make_permalink("f.rs", None);
1498        for body in ["a\n\n\nb\n", "a\r\n\r\nb\r\n", "a\n\r\n"] {
1499            for max_lines in [1, 2, 3, 50] {
1500                assert_truncated_read_matches_full(&permalink, body, max_lines);
1501            }
1502        }
1503    }
1504
1505    #[test]
1506    fn early_read_matches_full_read_with_range() {
1507        let body = "a\nb\nc\nd\ne\nf\ng\nh\n";
1508        let ranges = [
1509            LineRange { start: 1, end: 3 },
1510            LineRange { start: 3, end: 5 },
1511            LineRange { start: 2, end: 4 },
1512            LineRange { start: 2, end: 100 },
1513            LineRange {
1514                start: 100,
1515                end: 200,
1516            },
1517        ];
1518        for range in ranges {
1519            let permalink = make_permalink("f.rs", Some(range));
1520            for max_lines in [1, 2, 3, 50] {
1521                assert_truncated_read_matches_full(&permalink, body, max_lines);
1522            }
1523        }
1524    }
1525
1526    #[test]
1527    fn early_read_previews_file_with_huge_line_past_max_lines() {
1528        // #649: a huge line just past the display limit used to fail the whole preview.
1529        let permalink = make_permalink("f.js", None);
1530        let body = format!("a\nb\n{}\n", "x".repeat(MAX_BODY_BYTES + 1));
1531        let read = read_chunks(&[body.as_bytes()], permalink.read_limit(2)).unwrap();
1532
1533        let (_, code, metadata) = code_block_parts(permalink.build_code_block(&read, 2));
1534        assert_eq!(code, "a\nb");
1535        assert!(metadata.contains("truncated to 2 lines"));
1536    }
1537
1538    #[test]
1539    fn early_read_previews_range_after_huge_line_before_start() {
1540        // #732: a huge line before the range start used to fail the whole preview.
1541        let permalink = make_permalink("f.js", Some(LineRange { start: 3, end: 4 }));
1542        let body = format!("a\n{}\nc\nd\ne\n", "x".repeat(MAX_BODY_BYTES + 1));
1543        let read = read_chunks(&[body.as_bytes()], permalink.read_limit(50)).unwrap();
1544
1545        let (_, code, metadata) = code_block_parts(permalink.build_code_block(&read, 50));
1546        assert_eq!(code, "c\nd");
1547        assert!(metadata.contains("L3-L4"));
1548    }
1549
1550    #[test]
1551    fn build_code_block_range_starting_past_end_is_empty() {
1552        let permalink = make_permalink("f.rs", Some(LineRange { start: 9, end: 12 }));
1553        let read = read_chunks(&[b"a\nb\n"], permalink.read_limit(50)).unwrap();
1554
1555        let (_, code, _) = code_block_parts(permalink.build_code_block(&read, 50));
1556        assert_eq!(code, "");
1557    }
1558
1559    #[test]
1560    fn build_code_block_reversed_range_is_empty() {
1561        let permalink = make_permalink("f.rs", Some(LineRange { start: 4, end: 2 }));
1562        let body = "d\ne\n";
1563
1564        let (_, code, _) = code_block_parts(permalink.build_code_block(body, 50));
1565        assert_eq!(code, "");
1566    }
1567
1568    #[test]
1569    fn early_read_keeps_truncation_flag_for_utf16le() {
1570        // UTF-16LE BOM followed by "hi\nj\n": the probe must reach past the `00`
1571        // completing the first `\n` to see that a second line exists.
1572        let permalink = make_permalink("f.txt", None);
1573        let body = b"\xff\xfeh\0i\0\n\0j\0\n\0";
1574        let read = read_chunks(&[body], permalink.read_limit(1)).unwrap();
1575
1576        let (_, code, metadata) = code_block_parts(permalink.build_code_block(&read, 1));
1577        assert_eq!(code, "hi");
1578        assert!(metadata.contains("truncated to 1 lines"));
1579    }
1580
1581    // --- ensure_not_empty ---
1582
1583    #[test]
1584    fn ensure_not_empty_rejects_empty_file() {
1585        let permalink = make_permalink("empty.rs", None);
1586        let result = ensure_not_empty(permalink.build_code_block("", 50));
1587        assert!(matches!(result, Err(GitHubExpandError::ContentEmpty)));
1588    }
1589
1590    #[test]
1591    fn ensure_not_empty_rejects_whitespace_only_file() {
1592        let permalink = make_permalink("blank.rs", None);
1593        let result = ensure_not_empty(permalink.build_code_block("\n\n  \n", 50));
1594        assert!(matches!(result, Err(GitHubExpandError::ContentEmpty)));
1595    }
1596
1597    #[test]
1598    fn ensure_not_empty_rejects_line_range_past_end_of_file() {
1599        let permalink = make_permalink("f.rs", Some(LineRange { start: 10, end: 20 }));
1600        // The body is read the way `expand` reads it: the lines before the range are
1601        // skipped, so a range past the end of the file leaves nothing.
1602        let read = read_chunks(&[b"a\nb\n"], permalink.read_limit(50)).unwrap();
1603        let result = ensure_not_empty(permalink.build_code_block(&read, 50));
1604        assert!(matches!(result, Err(GitHubExpandError::ContentEmpty)));
1605    }
1606
1607    #[test]
1608    fn ensure_not_empty_keeps_block_with_content() {
1609        let permalink = make_permalink("f.rs", None);
1610        let content = ensure_not_empty(permalink.build_code_block("a\n", 50)).unwrap();
1611        assert_eq!(code_block_parts(content).1, "a");
1612    }
1613
1614    #[test]
1615    fn early_read_reversed_range_is_empty_for_a_long_body() {
1616        // A reversed range ending before its own start - 1 never reaches the skip
1617        // boundary, so the read must still terminate with an empty selection.
1618        let permalink = make_permalink("f.rs", Some(LineRange { start: 10, end: 2 }));
1619        let body = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n";
1620        let read = read_chunks(&[body.as_bytes()], permalink.read_limit(50)).unwrap();
1621
1622        let (_, code, _) = code_block_parts(permalink.build_code_block(&read, 50));
1623        assert_eq!(code, "");
1624    }
1625
1626    #[test]
1627    fn early_read_range_in_utf16le_shows_the_requested_lines() {
1628        // UTF-16LE BOM followed by "a\nb\nc\nd\n"; the range starts at line 2 and is
1629        // cut to 2 lines, so the body is read with a probe like any other.
1630        let permalink = make_permalink("f.txt", Some(LineRange { start: 2, end: 99 }));
1631        let body = b"\xff\xfea\0\n\0b\0\n\0c\0\n\0d\0\n\0";
1632        let read = read_chunks(&[body], permalink.read_limit(2)).unwrap();
1633
1634        let (_, code, metadata) = code_block_parts(permalink.build_code_block(&read, 2));
1635        assert_eq!(code, "b\nc");
1636        assert!(metadata.contains("L2-L99, truncated to 2 lines"));
1637    }
1638
1639    // --- is_commit_sha / shorten_ref ---
1640
1641    #[test]
1642    fn is_commit_sha_valid() {
1643        assert!(is_commit_sha("abcd1234"));
1644        assert!(is_commit_sha("abcdef1234567890abcdef1234567890abcdef12"));
1645    }
1646
1647    #[test]
1648    fn is_commit_sha_boundary() {
1649        // Exactly 4 hex chars (minimum)
1650        assert!(is_commit_sha("abcd"));
1651        // Exactly 40 hex chars (full SHA-1)
1652        assert!(is_commit_sha("abcdef1234567890abcdef1234567890abcdef12"));
1653    }
1654
1655    #[test]
1656    fn is_commit_sha_invalid() {
1657        assert!(!is_commit_sha("main"));
1658        assert!(!is_commit_sha("develop"));
1659        assert!(!is_commit_sha("abc")); // too short
1660        assert!(!is_commit_sha("abcdef1234567890abcdef1234567890abcdef123")); // too long (41)
1661        assert!(!is_commit_sha("ghijkl")); // non-hex
1662        assert!(!is_commit_sha("")); // empty
1663        assert!(is_commit_sha("ABCD1234")); // uppercase hex is still valid hex
1664    }
1665
1666    #[test]
1667    fn shorten_ref_commit() {
1668        assert_eq!(shorten_ref("abcdef1234567890"), "abcdef1");
1669    }
1670
1671    #[test]
1672    fn shorten_ref_short_sha() {
1673        // 4-char SHA should not be truncated further
1674        assert_eq!(shorten_ref("abcd"), "abcd");
1675    }
1676
1677    #[test]
1678    fn shorten_ref_branch() {
1679        assert_eq!(shorten_ref("main"), "main");
1680        assert_eq!(shorten_ref("feature-branch"), "feature-branch");
1681        assert_eq!(shorten_ref("release-v1.0"), "release-v1.0");
1682        assert_eq!(shorten_ref("v2.0.0"), "v2.0.0");
1683    }
1684}