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 collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
386 let mut out = String::with_capacity(collapsed.len());
387 for ch in collapsed.chars() {
388 if matches!(
389 ch,
390 '\\' | '`'
391 | '*'
392 | '_'
393 | '['
394 | ']'
395 | '('
396 | ')'
397 | '!'
398 | '<'
399 | '>'
400 | '#'
401 | '|'
402 | '~'
403 | '&'
404 ) {
405 out.push('\\');
406 }
407 out.push(ch);
408 }
409 out.trim().to_owned()
410}
411
412#[must_use]
416pub fn markdown_code_span(value: &str) -> String {
417 let longest_run = value
418 .split(|c| c != '`')
419 .map(str::len)
420 .max()
421 .unwrap_or_default();
422 let fence = "`".repeat(longest_run + 1);
423 let needs_padding = value.starts_with('`')
424 || value.ends_with('`')
425 || (value.starts_with(' ') && value.ends_with(' ') && !value.chars().all(|c| c == ' '));
426 if needs_padding {
427 format!("{fence} {value} {fence}")
428 } else {
429 format!("{fence}{value}{fence}")
430 }
431}
432
433#[must_use]
437pub fn markdown_table_code_span(value: &str) -> String {
438 let collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
439 markdown_code_span(&collapsed.replace('|', "\\|"))
440}
441
442#[must_use]
445pub fn markdown_table_text(value: &str) -> String {
446 value
447 .replace("\r\n", " ")
448 .replace(['\n', '\r'], " ")
449 .replace('|', "\\|")
450}
451
452#[must_use]
454pub fn render_review_envelope(input: &ReviewEnvelopeRenderInput<'_>) -> ReviewEnvelopeRenderResult {
455 render_review_envelope_with_id(input, None)
456}
457
458#[must_use]
460pub fn render_scoped_review_envelope(
461 input: &ReviewEnvelopeRenderInput<'_>,
462 review_id: &ReviewId,
463) -> ReviewEnvelopeRenderResult {
464 render_review_envelope_with_id(input, Some(review_id))
465}
466
467fn render_review_envelope_with_id(
468 input: &ReviewEnvelopeRenderInput<'_>,
469 review_id: Option<&ReviewId>,
470) -> ReviewEnvelopeRenderResult {
471 let grouped = group_review_issues_by_path_line(input.issues, input.max_comments);
472
473 let comments: Vec<ReviewComment> = grouped
474 .groups
475 .iter()
476 .map(|group| {
477 render_review_comment_for_group_with_id(
478 &ReviewCommentRenderInput {
479 provider: input.provider,
480 group,
481 gitlab_diff_refs: input.gitlab_diff_refs,
482 diff_index: input.diff_index,
483 path_prefix: input.path_prefix,
484 include_guidance: input.include_guidance,
485 suggestion_block: input.suggestion_block,
486 guidance_block: input.guidance_block,
487 },
488 review_id,
489 )
490 })
491 .collect();
492
493 let summary_text =
494 review_summary_text(input.command, input.provider, comments.len(), input.issues);
495 let summary_fp = summary_fingerprint(&summary_text);
496 let summary_marker = review_markers(&summary_fp, review_id);
497 let body = format!("{summary_text}{summary_marker}");
498 let summary = ReviewEnvelopeSummary {
499 body: body.clone(),
500 fingerprint: summary_fp,
501 };
502
503 let truncation = ReviewEnvelopeTruncation {
504 body: comments.iter().any(review_comment_truncated),
505 comment_limit: grouped.truncated,
506 };
507
508 ReviewEnvelopeRenderResult {
509 envelope: build_review_envelope_output(
510 input.provider,
511 body,
512 summary,
513 comments,
514 input.issues,
515 ),
516 truncation,
517 }
518}
519
520fn review_summary_text(
521 command: &str,
522 provider: CiProvider,
523 comment_count: usize,
524 issues: &[CiIssue],
525) -> String {
526 let verdict = review_summary_verdict(issues);
527 format!(
528 "### Fallow {}\n\n**{}**\n\n{} inline finding{} selected for {} review.\n\n<!-- fallow-review -->",
529 command_title(command),
530 verdict,
531 comment_count,
532 if comment_count == 1 { "" } else { "s" },
533 provider.name(),
534 )
535}
536
537fn review_summary_verdict(issues: &[CiIssue]) -> &'static str {
538 match github_check_conclusion(issues) {
539 ReviewCheckConclusion::Failure => "Quality gate failed",
540 ReviewCheckConclusion::Neutral => "Review needed",
541 ReviewCheckConclusion::Success => "Quality gate passed",
542 }
543}
544
545#[derive(Debug, PartialEq, Eq)]
548pub struct GroupedReviewIssues<'a> {
549 pub groups: Vec<Vec<&'a CiIssue>>,
551 pub truncated: bool,
553}
554
555#[must_use]
558pub fn group_review_issues_by_path_line(
559 issues: &[CiIssue],
560 max_groups: usize,
561) -> GroupedReviewIssues<'_> {
562 if max_groups == 0 {
563 return GroupedReviewIssues {
564 groups: Vec::new(),
565 truncated: !issues.is_empty(),
566 };
567 }
568 let mut groups: Vec<Vec<&CiIssue>> = Vec::with_capacity(max_groups.min(issues.len()));
569 let mut current: Vec<&CiIssue> = Vec::new();
570 let mut current_key: Option<(&str, u64)> = None;
571 for issue in issues {
572 let key = (issue.path.as_str(), issue.line);
573 if Some(key) != current_key {
574 if !current.is_empty() {
575 groups.push(std::mem::take(&mut current));
576 if groups.len() == max_groups {
577 return GroupedReviewIssues {
578 groups,
579 truncated: true,
580 };
581 }
582 }
583 current_key = Some(key);
584 }
585 current.push(issue);
586 }
587 if !current.is_empty() && groups.len() < max_groups {
588 groups.push(current);
589 }
590 GroupedReviewIssues {
591 groups,
592 truncated: false,
593 }
594}
595
596fn review_comment_truncated(comment: &ReviewComment) -> bool {
597 match comment {
598 ReviewComment::GitHub(comment) => comment.truncated,
599 ReviewComment::GitLab(comment) => comment.truncated,
600 }
601}
602
603pub struct ReviewCommentRenderInput<'a, 'group> {
605 pub provider: CiProvider,
607 pub group: &'a [&'group CiIssue],
609 pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
611 pub diff_index: Option<&'a DiffIndex>,
613 pub path_prefix: &'a str,
615 pub include_guidance: bool,
617 pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
620 pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
622}
623
624#[must_use]
626pub fn render_review_comment_for_group(input: &ReviewCommentRenderInput<'_, '_>) -> ReviewComment {
627 render_review_comment_for_group_with_id(input, None)
628}
629
630fn render_review_comment_for_group_with_id(
631 input: &ReviewCommentRenderInput<'_, '_>,
632 review_id: Option<&ReviewId>,
633) -> ReviewComment {
634 assert!(
635 !input.group.is_empty(),
636 "group_review_issues_by_path_line never yields empty"
637 );
638 let representative = input.group[0];
639 let fingerprint = if input.group.len() == 1 {
640 representative.fingerprint.clone()
641 } else {
642 let constituents: Vec<&str> = input.group.iter().map(|i| i.fingerprint.as_str()).collect();
643 composite_fingerprint(&constituents)
644 };
645
646 let content = build_merged_comment_content(input);
647 let marker_line = review_markers(&fingerprint, review_id);
648 let (body, truncated) = cap_body_with_marker(&content, &marker_line);
649
650 build_review_comment(ReviewCommentInput {
651 provider: input.provider,
652 representative,
653 gitlab_diff_refs: input.gitlab_diff_refs,
654 diff_index: input.diff_index,
655 path_prefix: input.path_prefix,
656 body,
657 fingerprint,
658 truncated,
659 })
660}
661
662#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
663fn build_merged_comment_content(input: &ReviewCommentRenderInput<'_, '_>) -> String {
664 let mut content = String::new();
665 for (index, issue) in input.group.iter().enumerate() {
666 let label = review_label_from_codeclimate(&issue.severity);
667 if index > 0 {
668 content.push_str("\n\n");
669 }
670 write!(
671 content,
672 "**{}** `{}`: {}",
673 label,
674 escape_md(&issue.rule_id),
675 escape_md(&issue.description)
676 )
677 .expect("write to String is infallible");
678 if let Some(suggestion) = (input.suggestion_block)(input.provider, issue) {
679 content.push_str(&suggestion);
680 }
681 if input.include_guidance
682 && let Some(guidance) = (input.guidance_block)(issue)
683 {
684 content.push_str(&guidance);
685 }
686 }
687 content
688}
689
690struct ReviewCommentInput<'a> {
691 provider: CiProvider,
692 representative: &'a CiIssue,
693 gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
694 diff_index: Option<&'a DiffIndex>,
695 path_prefix: &'a str,
696 body: String,
697 fingerprint: String,
698 truncated: bool,
699}
700
701fn build_review_comment(input: ReviewCommentInput<'_>) -> ReviewComment {
702 let ReviewCommentInput {
703 provider,
704 representative,
705 gitlab_diff_refs,
706 diff_index,
707 path_prefix,
708 body,
709 fingerprint,
710 truncated,
711 } = input;
712 match provider {
713 CiProvider::Github => ReviewComment::GitHub(GitHubReviewComment {
714 path: apply_path_prefix(path_prefix, &representative.path),
715 line: u32::try_from(representative.line).unwrap_or(u32::MAX),
716 side: GitHubReviewSide::Right,
717 body,
718 fingerprint,
719 truncated,
720 }),
721 CiProvider::Gitlab => {
722 let old_rel = diff_index
725 .and_then(|di| di.old_path_for_root_relative(&representative.path))
726 .map_or_else(|| representative.path.clone(), Cow::into_owned);
727 let new_path = apply_path_prefix(path_prefix, &representative.path);
728 let old_path = apply_path_prefix(path_prefix, &old_rel);
729 let position = GitLabReviewPosition {
730 base_sha: gitlab_diff_refs.map(|r| r.base_sha.clone()),
731 start_sha: gitlab_diff_refs.map(|r| r.start_sha.clone()),
732 head_sha: gitlab_diff_refs.map(|r| r.head_sha.clone()),
733 position_type: GitLabReviewPositionType::Text,
734 old_path,
735 new_path,
736 new_line: u32::try_from(representative.line).unwrap_or(u32::MAX),
737 };
738 ReviewComment::GitLab(GitLabReviewComment {
739 body,
740 position,
741 fingerprint,
742 truncated,
743 })
744 }
745 }
746}
747
748#[must_use]
752pub fn cap_body_with_marker(content: &str, marker_line: &str) -> (String, bool) {
753 let intact_len = content.len() + marker_line.len();
754 if intact_len <= MAX_COMMENT_BODY_BYTES {
755 let mut out = String::with_capacity(intact_len);
756 out.push_str(content);
757 out.push_str(marker_line);
758 return (out, false);
759 }
760 let reserved = marker_line.len() + TRUNCATION_SUFFIX.len();
761 let budget = MAX_COMMENT_BODY_BYTES.saturating_sub(reserved);
762 let mut cut = budget.min(content.len());
763 while cut > 0 && !content.is_char_boundary(cut) {
764 cut -= 1;
765 }
766 let mut out = String::with_capacity(MAX_COMMENT_BODY_BYTES);
767 out.push_str(&content[..cut]);
768 out.push_str(TRUNCATION_SUFFIX);
769 out.push_str(marker_line);
770 (out, true)
771}
772
773#[must_use]
776pub const fn review_label_from_codeclimate(severity_name: &str) -> &'static str {
777 match severity_name.as_bytes() {
778 b"major" | b"critical" | b"blocker" => "error",
779 _ => "warn",
780 }
781}
782
783#[must_use]
786pub fn github_check_conclusion(issues: &[CiIssue]) -> ReviewCheckConclusion {
787 if issues
788 .iter()
789 .any(|issue| matches!(issue.severity.as_str(), "major" | "critical" | "blocker"))
790 {
791 ReviewCheckConclusion::Failure
792 } else if issues.is_empty() {
793 ReviewCheckConclusion::Success
794 } else {
795 ReviewCheckConclusion::Neutral
796 }
797}
798
799fn build_review_envelope_output(
800 provider: CiProvider,
801 body: String,
802 summary: ReviewEnvelopeSummary,
803 comments: Vec<ReviewComment>,
804 issues: &[CiIssue],
805) -> ReviewEnvelopeOutput {
806 match provider {
807 CiProvider::Github => ReviewEnvelopeOutput {
808 event: Some(ReviewEnvelopeEvent::Comment),
809 body,
810 summary,
811 comments,
812 marker_regex: default_marker_regex(),
813 marker_regex_flags: default_marker_regex_flags(),
814 meta: ReviewEnvelopeMeta {
815 schema: ReviewEnvelopeSchema::V2,
816 provider: ReviewProvider::Github,
817 check_conclusion: Some(github_check_conclusion(issues)),
818 },
819 },
820 CiProvider::Gitlab => ReviewEnvelopeOutput {
821 event: None,
822 body,
823 summary,
824 comments,
825 marker_regex: default_marker_regex(),
826 marker_regex_flags: default_marker_regex_flags(),
827 meta: ReviewEnvelopeMeta {
828 schema: ReviewEnvelopeSchema::V2,
829 provider: ReviewProvider::Gitlab,
830 check_conclusion: None,
831 },
832 },
833 }
834}
835
836fn review_markers(fingerprint: &str, review_id: Option<&ReviewId>) -> String {
837 let fingerprint = format!("\n\n{MARKER_PREFIX_V2}{fingerprint}{MARKER_SUFFIX_V2}");
838 match review_id {
839 Some(review_id) => format!("{fingerprint}\n{}", review_id_marker(review_id)),
840 None => fingerprint,
841 }
842}
843
844#[must_use]
846pub fn summary_fingerprint(body: &str) -> String {
847 fingerprint_hash(&[body])
848}
849
850#[must_use]
854pub fn composite_fingerprint(constituents: &[&str]) -> String {
855 let mut sorted: Vec<&str> = constituents.to_vec();
856 sorted.sort_unstable();
857 let joined = sorted.join(":");
858 format!("merged:{}", fingerprint_hash(&[joined.as_str()]))
859}
860
861#[cfg(test)]
862mod tests {
863 use super::*;
864 use crate::{CodeClimateIssueKind, CodeClimateLines, CodeClimateLocation};
865
866 fn category_for_rule(rule_id: &str) -> &'static str {
867 match rule_id {
868 "fallow/code-duplication" => "Duplication",
869 "fallow/high-complexity" => "Health",
870 "fallow/unused-dependency" => "Dependencies",
871 _ => "Dead code",
872 }
873 }
874
875 #[test]
876 fn extracts_issues_from_codeclimate() {
877 let value = serde_json::json!([{
878 "check_name": "fallow/unused-export",
879 "description": "Export x is never imported",
880 "severity": "minor",
881 "fingerprint": "abc",
882 "location": { "path": "src/a.ts", "lines": { "begin": 7 } }
883 }]);
884 let issues = issues_from_codeclimate(&value);
885 assert_eq!(issues.len(), 1);
886 assert_eq!(issues[0].path, "src/a.ts");
887 assert_eq!(issues[0].line, 7);
888 }
889
890 #[test]
891 fn typed_codeclimate_issues_extract_like_json_codeclimate() {
892 let severities = [
893 (CodeClimateSeverity::Info, "info"),
894 (CodeClimateSeverity::Minor, "minor"),
895 (CodeClimateSeverity::Major, "major"),
896 (CodeClimateSeverity::Critical, "critical"),
897 (CodeClimateSeverity::Blocker, "blocker"),
898 ];
899 let typed = severities
900 .iter()
901 .enumerate()
902 .map(|(index, (severity, _))| CodeClimateIssue {
903 kind: CodeClimateIssueKind::Issue,
904 check_name: format!("fallow/rule-{index}"),
905 description: format!("Finding {index}"),
906 categories: vec!["Complexity".to_owned()],
907 severity: *severity,
908 fingerprint: format!("fp-{index}"),
909 location: CodeClimateLocation {
910 path: format!("src/{index}.ts"),
911 lines: CodeClimateLines {
912 begin: u32::try_from(index + 1).expect("small fixture index"),
913 },
914 },
915 owner: None,
916 group: None,
917 })
918 .collect::<Vec<_>>();
919 let value = serde_json::to_value(&typed).expect("typed fixture serializes");
920
921 assert_eq!(
922 issues_from_codeclimate_issues(&typed),
923 issues_from_codeclimate(&value)
924 );
925 let typed_labels = issues_from_codeclimate_issues(&typed)
926 .into_iter()
927 .map(|issue| issue.severity)
928 .collect::<Vec<_>>();
929 let expected_labels = severities
930 .iter()
931 .map(|(_, label)| (*label).to_owned())
932 .collect::<Vec<_>>();
933 assert_eq!(typed_labels, expected_labels);
934 }
935
936 #[test]
937 fn renders_default_empty_comment() {
938 let body = render_pr_comment(&PrCommentRenderInput {
939 command: "check",
940 provider: CiProvider::Github,
941 issues: &[],
942 marker_id: "fallow-results".to_owned(),
943 max_comments: 50,
944 category_for_rule: &category_for_rule,
945 });
946 assert!(body.contains("<!-- fallow-id: fallow-results"));
947 assert!(body.contains("No GitHub PR/MR findings."));
948 }
949
950 #[test]
951 fn escape_md_escapes_inline_commonmark_specials() {
952 let raw = "foo*bar_baz [a](u) `c` <h> #x !i ~s | p";
953 let escaped = escape_md(raw);
954 for ch in [
955 '*', '_', '[', ']', '(', ')', '`', '<', '>', '#', '!', '~', '|',
956 ] {
957 let raw_count = raw.chars().filter(|c| c == &ch).count();
958 let escaped_count = escaped.matches(&format!("\\{ch}")).count();
959 assert_eq!(
960 raw_count, escaped_count,
961 "char {ch:?}: raw {raw_count} occurrences, escaped {escaped_count} in {escaped:?}"
962 );
963 }
964 }
965
966 #[test]
967 fn escape_md_escapes_ampersand_to_block_numeric_entity_bypass() {
968 let raw = "value *suspicious* here";
969 let escaped = escape_md(raw);
970 assert!(escaped.contains(r"\&"), "got: {escaped}");
971 assert!(escaped.contains(r"\#"), "got: {escaped}");
972 assert!(!escaped.contains(" *suspicious"), "got: {escaped}");
973 }
974
975 #[test]
976 fn summary_label_foreshadows_truncation() {
977 assert_eq!(
978 summary_label("Duplication", 160, 50),
979 "Duplication (160, showing 50)"
980 );
981 assert_eq!(summary_label("Health", 12, 50), "Health (12)");
982 assert_eq!(summary_label("Dependencies", 50, 50), "Dependencies (50)");
983 }
984
985 #[test]
986 fn escape_md_does_not_escape_block_only_markers() {
987 let raw = "fallow/test-only-dependency package.json:12";
988 let escaped = escape_md(raw);
989 assert!(!escaped.contains("\\-"), "should not escape `-`");
990 assert!(!escaped.contains("\\."), "should not escape `.`");
991 assert_eq!(escaped, raw);
992 }
993
994 #[test]
995 fn escape_md_collapses_newlines_to_spaces() {
996 let raw = "first\nsecond\nthird";
997 assert_eq!(escape_md(raw), "first second third");
998 }
999
1000 #[test]
1001 fn escape_md_collapses_carriage_returns_to_spaces() {
1002 assert_eq!(escape_md("first\r\nsecond\rthird"), "first second third");
1003 }
1004
1005 #[test]
1006 fn markdown_code_span_grows_fence_past_inner_backticks() {
1007 assert_eq!(markdown_code_span("plain"), "`plain`");
1008 assert_eq!(markdown_code_span("has`tick"), "``has`tick``");
1009 assert_eq!(markdown_code_span("`leading"), "`` `leading ``");
1010 }
1011
1012 #[test]
1013 fn markdown_table_code_span_escapes_pipes() {
1014 assert_eq!(markdown_table_code_span("a|b"), "`a\\|b`");
1015 assert_eq!(markdown_table_code_span("x`|y"), "``x`\\|y``");
1016 }
1017
1018 #[test]
1019 fn markdown_table_code_span_collapses_line_endings() {
1020 assert_eq!(markdown_table_code_span("a\r\nb\rc\nd"), "`a b c d`");
1021 }
1022
1023 #[test]
1024 fn markdown_table_text_neutralizes_pipes_and_line_endings() {
1025 assert_eq!(markdown_table_text("a|b"), "a\\|b");
1026 assert_eq!(markdown_table_text("a\r\nb\rc\nd"), "a b c d");
1027 }
1028
1029 #[test]
1030 fn escape_md_leaves_safe_chars_unchanged() {
1031 let raw = "Export 'helperFn' is never imported by other modules";
1032 assert_eq!(
1033 escape_md(raw),
1034 r"Export 'helperFn' is never imported by other modules"
1035 );
1036 }
1037
1038 #[test]
1039 fn is_project_level_rule_covers_config_anchored_dependency_findings() {
1040 for rule_id in PROJECT_LEVEL_RULE_IDS {
1041 assert!(
1042 is_project_level_rule(rule_id),
1043 "{rule_id} must be project-level"
1044 );
1045 }
1046 for rule_id in [
1047 "fallow/unused-file",
1048 "fallow/unused-export",
1049 "fallow/unused-type",
1050 "fallow/unused-enum-member",
1051 "fallow/unused-class-member",
1052 "fallow/unused-store-member",
1053 "fallow/unresolved-import",
1054 "fallow/unlisted-dependency",
1055 "fallow/duplicate-export",
1056 "fallow/circular-dependency",
1057 "fallow/re-export-cycle",
1058 "fallow/boundary-violation",
1059 "fallow/stale-suppression",
1060 "fallow/private-type-leak",
1061 "fallow/high-complexity",
1062 "fallow/high-crap-score",
1063 ] {
1064 assert!(
1065 !is_project_level_rule(rule_id),
1066 "{rule_id} must NOT be project-level"
1067 );
1068 }
1069 }
1070
1071 #[test]
1072 fn escape_md_double_apply_is_safe() {
1073 let raw = "code with `backticks` and *stars*";
1074 let once = escape_md(raw);
1075 let twice = escape_md(&once);
1076 assert!(twice.contains(r"\\"));
1077 }
1078}