rumdl_lib/rules/
md034_no_bare_urls.rs

1/// Rule MD034: No unformatted URLs
2///
3/// See [docs/md034.md](../../docs/md034.md) for full documentation, configuration, and examples.
4use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
5use crate::utils::range_utils::{LineIndex, calculate_url_range};
6use crate::utils::regex_cache::{EMAIL_PATTERN, get_cached_regex};
7
8use crate::filtered_lines::FilteredLinesExt;
9use crate::lint_context::LintContext;
10
11// URL detection patterns
12const URL_QUICK_CHECK_STR: &str = r#"(?:https?|ftps?)://|@"#;
13const CUSTOM_PROTOCOL_PATTERN_STR: &str = r#"(?:grpc|ws|wss|ssh|git|svn|file|data|javascript|vscode|chrome|about|slack|discord|matrix|irc|redis|mongodb|postgresql|mysql|kafka|nats|amqp|mqtt|custom|app|api|service)://"#;
14const MARKDOWN_LINK_PATTERN_STR: &str = r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#;
15const MARKDOWN_EMPTY_LINK_PATTERN_STR: &str = r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(\)"#;
16const MARKDOWN_EMPTY_REF_PATTERN_STR: &str = r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\[\]"#;
17const ANGLE_LINK_PATTERN_STR: &str =
18    r#"<((?:https?|ftps?)://(?:\[[0-9a-fA-F:]+(?:%[a-zA-Z0-9]+)?\]|[^>]+)|[^@\s]+@[^@\s]+\.[^@\s>]+)>"#;
19const BADGE_LINK_LINE_STR: &str = r#"^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$"#;
20const MARKDOWN_IMAGE_PATTERN_STR: &str = r#"!\s*\[([^\]]*)\]\s*\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#;
21const SIMPLE_URL_REGEX_STR: &str = r#"(https?|ftps?)://(?:\[[0-9a-fA-F:%.]+\](?::\d+)?|[^\s<>\[\]()\\'\"`\]]+)(?:/[^\s<>\[\]()\\'\"`]*)?(?:\?[^\s<>\[\]()\\'\"`]*)?(?:#[^\s<>\[\]()\\'\"`]*)?"#;
22const IPV6_URL_REGEX_STR: &str = r#"(https?|ftps?)://\[[0-9a-fA-F:%.\-a-zA-Z]+\](?::\d+)?(?:/[^\s<>\[\]()\\'\"`]*)?(?:\?[^\s<>\[\]()\\'\"`]*)?(?:#[^\s<>\[\]()\\'\"`]*)?"#;
23const REFERENCE_DEF_RE_STR: &str = r"^\s*\[[^\]]+\]:\s*(?:https?|ftps?)://\S+$";
24const HTML_TAG_PATTERN_STR: &str = r#"<[^>]*>"#;
25const MULTILINE_LINK_CONTINUATION_STR: &str = r#"^[^\[]*\]\(.*\)"#;
26
27/// Reusable buffers for check_line to reduce allocations
28#[derive(Default)]
29struct LineCheckBuffers {
30    markdown_link_ranges: Vec<(usize, usize)>,
31    image_ranges: Vec<(usize, usize)>,
32    urls_found: Vec<(usize, usize, String)>,
33}
34
35#[derive(Default, Clone)]
36pub struct MD034NoBareUrls;
37
38impl MD034NoBareUrls {
39    #[inline]
40    pub fn should_skip_content(&self, content: &str) -> bool {
41        // Skip if content has no URLs and no email addresses
42        // Fast byte scanning for common URL/email indicators
43        let bytes = content.as_bytes();
44        !bytes.contains(&b':') && !bytes.contains(&b'@')
45    }
46
47    /// Remove trailing punctuation that is likely sentence punctuation, not part of the URL
48    fn trim_trailing_punctuation<'a>(&self, url: &'a str) -> &'a str {
49        let mut trimmed = url;
50
51        // Check for balanced parentheses - if we have unmatched closing parens, they're likely punctuation
52        let open_parens = url.chars().filter(|&c| c == '(').count();
53        let close_parens = url.chars().filter(|&c| c == ')').count();
54
55        if close_parens > open_parens {
56            // Find the last balanced closing paren position
57            let mut balance = 0;
58            let mut last_balanced_pos = url.len();
59
60            for (i, c) in url.chars().enumerate() {
61                if c == '(' {
62                    balance += 1;
63                } else if c == ')' {
64                    balance -= 1;
65                    if balance < 0 {
66                        // Found an unmatched closing paren
67                        last_balanced_pos = i;
68                        break;
69                    }
70                }
71            }
72
73            trimmed = &trimmed[..last_balanced_pos];
74        }
75
76        // Trim specific punctuation only if not followed by more URL-like chars
77        while let Some(last_char) = trimmed.chars().last() {
78            if matches!(last_char, '.' | ',' | ';' | ':' | '!' | '?') {
79                // Check if this looks like it could be part of the URL
80                // For ':' specifically, keep it if followed by digits (port number)
81                if last_char == ':' && trimmed.len() > 1 {
82                    // Don't trim
83                    break;
84                }
85                trimmed = &trimmed[..trimmed.len() - 1];
86            } else {
87                break;
88            }
89        }
90
91        trimmed
92    }
93
94    /// Check if line is inside a reference definition
95    fn is_reference_definition(&self, line: &str) -> bool {
96        get_cached_regex(REFERENCE_DEF_RE_STR)
97            .map(|re| re.is_match(line))
98            .unwrap_or(false)
99    }
100
101    /// Check if a position in a line is inside an HTML tag
102    fn is_in_html_tag(&self, line: &str, pos: usize) -> bool {
103        // Find all HTML tags in the line
104        if let Ok(re) = get_cached_regex(HTML_TAG_PATTERN_STR) {
105            for mat in re.find_iter(line) {
106                if pos >= mat.start() && pos < mat.end() {
107                    return true;
108                }
109            }
110        }
111        false
112    }
113
114    fn check_line(
115        &self,
116        line: &str,
117        ctx: &LintContext,
118        line_number: usize,
119        code_spans: &[crate::lint_context::CodeSpan],
120        buffers: &mut LineCheckBuffers,
121        line_index: &LineIndex,
122    ) -> Vec<LintWarning> {
123        let mut warnings = Vec::new();
124
125        // Skip reference definitions
126        if self.is_reference_definition(line) {
127            return warnings;
128        }
129
130        // Skip lines that are continuations of multiline markdown links
131        // Pattern: text](url) without a leading [
132        if let Ok(re) = get_cached_regex(MULTILINE_LINK_CONTINUATION_STR)
133            && re.is_match(line)
134        {
135            return warnings;
136        }
137
138        // Quick check - does this line potentially have a URL or email?
139        if let Ok(re) = get_cached_regex(URL_QUICK_CHECK_STR)
140            && !re.is_match(line)
141            && !line.contains('@')
142        {
143            return warnings;
144        }
145
146        // Clear and reuse buffers instead of allocating new ones
147        buffers.markdown_link_ranges.clear();
148        if let Ok(re) = get_cached_regex(MARKDOWN_LINK_PATTERN_STR) {
149            for cap in re.captures_iter(line) {
150                if let Some(mat) = cap.get(0) {
151                    buffers.markdown_link_ranges.push((mat.start(), mat.end()));
152                }
153            }
154        }
155
156        // Also include empty link patterns like [text]() and [text][]
157        if let Ok(re) = get_cached_regex(MARKDOWN_EMPTY_LINK_PATTERN_STR) {
158            for mat in re.find_iter(line) {
159                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
160            }
161        }
162
163        if let Ok(re) = get_cached_regex(MARKDOWN_EMPTY_REF_PATTERN_STR) {
164            for mat in re.find_iter(line) {
165                buffers.markdown_link_ranges.push((mat.start(), mat.end()));
166            }
167        }
168
169        if let Ok(re) = get_cached_regex(ANGLE_LINK_PATTERN_STR) {
170            for cap in re.captures_iter(line) {
171                if let Some(mat) = cap.get(0) {
172                    buffers.markdown_link_ranges.push((mat.start(), mat.end()));
173                }
174            }
175        }
176
177        // Find all markdown images for exclusion
178        buffers.image_ranges.clear();
179        if let Ok(re) = get_cached_regex(MARKDOWN_IMAGE_PATTERN_STR) {
180            for cap in re.captures_iter(line) {
181                if let Some(mat) = cap.get(0) {
182                    buffers.image_ranges.push((mat.start(), mat.end()));
183                }
184            }
185        }
186
187        // Check if this line contains only a badge link (common pattern)
188        let is_badge_line = get_cached_regex(BADGE_LINK_LINE_STR)
189            .map(|re| re.is_match(line))
190            .unwrap_or(false);
191
192        if is_badge_line {
193            return warnings;
194        }
195
196        // Find bare URLs
197        buffers.urls_found.clear();
198
199        // First, find IPv6 URLs (they need special handling)
200        if let Ok(re) = get_cached_regex(IPV6_URL_REGEX_STR) {
201            for mat in re.find_iter(line) {
202                let url_str = mat.as_str();
203                buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
204            }
205        }
206
207        // Then find regular URLs
208        if let Ok(re) = get_cached_regex(SIMPLE_URL_REGEX_STR) {
209            for mat in re.find_iter(line) {
210                let url_str = mat.as_str();
211
212                // Skip if it's an IPv6 URL (already handled)
213                if url_str.contains("://[") {
214                    continue;
215                }
216
217                // Skip malformed IPv6-like URLs
218                // Check for IPv6-like patterns that are malformed
219                if let Some(host_start) = url_str.find("://") {
220                    let after_protocol = &url_str[host_start + 3..];
221                    // If it looks like IPv6 (has :: or multiple :) but no brackets, skip if followed by ]
222                    if after_protocol.contains("::") || after_protocol.chars().filter(|&c| c == ':').count() > 1 {
223                        // Check if the next character after our match is ]
224                        if let Some(char_after) = line.chars().nth(mat.end())
225                            && char_after == ']'
226                        {
227                            // This is likely a malformed IPv6 URL like "https://::1]:8080"
228                            continue;
229                        }
230                    }
231                }
232
233                buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
234            }
235        }
236
237        // Process found URLs
238        for &(start, end, ref url_str) in buffers.urls_found.iter() {
239            // Skip custom protocols
240            if get_cached_regex(CUSTOM_PROTOCOL_PATTERN_STR)
241                .map(|re| re.is_match(url_str))
242                .unwrap_or(false)
243            {
244                continue;
245            }
246
247            // Check if this URL is inside a markdown link, angle bracket, or image
248            let mut is_inside_construct = false;
249            for &(link_start, link_end) in buffers.markdown_link_ranges.iter() {
250                if start >= link_start && end <= link_end {
251                    is_inside_construct = true;
252                    break;
253                }
254            }
255
256            for &(img_start, img_end) in buffers.image_ranges.iter() {
257                if start >= img_start && end <= img_end {
258                    is_inside_construct = true;
259                    break;
260                }
261            }
262
263            if is_inside_construct {
264                continue;
265            }
266
267            // Check if URL is inside an HTML tag
268            if self.is_in_html_tag(line, start) {
269                continue;
270            }
271
272            // Check if we're inside an HTML comment
273            let line_start_byte = line_index.get_line_start_byte(line_number).unwrap_or(0);
274            let absolute_pos = line_start_byte + start;
275            if ctx.is_in_html_comment(absolute_pos) {
276                continue;
277            }
278
279            // Clean up the URL by removing trailing punctuation
280            let trimmed_url = self.trim_trailing_punctuation(url_str);
281
282            // Only report if we have a valid URL after trimming
283            if !trimmed_url.is_empty() && trimmed_url != "//" {
284                let trimmed_len = trimmed_url.len();
285                let (start_line, start_col, end_line, end_col) =
286                    calculate_url_range(line_number, line, start, trimmed_len);
287
288                warnings.push(LintWarning {
289                    rule_name: Some("MD034".to_string()),
290                    line: start_line,
291                    column: start_col,
292                    end_line,
293                    end_column: end_col,
294                    message: format!("URL without angle brackets or link formatting: '{trimmed_url}'"),
295                    severity: Severity::Warning,
296                    fix: Some(Fix {
297                        range: {
298                            let line_start_byte = line_index.get_line_start_byte(line_number).unwrap_or(0);
299                            (line_start_byte + start)..(line_start_byte + start + trimmed_len)
300                        },
301                        replacement: format!("<{trimmed_url}>"),
302                    }),
303                });
304            }
305        }
306
307        // Check for bare email addresses
308        for cap in EMAIL_PATTERN.captures_iter(line) {
309            if let Some(mat) = cap.get(0) {
310                let email = mat.as_str();
311                let start = mat.start();
312                let end = mat.end();
313
314                // Check if email is inside angle brackets or markdown link
315                let mut is_inside_construct = false;
316                for &(link_start, link_end) in buffers.markdown_link_ranges.iter() {
317                    if start >= link_start && end <= link_end {
318                        is_inside_construct = true;
319                        break;
320                    }
321                }
322
323                if !is_inside_construct {
324                    // Check if email is inside an HTML tag
325                    if self.is_in_html_tag(line, start) {
326                        continue;
327                    }
328
329                    // Check if email is inside a code span
330                    let is_in_code_span = code_spans
331                        .iter()
332                        .any(|span| span.line == line_number && start >= span.start_col && start < span.end_col);
333
334                    if !is_in_code_span {
335                        let email_len = end - start;
336                        let (start_line, start_col, end_line, end_col) =
337                            calculate_url_range(line_number, line, start, email_len);
338
339                        warnings.push(LintWarning {
340                            rule_name: Some("MD034".to_string()),
341                            line: start_line,
342                            column: start_col,
343                            end_line,
344                            end_column: end_col,
345                            message: format!("Email address without angle brackets or link formatting: '{email}'"),
346                            severity: Severity::Warning,
347                            fix: Some(Fix {
348                                range: {
349                                    let line_start_byte = line_index.get_line_start_byte(line_number).unwrap_or(0);
350                                    (line_start_byte + start)..(line_start_byte + end)
351                                },
352                                replacement: format!("<{email}>"),
353                            }),
354                        });
355                    }
356                }
357            }
358        }
359
360        warnings
361    }
362}
363
364impl Rule for MD034NoBareUrls {
365    #[inline]
366    fn name(&self) -> &'static str {
367        "MD034"
368    }
369
370    fn as_any(&self) -> &dyn std::any::Any {
371        self
372    }
373
374    fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
375    where
376        Self: Sized,
377    {
378        Box::new(MD034NoBareUrls)
379    }
380
381    #[inline]
382    fn category(&self) -> RuleCategory {
383        RuleCategory::Link
384    }
385
386    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
387        !ctx.likely_has_links_or_images() && self.should_skip_content(ctx.content)
388    }
389
390    #[inline]
391    fn description(&self) -> &'static str {
392        "No bare URLs - wrap URLs in angle brackets"
393    }
394
395    fn check(&self, ctx: &LintContext) -> LintResult {
396        let mut warnings = Vec::new();
397        let content = ctx.content;
398
399        // Quick skip for content without URLs
400        if self.should_skip_content(content) {
401            return Ok(warnings);
402        }
403
404        // Create LineIndex for correct byte position calculations across all line ending types
405        let line_index = &ctx.line_index;
406
407        // Get code spans for exclusion
408        let code_spans = ctx.code_spans();
409
410        // Allocate reusable buffers once instead of per-line to reduce allocations
411        let mut buffers = LineCheckBuffers::default();
412
413        // Iterate over content lines, automatically skipping front matter and code blocks
414        // This uses the filtered iterator API which centralizes the skip logic
415        for line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
416            let mut line_warnings =
417                self.check_line(line.content, ctx, line.line_num, &code_spans, &mut buffers, line_index);
418
419            // Filter out warnings that are inside code spans
420            line_warnings.retain(|warning| {
421                // Check if the URL is inside a code span
422                !code_spans.iter().any(|span| {
423                    span.line == warning.line &&
424                    warning.column > 0 && // column is 1-indexed
425                    (warning.column - 1) >= span.start_col &&
426                    (warning.column - 1) < span.end_col
427                })
428            });
429
430            warnings.extend(line_warnings);
431        }
432
433        Ok(warnings)
434    }
435
436    fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
437        let mut content = ctx.content.to_string();
438        let mut warnings = self.check(ctx)?;
439
440        // Sort warnings by position to ensure consistent fix application
441        warnings.sort_by_key(|w| w.fix.as_ref().map(|f| f.range.start).unwrap_or(0));
442
443        // Apply fixes in reverse order to maintain positions
444        for warning in warnings.iter().rev() {
445            if let Some(fix) = &warning.fix {
446                let start = fix.range.start;
447                let end = fix.range.end;
448                content.replace_range(start..end, &fix.replacement);
449            }
450        }
451
452        Ok(content)
453    }
454}