1use std::sync::LazyLock;
5
6use regex::Regex;
7
8use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
9use crate::utils::range_utils::calculate_url_range;
10use crate::utils::regex_cache::{
11 EMAIL_PATTERN, URL_IPV6_REGEX, URL_QUICK_CHECK_REGEX, URL_STANDARD_REGEX, URL_WWW_REGEX, XMPP_URI_REGEX,
12};
13
14use crate::filtered_lines::FilteredLinesExt;
15use crate::lint_context::LintContext;
16
17static CUSTOM_PROTOCOL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
19 Regex::new(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)://"#).unwrap()
20});
21static MARKDOWN_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
22 Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#).unwrap()
23});
24static MARKDOWN_EMPTY_LINK_REGEX: LazyLock<Regex> =
25 LazyLock::new(|| Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\(\)"#).unwrap());
26static MARKDOWN_EMPTY_REF_REGEX: LazyLock<Regex> =
27 LazyLock::new(|| Regex::new(r#"\[(?:[^\[\]]|\[[^\]]*\])*\]\[\]"#).unwrap());
28static ANGLE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| {
29 Regex::new(
30 r#"<((?:https?|ftps?)://(?:\[[0-9a-fA-F:]+(?:%[a-zA-Z0-9]+)?\]|[^>]+)|xmpp:[^>]+|[^@\s]+@[^@\s]+\.[^@\s>]+)>"#,
31 )
32 .unwrap()
33});
34static BADGE_LINK_LINE_REGEX: LazyLock<Regex> =
35 LazyLock::new(|| Regex::new(r#"^\s*\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)\s*$"#).unwrap());
36static MARKDOWN_IMAGE_REGEX: LazyLock<Regex> =
37 LazyLock::new(|| Regex::new(r#"!\s*\[([^\]]*)\]\s*\(([^)\s]+)(?:\s+(?:\"[^\"]*\"|\'[^\']*\'))?\)"#).unwrap());
38static MULTILINE_LINK_CONTINUATION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"^[^\[]*\]\(.*\)"#).unwrap());
39static SHORTCUT_REF_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"\[([^\[\]]+)\]"#).unwrap());
40
41#[derive(Default)]
43struct LineCheckBuffers {
44 markdown_link_ranges: Vec<(usize, usize)>,
45 image_ranges: Vec<(usize, usize)>,
46 urls_found: Vec<(usize, usize, String)>,
47}
48
49#[derive(Default, Clone)]
50pub struct MD034NoBareUrls;
51
52impl MD034NoBareUrls {
53 #[inline]
54 pub fn should_skip_content(&self, content: &str) -> bool {
55 let bytes = content.as_bytes();
58 let has_colon = bytes.contains(&b':');
59 let has_at = bytes.contains(&b'@');
60 let has_www = content.contains("www.");
61 !has_colon && !has_at && !has_www
62 }
63
64 fn trim_trailing_punctuation<'a>(&self, url: &'a str) -> &'a str {
66 let mut trimmed = url;
67
68 let open_parens = url.chars().filter(|&c| c == '(').count();
70 let close_parens = url.chars().filter(|&c| c == ')').count();
71
72 if close_parens > open_parens {
73 let mut balance = 0;
75 let mut last_balanced_pos = url.len();
76
77 for (byte_idx, c) in url.char_indices() {
78 if c == '(' {
79 balance += 1;
80 } else if c == ')' {
81 balance -= 1;
82 if balance < 0 {
83 last_balanced_pos = byte_idx;
85 break;
86 }
87 }
88 }
89
90 trimmed = &trimmed[..last_balanced_pos];
91 }
92
93 while let Some(last_char) = trimmed.chars().last() {
95 if matches!(last_char, '.' | ',' | ';' | ':' | '!' | '?') {
96 if last_char == ':' && trimmed.len() > 1 {
99 break;
101 }
102 trimmed = &trimmed[..trimmed.len() - 1];
103 } else {
104 break;
105 }
106 }
107
108 trimmed
109 }
110
111 fn check_line(
112 &self,
113 line: &str,
114 ctx: &LintContext,
115 line_number: usize,
116 code_spans: &[crate::lint_context::CodeSpan],
117 buffers: &mut LineCheckBuffers,
118 ) -> Vec<LintWarning> {
119 let mut warnings = Vec::new();
120
121 if ctx.line_info(line_number).is_some_and(|info| info.in_html_block) {
123 return warnings;
124 }
125
126 if MULTILINE_LINK_CONTINUATION_REGEX.is_match(line) {
129 return warnings;
130 }
131
132 let has_quick_check = URL_QUICK_CHECK_REGEX.is_match(line);
134 let has_www = line.contains("www.");
135 let has_at = line.contains('@');
136
137 if !has_quick_check && !has_at && !has_www {
138 return warnings;
139 }
140
141 buffers.markdown_link_ranges.clear();
143 buffers.image_ranges.clear();
144
145 let has_bracket = line.contains('[');
146 let has_angle = line.contains('<');
147 let has_bang = line.contains('!');
148
149 if has_bracket {
150 for mat in MARKDOWN_LINK_REGEX.find_iter(line) {
151 buffers.markdown_link_ranges.push((mat.start(), mat.end()));
152 }
153
154 for mat in MARKDOWN_EMPTY_LINK_REGEX.find_iter(line) {
156 buffers.markdown_link_ranges.push((mat.start(), mat.end()));
157 }
158
159 for mat in MARKDOWN_EMPTY_REF_REGEX.find_iter(line) {
160 buffers.markdown_link_ranges.push((mat.start(), mat.end()));
161 }
162
163 for mat in SHORTCUT_REF_REGEX.find_iter(line) {
165 let end = mat.end();
166 let next_non_ws = line[end..].bytes().find(|b| !b.is_ascii_whitespace());
167 if next_non_ws == Some(b'(') || next_non_ws == Some(b'[') {
168 continue;
169 }
170 buffers.markdown_link_ranges.push((mat.start(), mat.end()));
171 }
172
173 if has_bang && BADGE_LINK_LINE_REGEX.is_match(line) {
175 return warnings;
176 }
177 }
178
179 if has_angle {
180 for mat in ANGLE_LINK_REGEX.find_iter(line) {
181 buffers.markdown_link_ranges.push((mat.start(), mat.end()));
182 }
183 }
184
185 if has_bang && has_bracket {
187 for mat in MARKDOWN_IMAGE_REGEX.find_iter(line) {
188 buffers.image_ranges.push((mat.start(), mat.end()));
189 }
190 }
191
192 buffers.urls_found.clear();
194
195 for mat in URL_IPV6_REGEX.find_iter(line) {
197 let url_str = mat.as_str();
198 buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
199 }
200
201 for mat in URL_STANDARD_REGEX.find_iter(line) {
203 let url_str = mat.as_str();
204
205 if url_str.contains("://[") {
207 continue;
208 }
209
210 if let Some(host_start) = url_str.find("://") {
213 let after_protocol = &url_str[host_start + 3..];
214 if after_protocol.contains("::") || after_protocol.chars().filter(|&c| c == ':').count() > 1 {
216 if line.as_bytes().get(mat.end()) == Some(&b']') {
218 continue;
220 }
221 }
222 }
223
224 buffers.urls_found.push((mat.start(), mat.end(), url_str.to_string()));
225 }
226
227 for mat in URL_WWW_REGEX.find_iter(line) {
229 let url_str = mat.as_str();
230 let start_pos = mat.start();
231 let end_pos = mat.end();
232
233 if start_pos > 0 {
235 let prev_char = line.as_bytes().get(start_pos - 1).copied();
236 if prev_char == Some(b'/') || prev_char == Some(b'@') {
237 continue;
238 }
239 }
240
241 if start_pos > 0 && end_pos < line.len() {
243 let prev_char = line.as_bytes().get(start_pos - 1).copied();
244 let next_char = line.as_bytes().get(end_pos).copied();
245 if prev_char == Some(b'<') && next_char == Some(b'>') {
246 continue;
247 }
248 }
249
250 buffers.urls_found.push((start_pos, end_pos, url_str.to_string()));
251 }
252
253 for mat in XMPP_URI_REGEX.find_iter(line) {
255 let uri_str = mat.as_str();
256 let start_pos = mat.start();
257 let end_pos = mat.end();
258
259 if start_pos > 0 && end_pos < line.len() {
261 let prev_char = line.as_bytes().get(start_pos - 1).copied();
262 let next_char = line.as_bytes().get(end_pos).copied();
263 if prev_char == Some(b'<') && next_char == Some(b'>') {
264 continue;
265 }
266 }
267
268 buffers.urls_found.push((start_pos, end_pos, uri_str.to_string()));
269 }
270
271 for &(start, _end, ref url_str) in &buffers.urls_found {
273 if CUSTOM_PROTOCOL_REGEX.is_match(url_str) {
275 continue;
276 }
277
278 let is_inside_construct = buffers
284 .markdown_link_ranges
285 .iter()
286 .any(|&(s, e)| start >= s && start < e)
287 || buffers.image_ranges.iter().any(|&(s, e)| start >= s && start < e);
288
289 if is_inside_construct {
290 continue;
291 }
292
293 let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
295 let absolute_pos = line_start_byte + start;
296
297 if ctx.is_in_html_tag(absolute_pos) {
299 continue;
300 }
301
302 if ctx.is_in_jsx_component_tag(absolute_pos) {
306 continue;
307 }
308
309 if ctx.is_in_html_comment(absolute_pos) || ctx.is_in_mdx_comment(absolute_pos) {
311 continue;
312 }
313
314 if ctx.is_in_shortcode(absolute_pos) {
316 continue;
317 }
318
319 if ctx.flavor.is_pandoc_compatible()
323 && (ctx.is_in_line_block(absolute_pos) || ctx.is_in_pandoc_metadata(absolute_pos))
324 {
325 continue;
326 }
327
328 let trimmed_url = self.trim_trailing_punctuation(url_str);
330
331 if !trimmed_url.is_empty() && trimmed_url != "//" {
333 let trimmed_len = trimmed_url.len();
334 let (start_line, start_col, end_line, end_col) =
335 calculate_url_range(line_number, line, start, trimmed_len);
336
337 let replacement = if trimmed_url.starts_with("www.") {
339 format!("<https://{trimmed_url}>")
340 } else {
341 format!("<{trimmed_url}>")
342 };
343
344 warnings.push(LintWarning {
345 rule_name: Some("MD034".to_string()),
346 line: start_line,
347 column: start_col,
348 end_line,
349 end_column: end_col,
350 message: if ctx.flavor == crate::config::MarkdownFlavor::MDG {
351 format!(
352 "URL without link formatting: '{trimmed_url}' (angle brackets are Gherkin placeholder syntax; use explicit link formatting where appropriate, or disable MD034)"
353 )
354 } else {
355 format!("URL without angle brackets or link formatting: '{trimmed_url}'")
356 },
357 severity: Severity::Warning,
358 fix: Some(Fix::new(
359 {
360 let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
361 (line_start_byte + start)..(line_start_byte + start + trimmed_len)
362 },
363 replacement,
364 )),
365 });
366 }
367 }
368
369 for cap in EMAIL_PATTERN.captures_iter(line) {
371 if let Some(mat) = cap.get(0) {
372 let email = mat.as_str();
373 let start = mat.start();
374 let end = mat.end();
375
376 if start >= 5 && line.is_char_boundary(start - 5) && &line[start - 5..start] == "xmpp:" {
379 continue;
380 }
381
382 let mut is_inside_construct = false;
384 for &(link_start, link_end) in &buffers.markdown_link_ranges {
385 if start >= link_start && end <= link_end {
386 is_inside_construct = true;
387 break;
388 }
389 }
390
391 if !is_inside_construct {
392 let line_start_byte = ctx.line_start_byte(line_number).unwrap_or(0);
394 let absolute_pos = line_start_byte + start;
395
396 if ctx.is_in_html_tag(absolute_pos) {
398 continue;
399 }
400
401 if ctx.is_in_jsx_component_tag(absolute_pos) {
404 continue;
405 }
406
407 if ctx.flavor.is_pandoc_compatible()
409 && (ctx.is_in_line_block(absolute_pos) || ctx.is_in_pandoc_metadata(absolute_pos))
410 {
411 continue;
412 }
413
414 let is_in_code_span = code_spans
416 .iter()
417 .any(|span| absolute_pos >= span.byte_offset && absolute_pos < span.byte_end);
418
419 if !is_in_code_span {
420 let email_len = end - start;
421 let (start_line, start_col, end_line, end_col) =
422 calculate_url_range(line_number, line, start, email_len);
423
424 warnings.push(LintWarning {
425 rule_name: Some("MD034".to_string()),
426 line: start_line,
427 column: start_col,
428 end_line,
429 end_column: end_col,
430 message: if ctx.flavor == crate::config::MarkdownFlavor::MDG {
431 format!(
432 "Email address without link formatting: '{email}' (angle brackets are Gherkin placeholder syntax; use explicit link formatting where appropriate, or disable MD034)"
433 )
434 } else {
435 format!("Email address without angle brackets or link formatting: '{email}'")
436 },
437 severity: Severity::Warning,
438 fix: Some(Fix::new(
439 (line_start_byte + start)..(line_start_byte + end),
440 format!("<{email}>"),
441 )),
442 });
443 }
444 }
445 }
446 }
447
448 warnings
449 }
450}
451
452impl Rule for MD034NoBareUrls {
453 #[inline]
454 fn name(&self) -> &'static str {
455 "MD034"
456 }
457
458 fn as_any(&self) -> &dyn std::any::Any {
459 self
460 }
461
462 fn from_config(_config: &crate::config::Config) -> Box<dyn Rule>
463 where
464 Self: Sized,
465 {
466 Box::new(MD034NoBareUrls)
467 }
468
469 #[inline]
470 fn category(&self) -> RuleCategory {
471 RuleCategory::Link
472 }
473
474 fn skippable_by_category(&self) -> bool {
475 false
480 }
481
482 fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
483 !ctx.likely_has_links_or_images() && self.should_skip_content(ctx.content)
484 }
485
486 #[inline]
487 fn description(&self) -> &'static str {
488 "No bare URLs - wrap URLs in angle brackets"
489 }
490
491 fn check(&self, ctx: &LintContext) -> LintResult {
492 let mut warnings = Vec::new();
493 let content = ctx.content;
494
495 if self.should_skip_content(content) {
497 return Ok(warnings);
498 }
499
500 let code_spans = ctx.code_spans();
502
503 let ref_def_lines: std::collections::HashSet<usize> =
507 ctx.reference_definitions().iter().map(|def| def.line).collect();
508
509 let mut buffers = LineCheckBuffers::default();
511
512 for line in ctx
516 .filtered_lines()
517 .skip_front_matter()
518 .skip_code_blocks()
519 .skip_jsx_expressions()
520 .skip_mdx_comments()
521 .skip_obsidian_comments()
522 {
523 if ctx.is_myst_colon_directive_opener_line(line.line_num) {
529 continue;
530 }
531
532 if ref_def_lines.contains(&line.line_num) {
534 continue;
535 }
536
537 let mut line_warnings = self.check_line(line.content, ctx, line.line_num, &code_spans, &mut buffers);
538
539 line_warnings.retain(|warning| {
541 !code_spans.iter().any(|span| {
542 if let Some(fix) = &warning.fix {
543 fix.range.start >= span.byte_offset && fix.range.start < span.byte_end
545 } else {
546 span.line == warning.line
547 && span.end_line == warning.line
548 && warning.column > 0
549 && (warning.column - 1) >= span.start_col
550 && (warning.column - 1) < span.end_col
551 }
552 })
553 });
554
555 line_warnings.retain(|warning| {
556 if let Some(fix) = &warning.fix {
557 !ctx.links().iter().any(|link| {
559 !(link.is_reference && link.url.is_empty())
560 && fix.range.start >= link.byte_offset
561 && fix.range.end <= link.byte_end
562 })
563 } else {
564 true
565 }
566 });
567
568 line_warnings.retain(|warning| !ctx.is_position_in_obsidian_comment(warning.line, warning.column));
571
572 warnings.extend(line_warnings);
573 }
574
575 if ctx.flavor == crate::config::MarkdownFlavor::MDG {
579 for warning in &mut warnings {
580 warning.fix = None;
581 }
582 }
583
584 Ok(warnings)
585 }
586
587 fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
588 let mut content = ctx.content.to_string();
589 let warnings = self.check(ctx)?;
590 let mut warnings =
591 crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
592
593 warnings.sort_by_key(|w| w.fix.as_ref().map_or(0, |f| f.range.start));
595
596 for warning in warnings.iter().rev() {
598 if let Some(fix) = &warning.fix {
599 let start = fix.range.start;
600 let end = fix.range.end;
601 content.replace_range(start..end, &fix.replacement);
602 }
603 }
604
605 Ok(content)
606 }
607}
608
609#[cfg(test)]
610mod tests {
611 use super::*;
612
613 #[test]
614 fn test_shortcut_ref_at_end_of_line_no_trailing_chars() {
615 let rule = MD034NoBareUrls;
616 let content = "See [https://example.com]";
617 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
618 let result = rule.check(&ctx).unwrap();
619 assert!(
620 result.is_empty(),
621 "[URL] at end of line should be treated as shortcut ref: {result:?}"
622 );
623 }
624
625 #[test]
626 fn test_shortcut_ref_multiple_spaces_before_paren() {
627 let rule = MD034NoBareUrls;
628 let content = "[text] (https://example.com)";
629 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
630 let result = rule.check(&ctx).unwrap();
631 let _ = result; }
636
637 #[test]
638 fn test_shortcut_ref_tab_before_bracket() {
639 let rule = MD034NoBareUrls;
640 let content = "[https://example.com]\t[other]";
641 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
642 let result = rule.check(&ctx).unwrap();
643 assert_eq!(
647 result.len(),
648 1,
649 "Bare URL inside shortcut ref should be detected: {result:?}"
650 );
651 }
652
653 #[test]
654 fn test_shortcut_ref_followed_by_punctuation() {
655 let rule = MD034NoBareUrls;
656 let content = "[https://example.com], see also other things.";
657 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
658 let result = rule.check(&ctx).unwrap();
659 assert!(
660 result.is_empty(),
661 "[URL] followed by comma should be treated as shortcut ref: {result:?}"
662 );
663 }
664
665 #[test]
666 fn test_url_in_backticks_inside_mdx_component_not_flagged() {
667 let rule = MD034NoBareUrls;
671 let content = "# Test\n\nControl: `https://rumdl.example.com/` is fine here.\n\n<ParamField path=\"--stuff\">\n This URL `https://rumdl.example.com/` must not be flagged.\n</ParamField>\n";
672 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
673 let result = rule.check(&ctx).unwrap();
674 assert!(
675 result.is_empty(),
676 "URL in backticks inside MDX component must not be flagged: {result:?}"
677 );
678 }
679
680 #[test]
681 fn test_bare_url_inside_mdx_component_still_flagged() {
682 let rule = MD034NoBareUrls;
685 let content =
686 "# Test\n\n<ParamField path=\"--stuff\">\n Visit https://rumdl.example.com/ for details.\n</ParamField>\n";
687 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
688 let result = rule.check(&ctx).unwrap();
689 assert_eq!(
690 result.len(),
691 1,
692 "Bare URL in MDX component body must still be flagged: {result:?}"
693 );
694 }
695
696 #[test]
697 fn test_url_in_backticks_inside_nested_mdx_component_not_flagged() {
698 let rule = MD034NoBareUrls;
700 let content = "<Outer>\n <Inner>\n Check `https://example.com/` here.\n </Inner>\n</Outer>\n";
701 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
702 let result = rule.check(&ctx).unwrap();
703 assert!(
704 result.is_empty(),
705 "URL in backticks inside nested MDX component must not be flagged: {result:?}"
706 );
707 }
708
709 #[test]
713 fn test_url_in_fenced_code_block_inside_jsx_not_flagged() {
714 let rule = MD034NoBareUrls;
715 let content = "# Title\n\n<Steps>\n <Step title=\"Send a request\">\n```bash\ncurl https://example.com/api\n```\n </Step>\n</Steps>\n";
716 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
717 let result = rule.check(&ctx).unwrap();
718 assert!(
719 result.is_empty(),
720 "URL in a fenced code block nested in a JSX component must not be flagged: {result:?}"
721 );
722 }
723
724 #[test]
727 fn test_fix_does_not_rewrite_url_in_fenced_code_block_inside_jsx() {
728 let rule = MD034NoBareUrls;
729 let content = "# Title\n\n<Steps>\n <Step title=\"Send a request\">\n```bash\ncurl https://example.com/api\n```\n </Step>\n</Steps>\n";
730 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
731 let fixed = rule.fix(&ctx).unwrap();
732 assert_eq!(
733 fixed, content,
734 "fix must not rewrite a URL inside a JSX-nested fenced code block"
735 );
736 }
737
738 #[test]
741 fn test_bare_url_in_jsx_body_outside_fence_still_flagged() {
742 let rule = MD034NoBareUrls;
743 let content = "# Title\n\n<Steps>\n <Step title=\"Send a request\">\n Visit https://example.com/api now.\n </Step>\n</Steps>\n";
744 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
745 let result = rule.check(&ctx).unwrap();
746 assert_eq!(
747 result.len(),
748 1,
749 "A bare URL in the JSX body (not in a fence) must still be flagged: {result:?}"
750 );
751 }
752
753 #[test]
757 fn test_bare_url_not_masked_by_comment_delimiter_in_code_block() {
758 let rule = MD034NoBareUrls;
759 let content =
760 "# T\n\n```text\n<!-- literal opener, not a comment\n```\n\nhttps://example.com should be flagged\n\n-->\n";
761 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
762 let result = rule.check(&ctx).unwrap();
763 assert_eq!(result.len(), 1, "the bare URL must still be flagged: {result:?}");
764 assert!(
765 result[0].message.contains("example.com"),
766 "the flagged URL must be the bare one: {result:?}"
767 );
768 }
769
770 #[test]
775 fn test_bare_url_in_indented_comment_in_admonition_still_skipped() {
776 let rule = MD034NoBareUrls;
777 let content = "# T\n\n!!! note\n Some text.\n\n <!--\n https://example.com\n -->\n";
778 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MkDocs, None);
779 let result = rule.check(&ctx).unwrap();
780 assert!(
781 result.is_empty(),
782 "URL inside an indented HTML comment in an admonition must not be flagged: {result:?}"
783 );
784 }
785
786 #[test]
790 fn test_url_in_jsx_component_attribute_not_flagged() {
791 let rule = MD034NoBareUrls;
792 let content = "<Card title=\"Docs\" href=\"https://example.com/docs\" />\n";
793 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
794 let result = rule.check(&ctx).unwrap();
795 assert!(
796 result.is_empty(),
797 "URL in a JSX component attribute must not be flagged: {result:?}"
798 );
799 }
800
801 #[test]
803 fn test_url_in_multiline_jsx_component_attribute_not_flagged() {
804 let rule = MD034NoBareUrls;
805 let content = "<Card\n title=\"Docs\"\n href=\"https://example.com/docs\"\n/>\n";
806 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
807 let result = rule.check(&ctx).unwrap();
808 assert!(
809 result.is_empty(),
810 "URL in a multi-line JSX component attribute must not be flagged: {result:?}"
811 );
812 }
813
814 #[test]
817 fn test_jsx_attribute_url_skipped_but_body_url_flagged() {
818 let rule = MD034NoBareUrls;
819 let content = "<Card href=\"https://attr.example.com\">\n Visit https://body.example.com now.\n</Card>\n";
820 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
821 let result = rule.check(&ctx).unwrap();
822 assert_eq!(
823 result.len(),
824 1,
825 "Only the body URL must be flagged, not the attribute URL: {result:?}"
826 );
827 assert!(
828 result[0].message.contains("body.example.com"),
829 "The flagged URL must be the body one: {result:?}"
830 );
831 }
832
833 #[test]
836 fn test_email_in_jsx_component_attribute_not_flagged() {
837 let rule = MD034NoBareUrls;
838 let content = "<Contact email=\"hello@example.com\" />\n";
839 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
840 let result = rule.check(&ctx).unwrap();
841 assert!(
842 result.is_empty(),
843 "Email in a JSX component attribute must not be flagged: {result:?}"
844 );
845 }
846
847 #[test]
851 fn test_jsx_attribute_url_not_flagged_in_standard_flavor() {
852 let rule = MD034NoBareUrls;
853 let content = "<Card href=\"https://example.com/docs\" />\n";
854 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
855 let result = rule.check(&ctx).unwrap();
856 assert!(
857 result.is_empty(),
858 "URL in a tag attribute must not be flagged under Standard flavor either: {result:?}"
859 );
860 }
861
862 #[test]
864 fn test_pandoc_skips_urls_in_line_blocks() {
865 use crate::config::MarkdownFlavor;
866 use crate::lint_context::LintContext;
867 let rule = MD034NoBareUrls;
868 let content = "| See https://example.com\n| For details\n";
869 let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
870 let result = rule.check(&ctx).unwrap();
871 assert!(
872 result.is_empty(),
873 "MD034 should skip URLs in Pandoc line blocks: {result:?}"
874 );
875 }
876
877 #[test]
879 fn test_pandoc_skips_urls_in_metadata() {
880 use crate::config::MarkdownFlavor;
881 use crate::lint_context::LintContext;
882 let rule = MD034NoBareUrls;
883 let content = "---\nhomepage: https://example.com\n---\n\nBody.\n";
884 let ctx = LintContext::new(content, MarkdownFlavor::Pandoc, None);
885 let result = rule.check(&ctx).unwrap();
886 assert!(
887 result.is_empty(),
888 "MD034 should skip URLs in Pandoc YAML metadata: {result:?}"
889 );
890 }
891
892 #[test]
895 fn test_standard_still_flags_urls_in_pipe_prefixed_lines() {
896 use crate::config::MarkdownFlavor;
897 use crate::lint_context::LintContext;
898 let rule = MD034NoBareUrls;
899 let content = "| See https://example.com\n";
900 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
901 let result = rule.check(&ctx).unwrap();
902 assert!(
903 !result.is_empty(),
904 "MD034 should still flag URLs in pipe-prefixed lines under Standard flavor"
905 );
906 }
907
908 #[test]
909 fn test_url_in_backticks_after_fenced_code_block_inside_mdx_not_flagged() {
910 let rule = MD034NoBareUrls;
914 let content = "\
915<Component>
916Some intro text.
917
918```
919example code here
920```
921
922Check `https://example.com/` here.
923</Component>
924";
925 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
926 let result = rule.check(&ctx).unwrap();
927 assert!(
928 result.is_empty(),
929 "URL in backticks after a fenced code block inside MDX must not be flagged: {result:?}"
930 );
931 }
932
933 #[test]
937 fn test_myst_colon_directive_argument_url_not_flagged() {
938 use crate::config::MarkdownFlavor;
939 use crate::lint_context::LintContext;
940 let rule = MD034NoBareUrls;
941 let content = "\
942:::{anywidget} https://cdn.jsdelivr.net/npm/repo-review-webapp@1.1.3/dist/repo-review-anywidget.mjs
943{
944 \"deps\": [\"repo-review~=1.1.0\"]
945}
946:::
947";
948 let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
949 let result = rule.check(&ctx).unwrap();
950 assert!(
951 result.is_empty(),
952 "URL argument on a MyST colon directive opener must not be flagged: {result:?}"
953 );
954 }
955
956 #[test]
958 fn test_myst_nested_colon_directive_argument_url_not_flagged() {
959 use crate::config::MarkdownFlavor;
960 use crate::lint_context::LintContext;
961 let rule = MD034NoBareUrls;
962 let content = "\
963::::{grid}
964:::{card} https://example.com/card-target
965Some caption.
966:::
967::::
968";
969 let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
970 let result = rule.check(&ctx).unwrap();
971 assert!(
972 result.is_empty(),
973 "URL argument on a nested MyST colon directive opener must not be flagged: {result:?}"
974 );
975 }
976
977 #[test]
980 fn test_myst_directive_body_url_still_flagged() {
981 use crate::config::MarkdownFlavor;
982 use crate::lint_context::LintContext;
983 let rule = MD034NoBareUrls;
984 let content = "\
985:::{note}
986See https://example.com/docs for more details.
987:::
988";
989 let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
990 let result = rule.check(&ctx).unwrap();
991 assert_eq!(
992 result.len(),
993 1,
994 "Bare URL in a MyST directive body must still be flagged: {result:?}"
995 );
996 }
997
998 #[test]
1001 fn test_myst_unclosed_colon_directive_argument_url_not_flagged() {
1002 use crate::config::MarkdownFlavor;
1003 use crate::lint_context::LintContext;
1004 let rule = MD034NoBareUrls;
1005 let content = "\
1006:::{anywidget} https://example.com/widget.mjs
1007Some trailing content with no closing fence.
1008";
1009 let ctx = LintContext::new(content, MarkdownFlavor::MyST, None);
1010 let result = rule.check(&ctx).unwrap();
1011 assert!(
1012 result.is_empty(),
1013 "URL argument on an unclosed MyST colon directive opener must not be flagged: {result:?}"
1014 );
1015 }
1016
1017 #[test]
1020 fn test_colon_directive_url_flagged_in_standard_flavor() {
1021 use crate::config::MarkdownFlavor;
1022 use crate::lint_context::LintContext;
1023 let rule = MD034NoBareUrls;
1024 let content = ":::{anywidget} https://example.com/widget.mjs\n";
1025 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
1026 let result = rule.check(&ctx).unwrap();
1027 assert_eq!(
1028 result.len(),
1029 1,
1030 "Under Standard flavor a bare URL on a `:::` line must still be flagged: {result:?}"
1031 );
1032 }
1033
1034 #[test]
1035 fn test_md034_complex_link() {
1036 let rule = MD034NoBareUrls;
1037
1038 let content = "Check [link `code [with brackets]` text](http://example.com) and see http://bare.com.\n";
1041 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1042 let result = rule.check(&ctx).unwrap();
1043 assert_eq!(result.len(), 1, "Should flag exactly 1 URL (the bare one): {result:?}");
1044 assert!(result[0].message.contains("bare.com"));
1045
1046 let content2 = "Check [link `code [` text](http://example.com) and see http://bare.com.\n";
1049 let ctx2 = crate::lint_context::LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
1050 let result2 = rule.check(&ctx2).unwrap();
1051 assert_eq!(
1052 result2.len(),
1053 1,
1054 "Should flag exactly 1 URL (the bare one): {result2:?}"
1055 );
1056 assert!(result2[0].message.contains("bare.com"));
1057 }
1058
1059 #[test]
1062 fn test_mdg_reports_bare_urls_without_fixing_them() {
1063 let rule = MD034NoBareUrls;
1064 let content = "\
1065# Feature: Visit https://feature.example.com
1066
1067Prose about https://prose.example.com for background.
1068
1069## Scenario Outline: Open https://outline.example.com
1070
1071* Given I go to https://step.example.com
1072 | site |
1073 | https://datatable.example.com |
1074
1075> * Given I go to https://blockquoted.example.com
1076
10771. Given I go to https://ordered.example.com
1078
1079| url |
1080| ------------------------------ |
1081| https://unindented.example.com |
1082
1083### Examples:
1084
1085 | url |
1086 | ---------------------------- |
1087 | https://examples.example.com |
1088";
1089
1090 let standard_ctx =
1091 crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
1092 let standard_lines: Vec<usize> = rule.check(&standard_ctx).unwrap().iter().map(|w| w.line).collect();
1093 assert_eq!(
1094 standard_lines,
1095 vec![1, 3, 5, 7, 9, 11, 13, 17, 23],
1096 "Standard flavor flags every bare URL"
1097 );
1098
1099 let mdg_ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
1100 assert!(!rule.should_skip(&mdg_ctx), "MDG must still run the diagnostic");
1101 let mdg = rule.check(&mdg_ctx).unwrap();
1102 assert_eq!(mdg.iter().map(|w| w.line).collect::<Vec<_>>(), standard_lines);
1103 assert!(mdg.iter().all(|warning| warning.fix.is_none()));
1104 assert!(
1105 mdg.iter()
1106 .all(|warning| warning.message.contains("Gherkin placeholder"))
1107 );
1108 assert!(mdg.iter().all(|warning| warning.message.contains("disable MD034")));
1109 assert_eq!(rule.fix(&mdg_ctx).unwrap(), content, "MDG must rewrite nothing");
1110 }
1111
1112 #[test]
1113 fn test_mdg_reports_bare_email_without_fixing_it() {
1114 let rule = MD034NoBareUrls;
1115 let content = "# Feature: Contact\n\n* Given I email user@example.com\n";
1116 let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::MDG, None);
1117
1118 let warnings = rule.check(&ctx).unwrap();
1119 assert_eq!(warnings.len(), 1);
1120 assert!(warnings[0].message.contains("Gherkin placeholder"));
1121 assert!(warnings[0].message.contains("disable MD034"));
1122 assert!(warnings[0].fix.is_none());
1123 assert_eq!(rule.fix(&ctx).unwrap(), content);
1124 }
1125
1126 #[test]
1129 fn test_mdg_exemption_does_not_affect_other_flavors() {
1130 let rule = MD034NoBareUrls;
1131 let content = "\
1132# Feature: Visit https://feature.example.com
1133
1134Prose about https://prose.example.com for background.
1135
1136## Scenario Outline: Open https://outline.example.com
1137
1138* Given I go to https://step.example.com
1139 | site |
1140 | https://datatable.example.com |
1141
1142### Examples:
1143
1144 | url |
1145 | ---------------------------- |
1146 | https://examples.example.com |
1147";
1148 let expected = "\
1149# Feature: Visit <https://feature.example.com>
1150
1151Prose about <https://prose.example.com> for background.
1152
1153## Scenario Outline: Open <https://outline.example.com>
1154
1155* Given I go to <https://step.example.com>
1156 | site |
1157 | <https://datatable.example.com> |
1158
1159### Examples:
1160
1161 | url |
1162 | ---------------------------- |
1163 | <https://examples.example.com> |
1164";
1165
1166 for flavor in [
1167 crate::config::MarkdownFlavor::Standard,
1168 crate::config::MarkdownFlavor::MkDocs,
1169 crate::config::MarkdownFlavor::MyST,
1170 ] {
1171 let ctx = crate::lint_context::LintContext::new(content, flavor, None);
1172 assert!(!rule.should_skip(&ctx), "{flavor:?} must still run the rule");
1173 assert_eq!(rule.check(&ctx).unwrap().len(), 6, "{flavor:?} must flag all six URLs");
1174
1175 let fixed = rule.fix(&ctx).unwrap();
1176 assert_eq!(fixed, expected, "{flavor:?} must wrap all six URLs");
1177
1178 let fixed_ctx = crate::lint_context::LintContext::new(&fixed, flavor, None);
1179 assert!(rule.check(&fixed_ctx).unwrap().is_empty());
1180 assert_eq!(
1181 rule.fix(&fixed_ctx).unwrap(),
1182 fixed,
1183 "{flavor:?} fix must be idempotent"
1184 );
1185 }
1186 }
1187}