1use std::borrow::Cow;
4use std::fmt::Write as _;
5
6use crate::{
7 CodeClimateIssue, CodeClimateSeverity, DiffIndex, GitHubReviewComment, GitHubReviewSide,
8 GitLabReviewComment, GitLabReviewPosition, GitLabReviewPositionType, ReviewCheckConclusion,
9 ReviewComment, ReviewEnvelopeEvent, ReviewEnvelopeMeta, ReviewEnvelopeOutput,
10 ReviewEnvelopeSchema, ReviewEnvelopeSummary, ReviewId, ReviewProvider, default_marker_regex,
11 default_marker_regex_flags, review_id_marker,
12};
13use serde_json::Value;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum CiProvider {
18 Github,
20 Gitlab,
22}
23
24impl CiProvider {
25 #[must_use]
27 pub const fn name(self) -> &'static str {
28 match self {
29 Self::Github => "GitHub",
30 Self::Gitlab => "GitLab",
31 }
32 }
33}
34
35#[must_use]
43pub fn apply_path_prefix(prefix: &str, path: &str) -> String {
44 if prefix.is_empty() {
45 return path.to_owned();
46 }
47 format!("{prefix}/{path}")
48}
49
50#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct CiIssue {
53 pub rule_id: String,
55 pub description: String,
57 pub severity: String,
59 pub path: String,
61 pub line: u64,
63 pub fingerprint: String,
65}
66
67pub struct PrCommentRenderInput<'a> {
69 pub command: &'a str,
71 pub provider: CiProvider,
73 pub issues: &'a [CiIssue],
75 pub marker_id: String,
77 pub max_comments: usize,
79 pub category_for_rule: &'a dyn Fn(&str) -> &'static str,
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct ReviewGitlabDiffRefs {
86 pub base_sha: String,
88 pub start_sha: String,
90 pub head_sha: String,
92}
93
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub struct ReviewEnvelopeTruncation {
97 pub body: bool,
99 pub comment_limit: bool,
101}
102
103#[derive(Debug)]
105pub struct ReviewEnvelopeRenderResult {
106 pub envelope: ReviewEnvelopeOutput,
108 pub truncation: ReviewEnvelopeTruncation,
110}
111
112pub struct ReviewEnvelopeRenderInput<'a> {
114 pub command: &'a str,
116 pub provider: CiProvider,
118 pub issues: &'a [CiIssue],
120 pub diff_index: Option<&'a DiffIndex>,
122 pub path_prefix: &'a str,
124 pub max_comments: usize,
126 pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
128 pub include_guidance: bool,
130 pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
133 pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
135}
136
137pub const MARKER_PREFIX_V2: &str = "<!-- fallow-fingerprint:v2: ";
139
140pub const MARKER_SUFFIX_V2: &str = " -->";
142
143pub const MAX_COMMENT_BODY_BYTES: usize = 65_536;
146const TRUNCATION_SUFFIX: &str = "\n\n<!-- fallow-truncated -->\n> Body truncated by fallow.";
147
148#[must_use]
151pub fn issues_from_codeclimate(value: &Value) -> Vec<CiIssue> {
152 let mut issues = value
153 .as_array()
154 .into_iter()
155 .flatten()
156 .filter_map(issue_from_codeclimate)
157 .collect::<Vec<_>>();
158 sort_ci_issues(&mut issues);
159 issues
160}
161
162#[must_use]
165pub fn issues_from_codeclimate_issues(issues: &[CodeClimateIssue]) -> Vec<CiIssue> {
166 let mut issues = issues
167 .iter()
168 .map(issue_from_codeclimate_issue)
169 .collect::<Vec<_>>();
170 sort_ci_issues(&mut issues);
171 issues
172}
173
174fn issue_from_codeclimate(value: &Value) -> Option<CiIssue> {
175 let path = value.pointer("/location/path")?.as_str()?.to_string();
176 let line = value
177 .pointer("/location/lines/begin")
178 .and_then(Value::as_u64)
179 .unwrap_or(1);
180 Some(CiIssue {
181 rule_id: value
182 .get("check_name")
183 .and_then(Value::as_str)
184 .unwrap_or("fallow/finding")
185 .to_string(),
186 description: value
187 .get("description")
188 .and_then(Value::as_str)
189 .unwrap_or("Fallow finding")
190 .to_string(),
191 severity: value
192 .get("severity")
193 .and_then(Value::as_str)
194 .unwrap_or("minor")
195 .to_string(),
196 fingerprint: value
197 .get("fingerprint")
198 .and_then(Value::as_str)
199 .unwrap_or("")
200 .to_string(),
201 path,
202 line,
203 })
204}
205
206fn issue_from_codeclimate_issue(issue: &CodeClimateIssue) -> CiIssue {
207 CiIssue {
208 rule_id: issue.check_name.clone(),
209 description: issue.description.clone(),
210 severity: codeclimate_severity_label(issue.severity).to_owned(),
211 path: issue.location.path.clone(),
212 line: u64::from(issue.location.lines.begin),
213 fingerprint: issue.fingerprint.clone(),
214 }
215}
216
217const fn codeclimate_severity_label(severity: CodeClimateSeverity) -> &'static str {
218 match severity {
219 CodeClimateSeverity::Info => "info",
220 CodeClimateSeverity::Minor => "minor",
221 CodeClimateSeverity::Major => "major",
222 CodeClimateSeverity::Critical => "critical",
223 CodeClimateSeverity::Blocker => "blocker",
224 }
225}
226
227fn sort_ci_issues(issues: &mut [CiIssue]) {
228 issues
229 .sort_by(|a, b| (&a.path, a.line, &a.fingerprint).cmp(&(&b.path, b.line, &b.fingerprint)));
230}
231
232fn fingerprint_hash(parts: &[&str]) -> String {
233 crate::codeclimate_fingerprint_hash(parts)
234}
235
236#[must_use]
239#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
240pub fn render_pr_comment(input: &PrCommentRenderInput<'_>) -> String {
241 let marker = format!("<!-- fallow-id: {} -->", input.marker_id);
242 let title = command_title(input.command);
243 let count = input.issues.len();
244 let noun = if count == 1 { "finding" } else { "findings" };
245
246 let mut out = String::new();
247 out.push_str(&marker);
248 out.push('\n');
249 write!(&mut out, "### Fallow {title}\n\n").expect("write to string");
250 if count == 0 {
251 writeln!(
252 &mut out,
253 "No {provider} PR/MR findings.",
254 provider = input.provider.name()
255 )
256 .expect("write to string");
257 } else {
258 write!(&mut out, "Found **{count}** {noun}.\n\n").expect("write to string");
259 let groups = group_by_category(input.issues, input.category_for_rule);
260 if let [(_, group_issues)] = groups.as_slice() {
261 render_findings_table(&mut out, group_issues, input.max_comments, "Details");
262 } else {
263 for (category, group_issues) in &groups {
264 let summary_label = summary_label(category, group_issues.len(), input.max_comments);
265 render_findings_table(&mut out, group_issues, input.max_comments, &summary_label);
266 }
267 }
268 }
269 out.push_str("\nGenerated by fallow.");
270 out
271}
272
273pub const PROJECT_LEVEL_RULE_IDS: &[&str] = &[
276 "fallow/unused-catalog-entry",
277 "fallow/empty-catalog-group",
278 "fallow/unresolved-catalog-reference",
279 "fallow/unused-dependency-override",
280 "fallow/misconfigured-dependency-override",
281 "fallow/unused-dependency",
282 "fallow/unused-dev-dependency",
283 "fallow/unused-optional-dependency",
284 "fallow/type-only-dependency",
285 "fallow/test-only-dependency",
286 "fallow/dev-dependency-in-production",
287];
288
289#[must_use]
292pub fn is_project_level_rule(rule_id: &str) -> bool {
293 PROJECT_LEVEL_RULE_IDS.contains(&rule_id)
294}
295
296const CATEGORY_ORDER: [&str; 6] = [
297 "Dead code",
298 "Dependencies",
299 "Duplication",
300 "Health",
301 "Architecture",
302 "Suppressions",
303];
304
305fn group_by_category<'a>(
306 issues: &'a [CiIssue],
307 category_for_rule: &dyn Fn(&str) -> &'static str,
308) -> Vec<(&'static str, Vec<&'a CiIssue>)> {
309 let mut buckets: std::collections::BTreeMap<&'static str, Vec<&CiIssue>> =
310 std::collections::BTreeMap::new();
311 for issue in issues {
312 let category = category_for_rule(&issue.rule_id);
313 buckets.entry(category).or_default().push(issue);
314 }
315 let mut ordered: Vec<(&'static str, Vec<&CiIssue>)> = Vec::with_capacity(buckets.len());
316 for category in CATEGORY_ORDER {
317 if let Some(items) = buckets.remove(category) {
318 ordered.push((category, items));
319 }
320 }
321 for (category, items) in buckets {
322 ordered.push((category, items));
323 }
324 ordered
325}
326
327#[must_use]
330pub fn summary_label(category: &str, total: usize, max: usize) -> String {
331 if total > max {
332 format!("{category} ({total}, showing {max})")
333 } else {
334 format!("{category} ({total})")
335 }
336}
337
338#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
339fn render_findings_table(out: &mut String, issues: &[&CiIssue], max: usize, summary: &str) {
340 writeln!(out, "<details>\n<summary>{summary}</summary>\n").expect("write to string");
341 out.push_str("| Severity | Rule | Location | Description |\n");
342 out.push_str("| --- | --- | --- | --- |\n");
343 for issue in issues.iter().take(max) {
344 writeln!(
345 out,
346 "| {} | `{}` | `{}`:{} | {} |",
347 escape_md(&issue.severity),
348 escape_md(&issue.rule_id),
349 escape_md(&issue.path),
350 issue.line,
351 escape_md(&issue.description),
352 )
353 .expect("write to string");
354 }
355 if issues.len() > max {
356 writeln!(
357 out,
358 "\nShowing {max} of {} findings. Run fallow locally or inspect the CI output for the full report.",
359 issues.len(),
360 )
361 .expect("write to string");
362 }
363 out.push_str("\n</details>\n\n");
364}
365
366#[must_use]
369pub fn command_title(command: &str) -> &'static str {
370 match command {
371 "dead-code" | "check" => "dead-code report",
372 "dupes" => "duplication report",
373 "health" => "health report",
374 "audit" => "audit report",
375 "" | "combined" => "combined report",
376 _ => "report",
377 }
378}
379
380#[must_use]
382pub fn escape_md(value: &str) -> String {
383 let value = value.trim();
384 let mut chars = value.chars().peekable();
387 let mut out = String::with_capacity(value.len());
388 while let Some(ch) = chars.next() {
389 let ch = match ch {
390 '\r' => {
391 if chars.peek() == Some(&'\n') {
392 chars.next();
393 }
394 ' '
395 }
396 '\n' => ' ',
397 _ => ch,
398 };
399 if matches!(
400 ch,
401 '\\' | '`'
402 | '*'
403 | '_'
404 | '['
405 | ']'
406 | '('
407 | ')'
408 | '!'
409 | '<'
410 | '>'
411 | '#'
412 | '|'
413 | '~'
414 | '&'
415 ) {
416 out.push('\\');
417 }
418 out.push(ch);
419 }
420 out
421}
422
423#[must_use]
427pub fn markdown_code_span(value: &str) -> String {
428 let longest_run = value
429 .split(|c| c != '`')
430 .map(str::len)
431 .max()
432 .unwrap_or_default();
433 let fence = "`".repeat(longest_run + 1);
434 let needs_padding = value.starts_with('`')
435 || value.ends_with('`')
436 || (value.starts_with(' ') && value.ends_with(' ') && !value.chars().all(|c| c == ' '));
437 if needs_padding {
438 format!("{fence} {value} {fence}")
439 } else {
440 format!("{fence}{value}{fence}")
441 }
442}
443
444#[must_use]
448pub fn markdown_table_code_span(value: &str) -> String {
449 let collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
450 markdown_code_span(&collapsed.replace('|', "\\|"))
451}
452
453#[must_use]
456pub fn markdown_table_text(value: &str) -> String {
457 value
458 .replace("\r\n", " ")
459 .replace(['\n', '\r'], " ")
460 .replace('|', "\\|")
461}
462
463#[must_use]
465pub fn render_review_envelope(input: &ReviewEnvelopeRenderInput<'_>) -> ReviewEnvelopeRenderResult {
466 render_review_envelope_with_id(input, None)
467}
468
469#[must_use]
471pub fn render_scoped_review_envelope(
472 input: &ReviewEnvelopeRenderInput<'_>,
473 review_id: &ReviewId,
474) -> ReviewEnvelopeRenderResult {
475 render_review_envelope_with_id(input, Some(review_id))
476}
477
478fn render_review_envelope_with_id(
479 input: &ReviewEnvelopeRenderInput<'_>,
480 review_id: Option<&ReviewId>,
481) -> ReviewEnvelopeRenderResult {
482 let grouped = group_review_issues_by_path_line(input.issues, input.max_comments);
483
484 let comments: Vec<ReviewComment> = grouped
485 .groups
486 .iter()
487 .map(|group| {
488 render_review_comment_for_group_with_id(
489 &ReviewCommentRenderInput {
490 provider: input.provider,
491 group,
492 gitlab_diff_refs: input.gitlab_diff_refs,
493 diff_index: input.diff_index,
494 path_prefix: input.path_prefix,
495 include_guidance: input.include_guidance,
496 suggestion_block: input.suggestion_block,
497 guidance_block: input.guidance_block,
498 },
499 review_id,
500 )
501 })
502 .collect();
503
504 let summary_text =
505 review_summary_text(input.command, input.provider, comments.len(), input.issues);
506 let summary_fp = summary_fingerprint(&summary_text);
507 let summary_marker = review_markers(&summary_fp, review_id);
508 let body = format!("{summary_text}{summary_marker}");
509 let summary = ReviewEnvelopeSummary {
510 body: body.clone(),
511 fingerprint: summary_fp,
512 };
513
514 let truncation = ReviewEnvelopeTruncation {
515 body: comments.iter().any(review_comment_truncated),
516 comment_limit: grouped.truncated,
517 };
518
519 ReviewEnvelopeRenderResult {
520 envelope: build_review_envelope_output(
521 input.provider,
522 body,
523 summary,
524 comments,
525 input.issues,
526 ),
527 truncation,
528 }
529}
530
531fn review_summary_text(
532 command: &str,
533 provider: CiProvider,
534 comment_count: usize,
535 issues: &[CiIssue],
536) -> String {
537 let verdict = review_summary_verdict(issues);
538 format!(
539 "### Fallow {}\n\n**{}**\n\n{} inline finding{} selected for {} review.\n\n<!-- fallow-review -->",
540 command_title(command),
541 verdict,
542 comment_count,
543 if comment_count == 1 { "" } else { "s" },
544 provider.name(),
545 )
546}
547
548fn review_summary_verdict(issues: &[CiIssue]) -> &'static str {
549 match github_check_conclusion(issues) {
550 ReviewCheckConclusion::Failure => "Quality gate failed",
551 ReviewCheckConclusion::Neutral => "Review needed",
552 ReviewCheckConclusion::Success => "Quality gate passed",
553 }
554}
555
556#[derive(Debug, PartialEq, Eq)]
559pub struct GroupedReviewIssues<'a> {
560 pub groups: Vec<Vec<&'a CiIssue>>,
562 pub truncated: bool,
564}
565
566#[must_use]
569pub fn group_review_issues_by_path_line(
570 issues: &[CiIssue],
571 max_groups: usize,
572) -> GroupedReviewIssues<'_> {
573 if max_groups == 0 {
574 return GroupedReviewIssues {
575 groups: Vec::new(),
576 truncated: !issues.is_empty(),
577 };
578 }
579 let mut groups: Vec<Vec<&CiIssue>> = Vec::with_capacity(max_groups.min(issues.len()));
580 let mut current: Vec<&CiIssue> = Vec::new();
581 let mut current_key: Option<(&str, u64)> = None;
582 for issue in issues {
583 let key = (issue.path.as_str(), issue.line);
584 if Some(key) != current_key {
585 if !current.is_empty() {
586 groups.push(std::mem::take(&mut current));
587 if groups.len() == max_groups {
588 return GroupedReviewIssues {
589 groups,
590 truncated: true,
591 };
592 }
593 }
594 current_key = Some(key);
595 }
596 current.push(issue);
597 }
598 if !current.is_empty() && groups.len() < max_groups {
599 groups.push(current);
600 }
601 GroupedReviewIssues {
602 groups,
603 truncated: false,
604 }
605}
606
607fn review_comment_truncated(comment: &ReviewComment) -> bool {
608 match comment {
609 ReviewComment::GitHub(comment) => comment.truncated,
610 ReviewComment::GitLab(comment) => comment.truncated,
611 }
612}
613
614pub struct ReviewCommentRenderInput<'a, 'group> {
616 pub provider: CiProvider,
618 pub group: &'a [&'group CiIssue],
620 pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
622 pub diff_index: Option<&'a DiffIndex>,
624 pub path_prefix: &'a str,
626 pub include_guidance: bool,
628 pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
631 pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
633}
634
635#[must_use]
637pub fn render_review_comment_for_group(input: &ReviewCommentRenderInput<'_, '_>) -> ReviewComment {
638 render_review_comment_for_group_with_id(input, None)
639}
640
641fn render_review_comment_for_group_with_id(
642 input: &ReviewCommentRenderInput<'_, '_>,
643 review_id: Option<&ReviewId>,
644) -> ReviewComment {
645 assert!(
646 !input.group.is_empty(),
647 "group_review_issues_by_path_line never yields empty"
648 );
649 let representative = input.group[0];
650 let fingerprint = if input.group.len() == 1 {
651 representative.fingerprint.clone()
652 } else {
653 let constituents: Vec<&str> = input.group.iter().map(|i| i.fingerprint.as_str()).collect();
654 composite_fingerprint(&constituents)
655 };
656
657 let content = build_merged_comment_content(input);
658 let marker_line = review_markers(&fingerprint, review_id);
659 let (body, truncated) = cap_body_with_marker(&content, &marker_line);
660
661 build_review_comment(ReviewCommentInput {
662 provider: input.provider,
663 representative,
664 gitlab_diff_refs: input.gitlab_diff_refs,
665 diff_index: input.diff_index,
666 path_prefix: input.path_prefix,
667 body,
668 fingerprint,
669 truncated,
670 })
671}
672
673#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
674fn build_merged_comment_content(input: &ReviewCommentRenderInput<'_, '_>) -> String {
675 let mut content = String::new();
676 for (index, issue) in input.group.iter().enumerate() {
677 let label = review_label_from_codeclimate(&issue.severity);
678 if index > 0 {
679 content.push_str("\n\n");
680 }
681 write!(
682 content,
683 "**{}** `{}`: {}",
684 label,
685 escape_md(&issue.rule_id),
686 escape_md(&issue.description)
687 )
688 .expect("write to String is infallible");
689 if let Some(suggestion) = (input.suggestion_block)(input.provider, issue) {
690 content.push_str(&suggestion);
691 }
692 if input.include_guidance
693 && let Some(guidance) = (input.guidance_block)(issue)
694 {
695 content.push_str(&guidance);
696 }
697 }
698 content
699}
700
701struct ReviewCommentInput<'a> {
702 provider: CiProvider,
703 representative: &'a CiIssue,
704 gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
705 diff_index: Option<&'a DiffIndex>,
706 path_prefix: &'a str,
707 body: String,
708 fingerprint: String,
709 truncated: bool,
710}
711
712fn build_review_comment(input: ReviewCommentInput<'_>) -> ReviewComment {
713 let ReviewCommentInput {
714 provider,
715 representative,
716 gitlab_diff_refs,
717 diff_index,
718 path_prefix,
719 body,
720 fingerprint,
721 truncated,
722 } = input;
723 match provider {
724 CiProvider::Github => ReviewComment::GitHub(GitHubReviewComment {
725 path: apply_path_prefix(path_prefix, &representative.path),
726 line: u32::try_from(representative.line).unwrap_or(u32::MAX),
727 side: GitHubReviewSide::Right,
728 body,
729 fingerprint,
730 truncated,
731 }),
732 CiProvider::Gitlab => {
733 let old_rel = diff_index
736 .and_then(|di| di.old_path_for_root_relative(&representative.path))
737 .map_or_else(|| representative.path.clone(), Cow::into_owned);
738 let new_path = apply_path_prefix(path_prefix, &representative.path);
739 let old_path = apply_path_prefix(path_prefix, &old_rel);
740 let position = GitLabReviewPosition {
741 base_sha: gitlab_diff_refs.map(|r| r.base_sha.clone()),
742 start_sha: gitlab_diff_refs.map(|r| r.start_sha.clone()),
743 head_sha: gitlab_diff_refs.map(|r| r.head_sha.clone()),
744 position_type: GitLabReviewPositionType::Text,
745 old_path,
746 new_path,
747 new_line: u32::try_from(representative.line).unwrap_or(u32::MAX),
748 };
749 ReviewComment::GitLab(GitLabReviewComment {
750 body,
751 position,
752 fingerprint,
753 truncated,
754 })
755 }
756 }
757}
758
759#[must_use]
763pub fn cap_body_with_marker(content: &str, marker_line: &str) -> (String, bool) {
764 let intact_len = content.len() + marker_line.len();
765 if intact_len <= MAX_COMMENT_BODY_BYTES {
766 let mut out = String::with_capacity(intact_len);
767 out.push_str(content);
768 out.push_str(marker_line);
769 return (out, false);
770 }
771 let reserved = marker_line.len() + TRUNCATION_SUFFIX.len();
772 let budget = MAX_COMMENT_BODY_BYTES.saturating_sub(reserved);
773 let mut cut = budget.min(content.len());
774 while cut > 0 && !content.is_char_boundary(cut) {
775 cut -= 1;
776 }
777 let mut out = String::with_capacity(MAX_COMMENT_BODY_BYTES);
778 out.push_str(&content[..cut]);
779 out.push_str(TRUNCATION_SUFFIX);
780 out.push_str(marker_line);
781 (out, true)
782}
783
784#[must_use]
787pub const fn review_label_from_codeclimate(severity_name: &str) -> &'static str {
788 match severity_name.as_bytes() {
789 b"major" | b"critical" | b"blocker" => "error",
790 _ => "warn",
791 }
792}
793
794#[must_use]
797pub fn github_check_conclusion(issues: &[CiIssue]) -> ReviewCheckConclusion {
798 if issues
799 .iter()
800 .any(|issue| matches!(issue.severity.as_str(), "major" | "critical" | "blocker"))
801 {
802 ReviewCheckConclusion::Failure
803 } else if issues.is_empty() {
804 ReviewCheckConclusion::Success
805 } else {
806 ReviewCheckConclusion::Neutral
807 }
808}
809
810fn build_review_envelope_output(
811 provider: CiProvider,
812 body: String,
813 summary: ReviewEnvelopeSummary,
814 comments: Vec<ReviewComment>,
815 issues: &[CiIssue],
816) -> ReviewEnvelopeOutput {
817 match provider {
818 CiProvider::Github => ReviewEnvelopeOutput {
819 event: Some(ReviewEnvelopeEvent::Comment),
820 body,
821 summary,
822 comments,
823 marker_regex: default_marker_regex(),
824 marker_regex_flags: default_marker_regex_flags(),
825 meta: ReviewEnvelopeMeta {
826 schema: ReviewEnvelopeSchema::V2,
827 provider: ReviewProvider::Github,
828 check_conclusion: Some(github_check_conclusion(issues)),
829 },
830 },
831 CiProvider::Gitlab => ReviewEnvelopeOutput {
832 event: None,
833 body,
834 summary,
835 comments,
836 marker_regex: default_marker_regex(),
837 marker_regex_flags: default_marker_regex_flags(),
838 meta: ReviewEnvelopeMeta {
839 schema: ReviewEnvelopeSchema::V2,
840 provider: ReviewProvider::Gitlab,
841 check_conclusion: None,
842 },
843 },
844 }
845}
846
847fn review_markers(fingerprint: &str, review_id: Option<&ReviewId>) -> String {
848 let fingerprint = format!("\n\n{MARKER_PREFIX_V2}{fingerprint}{MARKER_SUFFIX_V2}");
849 match review_id {
850 Some(review_id) => format!("{fingerprint}\n{}", review_id_marker(review_id)),
851 None => fingerprint,
852 }
853}
854
855#[must_use]
857pub fn summary_fingerprint(body: &str) -> String {
858 fingerprint_hash(&[body])
859}
860
861#[must_use]
865pub fn composite_fingerprint(constituents: &[&str]) -> String {
866 let mut sorted: Vec<&str> = constituents.to_vec();
867 sorted.sort_unstable();
868 let joined = sorted.join(":");
869 format!("merged:{}", fingerprint_hash(&[joined.as_str()]))
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875 use crate::{CodeClimateIssueKind, CodeClimateLines, CodeClimateLocation};
876
877 fn escape_md_legacy(value: &str) -> String {
878 let collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
879 let mut out = String::with_capacity(collapsed.len());
880 for ch in collapsed.chars() {
881 if matches!(
882 ch,
883 '\\' | '`'
884 | '*'
885 | '_'
886 | '['
887 | ']'
888 | '('
889 | ')'
890 | '!'
891 | '<'
892 | '>'
893 | '#'
894 | '|'
895 | '~'
896 | '&'
897 ) {
898 out.push('\\');
899 }
900 out.push(ch);
901 }
902 out.trim().to_owned()
903 }
904
905 fn category_for_rule(rule_id: &str) -> &'static str {
906 match rule_id {
907 "fallow/code-duplication" => "Duplication",
908 "fallow/high-complexity" => "Health",
909 "fallow/unused-dependency" => "Dependencies",
910 _ => "Dead code",
911 }
912 }
913
914 #[test]
915 fn extracts_issues_from_codeclimate() {
916 let value = serde_json::json!([{
917 "check_name": "fallow/unused-export",
918 "description": "Export x is never imported",
919 "severity": "minor",
920 "fingerprint": "abc",
921 "location": { "path": "src/a.ts", "lines": { "begin": 7 } }
922 }]);
923 let issues = issues_from_codeclimate(&value);
924 assert_eq!(issues.len(), 1);
925 assert_eq!(issues[0].path, "src/a.ts");
926 assert_eq!(issues[0].line, 7);
927 }
928
929 #[test]
930 fn typed_codeclimate_issues_extract_like_json_codeclimate() {
931 let severities = [
932 (CodeClimateSeverity::Info, "info"),
933 (CodeClimateSeverity::Minor, "minor"),
934 (CodeClimateSeverity::Major, "major"),
935 (CodeClimateSeverity::Critical, "critical"),
936 (CodeClimateSeverity::Blocker, "blocker"),
937 ];
938 let typed = severities
939 .iter()
940 .enumerate()
941 .map(|(index, (severity, _))| CodeClimateIssue {
942 kind: CodeClimateIssueKind::Issue,
943 check_name: format!("fallow/rule-{index}"),
944 description: format!("Finding {index}"),
945 categories: vec!["Complexity".to_owned()],
946 severity: *severity,
947 fingerprint: format!("fp-{index}"),
948 location: CodeClimateLocation {
949 path: format!("src/{index}.ts"),
950 lines: CodeClimateLines {
951 begin: u32::try_from(index + 1).expect("small fixture index"),
952 },
953 },
954 owner: None,
955 group: None,
956 })
957 .collect::<Vec<_>>();
958 let value = serde_json::to_value(&typed).expect("typed fixture serializes");
959
960 assert_eq!(
961 issues_from_codeclimate_issues(&typed),
962 issues_from_codeclimate(&value)
963 );
964 let typed_labels = issues_from_codeclimate_issues(&typed)
965 .into_iter()
966 .map(|issue| issue.severity)
967 .collect::<Vec<_>>();
968 let expected_labels = severities
969 .iter()
970 .map(|(_, label)| (*label).to_owned())
971 .collect::<Vec<_>>();
972 assert_eq!(typed_labels, expected_labels);
973 }
974
975 #[test]
976 fn renders_default_empty_comment() {
977 let body = render_pr_comment(&PrCommentRenderInput {
978 command: "check",
979 provider: CiProvider::Github,
980 issues: &[],
981 marker_id: "fallow-results".to_owned(),
982 max_comments: 50,
983 category_for_rule: &category_for_rule,
984 });
985 assert!(body.contains("<!-- fallow-id: fallow-results"));
986 assert!(body.contains("No GitHub PR/MR findings."));
987 }
988
989 #[test]
990 fn escape_md_escapes_inline_commonmark_specials() {
991 let raw = "foo*bar_baz [a](u) `c` <h> #x !i ~s | p";
992 let escaped = escape_md(raw);
993 for ch in [
994 '*', '_', '[', ']', '(', ')', '`', '<', '>', '#', '!', '~', '|',
995 ] {
996 let raw_count = raw.chars().filter(|c| c == &ch).count();
997 let escaped_count = escaped.matches(&format!("\\{ch}")).count();
998 assert_eq!(
999 raw_count, escaped_count,
1000 "char {ch:?}: raw {raw_count} occurrences, escaped {escaped_count} in {escaped:?}"
1001 );
1002 }
1003 }
1004
1005 #[test]
1006 fn escape_md_escapes_ampersand_to_block_numeric_entity_bypass() {
1007 let raw = "value *suspicious* here";
1008 let escaped = escape_md(raw);
1009 assert!(escaped.contains(r"\&"), "got: {escaped}");
1010 assert!(escaped.contains(r"\#"), "got: {escaped}");
1011 assert!(!escaped.contains(" *suspicious"), "got: {escaped}");
1012 }
1013
1014 #[test]
1015 fn summary_label_foreshadows_truncation() {
1016 assert_eq!(
1017 summary_label("Duplication", 160, 50),
1018 "Duplication (160, showing 50)"
1019 );
1020 assert_eq!(summary_label("Health", 12, 50), "Health (12)");
1021 assert_eq!(summary_label("Dependencies", 50, 50), "Dependencies (50)");
1022 }
1023
1024 #[test]
1025 fn escape_md_does_not_escape_block_only_markers() {
1026 let raw = "fallow/test-only-dependency package.json:12";
1027 let escaped = escape_md(raw);
1028 assert!(!escaped.contains("\\-"), "should not escape `-`");
1029 assert!(!escaped.contains("\\."), "should not escape `.`");
1030 assert_eq!(escaped, raw);
1031 }
1032
1033 #[test]
1034 fn escape_md_collapses_newlines_to_spaces() {
1035 let raw = "first\nsecond\nthird";
1036 assert_eq!(escape_md(raw), "first second third");
1037 }
1038
1039 #[test]
1040 fn escape_md_collapses_carriage_returns_to_spaces() {
1041 assert_eq!(escape_md("first\r\nsecond\rthird"), "first second third");
1042 }
1043
1044 #[test]
1045 fn escape_md_matches_legacy_contract_corpus() {
1046 const ALPHABET: [char; 12] = [
1047 'a', ' ', '\t', '\r', '\n', '\\', '|', '`', '&', '\u{2003}', 'é', '🦀',
1048 ];
1049
1050 for length in 0..=4 {
1051 let case_count = ALPHABET.len().pow(length);
1052 for mut encoded in 0..case_count {
1053 let mut value = String::new();
1054 for _ in 0..length {
1055 value.push(ALPHABET[encoded % ALPHABET.len()]);
1056 encoded /= ALPHABET.len();
1057 }
1058 assert_eq!(
1059 escape_md(&value),
1060 escape_md_legacy(&value),
1061 "contract mismatch for {value:?}"
1062 );
1063 }
1064 }
1065 }
1066
1067 #[test]
1068 fn markdown_code_span_grows_fence_past_inner_backticks() {
1069 assert_eq!(markdown_code_span("plain"), "`plain`");
1070 assert_eq!(markdown_code_span("has`tick"), "``has`tick``");
1071 assert_eq!(markdown_code_span("`leading"), "`` `leading ``");
1072 }
1073
1074 #[test]
1075 fn markdown_table_code_span_escapes_pipes() {
1076 assert_eq!(markdown_table_code_span("a|b"), "`a\\|b`");
1077 assert_eq!(markdown_table_code_span("x`|y"), "``x`\\|y``");
1078 }
1079
1080 #[test]
1081 fn markdown_table_code_span_collapses_line_endings() {
1082 assert_eq!(markdown_table_code_span("a\r\nb\rc\nd"), "`a b c d`");
1083 }
1084
1085 #[test]
1086 fn markdown_table_text_neutralizes_pipes_and_line_endings() {
1087 assert_eq!(markdown_table_text("a|b"), "a\\|b");
1088 assert_eq!(markdown_table_text("a\r\nb\rc\nd"), "a b c d");
1089 }
1090
1091 #[test]
1092 fn escape_md_leaves_safe_chars_unchanged() {
1093 let raw = "Export 'helperFn' is never imported by other modules";
1094 assert_eq!(
1095 escape_md(raw),
1096 r"Export 'helperFn' is never imported by other modules"
1097 );
1098 }
1099
1100 #[test]
1101 fn is_project_level_rule_covers_config_anchored_dependency_findings() {
1102 for rule_id in PROJECT_LEVEL_RULE_IDS {
1103 assert!(
1104 is_project_level_rule(rule_id),
1105 "{rule_id} must be project-level"
1106 );
1107 }
1108 for rule_id in [
1109 "fallow/unused-file",
1110 "fallow/unused-export",
1111 "fallow/unused-type",
1112 "fallow/unused-enum-member",
1113 "fallow/unused-class-member",
1114 "fallow/unused-store-member",
1115 "fallow/unresolved-import",
1116 "fallow/unlisted-dependency",
1117 "fallow/duplicate-export",
1118 "fallow/circular-dependency",
1119 "fallow/re-export-cycle",
1120 "fallow/boundary-violation",
1121 "fallow/stale-suppression",
1122 "fallow/private-type-leak",
1123 "fallow/high-complexity",
1124 "fallow/high-crap-score",
1125 ] {
1126 assert!(
1127 !is_project_level_rule(rule_id),
1128 "{rule_id} must NOT be project-level"
1129 );
1130 }
1131 }
1132
1133 #[test]
1134 fn escape_md_double_apply_is_safe() {
1135 let raw = "code with `backticks` and *stars*";
1136 let once = escape_md(raw);
1137 let twice = escape_md(&once);
1138 assert!(twice.contains(r"\\"));
1139 }
1140}