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, ReviewProvider, default_marker_regex,
11 default_marker_regex_flags,
12};
13use serde_json::Value;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum CiProvider {
18 Github,
19 Gitlab,
20}
21
22impl CiProvider {
23 #[must_use]
24 pub const fn name(self) -> &'static str {
25 match self {
26 Self::Github => "GitHub",
27 Self::Gitlab => "GitLab",
28 }
29 }
30}
31
32#[must_use]
40pub fn apply_path_prefix(prefix: &str, path: &str) -> String {
41 if prefix.is_empty() {
42 return path.to_owned();
43 }
44 format!("{prefix}/{path}")
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct CiIssue {
50 pub rule_id: String,
51 pub description: String,
52 pub severity: String,
53 pub path: String,
54 pub line: u64,
55 pub fingerprint: String,
56}
57
58pub struct PrCommentRenderInput<'a> {
60 pub command: &'a str,
61 pub provider: CiProvider,
62 pub issues: &'a [CiIssue],
63 pub marker_id: String,
64 pub max_comments: usize,
65 pub category_for_rule: &'a dyn Fn(&str) -> &'static str,
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct ReviewGitlabDiffRefs {
71 pub base_sha: String,
72 pub start_sha: String,
73 pub head_sha: String,
74}
75
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub struct ReviewEnvelopeTruncation {
79 pub body: bool,
80 pub comment_limit: bool,
81}
82
83#[derive(Debug)]
85pub struct ReviewEnvelopeRenderResult {
86 pub envelope: ReviewEnvelopeOutput,
87 pub truncation: ReviewEnvelopeTruncation,
88}
89
90pub struct ReviewEnvelopeRenderInput<'a> {
92 pub command: &'a str,
93 pub provider: CiProvider,
94 pub issues: &'a [CiIssue],
95 pub diff_index: Option<&'a DiffIndex>,
96 pub path_prefix: &'a str,
98 pub max_comments: usize,
99 pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
100 pub include_guidance: bool,
101 pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
102 pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
103}
104
105pub const MARKER_PREFIX_V2: &str = "<!-- fallow-fingerprint:v2: ";
107
108pub const MARKER_SUFFIX_V2: &str = " -->";
110
111pub const MAX_COMMENT_BODY_BYTES: usize = 65_536;
112const TRUNCATION_SUFFIX: &str = "\n\n<!-- fallow-truncated -->\n> Body truncated by fallow.";
113
114#[must_use]
115pub fn issues_from_codeclimate(value: &Value) -> Vec<CiIssue> {
116 let mut issues = value
117 .as_array()
118 .into_iter()
119 .flatten()
120 .filter_map(issue_from_codeclimate)
121 .collect::<Vec<_>>();
122 sort_ci_issues(&mut issues);
123 issues
124}
125
126#[must_use]
127pub fn issues_from_codeclimate_issues(issues: &[CodeClimateIssue]) -> Vec<CiIssue> {
128 let mut issues = issues
129 .iter()
130 .map(issue_from_codeclimate_issue)
131 .collect::<Vec<_>>();
132 sort_ci_issues(&mut issues);
133 issues
134}
135
136fn issue_from_codeclimate(value: &Value) -> Option<CiIssue> {
137 let path = value.pointer("/location/path")?.as_str()?.to_string();
138 let line = value
139 .pointer("/location/lines/begin")
140 .and_then(Value::as_u64)
141 .unwrap_or(1);
142 Some(CiIssue {
143 rule_id: value
144 .get("check_name")
145 .and_then(Value::as_str)
146 .unwrap_or("fallow/finding")
147 .to_string(),
148 description: value
149 .get("description")
150 .and_then(Value::as_str)
151 .unwrap_or("Fallow finding")
152 .to_string(),
153 severity: value
154 .get("severity")
155 .and_then(Value::as_str)
156 .unwrap_or("minor")
157 .to_string(),
158 fingerprint: value
159 .get("fingerprint")
160 .and_then(Value::as_str)
161 .unwrap_or("")
162 .to_string(),
163 path,
164 line,
165 })
166}
167
168fn issue_from_codeclimate_issue(issue: &CodeClimateIssue) -> CiIssue {
169 CiIssue {
170 rule_id: issue.check_name.clone(),
171 description: issue.description.clone(),
172 severity: codeclimate_severity_label(issue.severity).to_owned(),
173 path: issue.location.path.clone(),
174 line: u64::from(issue.location.lines.begin),
175 fingerprint: issue.fingerprint.clone(),
176 }
177}
178
179const fn codeclimate_severity_label(severity: CodeClimateSeverity) -> &'static str {
180 match severity {
181 CodeClimateSeverity::Info => "info",
182 CodeClimateSeverity::Minor => "minor",
183 CodeClimateSeverity::Major => "major",
184 CodeClimateSeverity::Critical => "critical",
185 CodeClimateSeverity::Blocker => "blocker",
186 }
187}
188
189fn sort_ci_issues(issues: &mut [CiIssue]) {
190 issues
191 .sort_by(|a, b| (&a.path, a.line, &a.fingerprint).cmp(&(&b.path, b.line, &b.fingerprint)));
192}
193
194fn fingerprint_hash(parts: &[&str]) -> String {
195 crate::codeclimate_fingerprint_hash(parts)
196}
197
198#[must_use]
199#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
200pub fn render_pr_comment(input: &PrCommentRenderInput<'_>) -> String {
201 let marker = format!("<!-- fallow-id: {} -->", input.marker_id);
202 let title = command_title(input.command);
203 let count = input.issues.len();
204 let noun = if count == 1 { "finding" } else { "findings" };
205
206 let mut out = String::new();
207 out.push_str(&marker);
208 out.push('\n');
209 write!(&mut out, "### Fallow {title}\n\n").expect("write to string");
210 if count == 0 {
211 writeln!(
212 &mut out,
213 "No {provider} PR/MR findings.",
214 provider = input.provider.name()
215 )
216 .expect("write to string");
217 } else {
218 write!(&mut out, "Found **{count}** {noun}.\n\n").expect("write to string");
219 let groups = group_by_category(input.issues, input.category_for_rule);
220 if let [(_, group_issues)] = groups.as_slice() {
221 render_findings_table(&mut out, group_issues, input.max_comments, "Details");
222 } else {
223 for (category, group_issues) in &groups {
224 let summary_label = summary_label(category, group_issues.len(), input.max_comments);
225 render_findings_table(&mut out, group_issues, input.max_comments, &summary_label);
226 }
227 }
228 }
229 out.push_str("\nGenerated by fallow.");
230 out
231}
232
233pub const PROJECT_LEVEL_RULE_IDS: &[&str] = &[
236 "fallow/unused-catalog-entry",
237 "fallow/empty-catalog-group",
238 "fallow/unresolved-catalog-reference",
239 "fallow/unused-dependency-override",
240 "fallow/misconfigured-dependency-override",
241 "fallow/unused-dependency",
242 "fallow/unused-dev-dependency",
243 "fallow/unused-optional-dependency",
244 "fallow/type-only-dependency",
245 "fallow/test-only-dependency",
246 "fallow/dev-dependency-in-production",
247];
248
249#[must_use]
250pub fn is_project_level_rule(rule_id: &str) -> bool {
251 PROJECT_LEVEL_RULE_IDS.contains(&rule_id)
252}
253
254const CATEGORY_ORDER: [&str; 6] = [
255 "Dead code",
256 "Dependencies",
257 "Duplication",
258 "Health",
259 "Architecture",
260 "Suppressions",
261];
262
263fn group_by_category<'a>(
264 issues: &'a [CiIssue],
265 category_for_rule: &dyn Fn(&str) -> &'static str,
266) -> Vec<(&'static str, Vec<&'a CiIssue>)> {
267 let mut buckets: std::collections::BTreeMap<&'static str, Vec<&CiIssue>> =
268 std::collections::BTreeMap::new();
269 for issue in issues {
270 let category = category_for_rule(&issue.rule_id);
271 buckets.entry(category).or_default().push(issue);
272 }
273 let mut ordered: Vec<(&'static str, Vec<&CiIssue>)> = Vec::with_capacity(buckets.len());
274 for category in CATEGORY_ORDER {
275 if let Some(items) = buckets.remove(category) {
276 ordered.push((category, items));
277 }
278 }
279 for (category, items) in buckets {
280 ordered.push((category, items));
281 }
282 ordered
283}
284
285#[must_use]
286pub fn summary_label(category: &str, total: usize, max: usize) -> String {
287 if total > max {
288 format!("{category} ({total}, showing {max})")
289 } else {
290 format!("{category} ({total})")
291 }
292}
293
294#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
295fn render_findings_table(out: &mut String, issues: &[&CiIssue], max: usize, summary: &str) {
296 writeln!(out, "<details>\n<summary>{summary}</summary>\n").expect("write to string");
297 out.push_str("| Severity | Rule | Location | Description |\n");
298 out.push_str("| --- | --- | --- | --- |\n");
299 for issue in issues.iter().take(max) {
300 writeln!(
301 out,
302 "| {} | `{}` | `{}`:{} | {} |",
303 escape_md(&issue.severity),
304 escape_md(&issue.rule_id),
305 escape_md(&issue.path),
306 issue.line,
307 escape_md(&issue.description),
308 )
309 .expect("write to string");
310 }
311 if issues.len() > max {
312 writeln!(
313 out,
314 "\nShowing {max} of {} findings. Run fallow locally or inspect the CI output for the full report.",
315 issues.len(),
316 )
317 .expect("write to string");
318 }
319 out.push_str("\n</details>\n\n");
320}
321
322#[must_use]
323pub fn command_title(command: &str) -> &'static str {
324 match command {
325 "dead-code" | "check" => "dead-code report",
326 "dupes" => "duplication report",
327 "health" => "health report",
328 "audit" => "audit report",
329 "" | "combined" => "combined report",
330 _ => "report",
331 }
332}
333
334#[must_use]
336pub fn escape_md(value: &str) -> String {
337 let collapsed = value.replace('\n', " ");
338 let mut out = String::with_capacity(collapsed.len());
339 for ch in collapsed.chars() {
340 if matches!(
341 ch,
342 '\\' | '`'
343 | '*'
344 | '_'
345 | '['
346 | ']'
347 | '('
348 | ')'
349 | '!'
350 | '<'
351 | '>'
352 | '#'
353 | '|'
354 | '~'
355 | '&'
356 ) {
357 out.push('\\');
358 }
359 out.push(ch);
360 }
361 out.trim().to_owned()
362}
363
364#[must_use]
366pub fn render_review_envelope(input: &ReviewEnvelopeRenderInput<'_>) -> ReviewEnvelopeRenderResult {
367 let grouped = group_review_issues_by_path_line(input.issues, input.max_comments);
368
369 let comments: Vec<ReviewComment> = grouped
370 .groups
371 .iter()
372 .map(|group| {
373 render_review_comment_for_group(&ReviewCommentRenderInput {
374 provider: input.provider,
375 group,
376 gitlab_diff_refs: input.gitlab_diff_refs,
377 diff_index: input.diff_index,
378 path_prefix: input.path_prefix,
379 include_guidance: input.include_guidance,
380 suggestion_block: input.suggestion_block,
381 guidance_block: input.guidance_block,
382 })
383 })
384 .collect();
385
386 let summary_text =
387 review_summary_text(input.command, input.provider, comments.len(), input.issues);
388 let summary_fp = summary_fingerprint(&summary_text);
389 let summary_marker = format!("\n\n{MARKER_PREFIX_V2}{summary_fp}{MARKER_SUFFIX_V2}");
390 let body = format!("{summary_text}{summary_marker}");
391 let summary = ReviewEnvelopeSummary {
392 body: body.clone(),
393 fingerprint: summary_fp,
394 };
395
396 let truncation = ReviewEnvelopeTruncation {
397 body: comments.iter().any(review_comment_truncated),
398 comment_limit: grouped.truncated,
399 };
400
401 ReviewEnvelopeRenderResult {
402 envelope: build_review_envelope_output(
403 input.provider,
404 body,
405 summary,
406 comments,
407 input.issues,
408 ),
409 truncation,
410 }
411}
412
413fn review_summary_text(
414 command: &str,
415 provider: CiProvider,
416 comment_count: usize,
417 issues: &[CiIssue],
418) -> String {
419 let verdict = review_summary_verdict(issues);
420 format!(
421 "### Fallow {}\n\n**{}**\n\n{} inline finding{} selected for {} review.\n\n<!-- fallow-review -->",
422 command_title(command),
423 verdict,
424 comment_count,
425 if comment_count == 1 { "" } else { "s" },
426 provider.name(),
427 )
428}
429
430fn review_summary_verdict(issues: &[CiIssue]) -> &'static str {
431 match github_check_conclusion(issues) {
432 ReviewCheckConclusion::Failure => "Quality gate failed",
433 ReviewCheckConclusion::Neutral => "Review needed",
434 ReviewCheckConclusion::Success => "Quality gate passed",
435 }
436}
437
438#[derive(Debug, PartialEq, Eq)]
439pub struct GroupedReviewIssues<'a> {
440 pub groups: Vec<Vec<&'a CiIssue>>,
441 pub truncated: bool,
442}
443
444#[must_use]
447pub fn group_review_issues_by_path_line(
448 issues: &[CiIssue],
449 max_groups: usize,
450) -> GroupedReviewIssues<'_> {
451 if max_groups == 0 {
452 return GroupedReviewIssues {
453 groups: Vec::new(),
454 truncated: !issues.is_empty(),
455 };
456 }
457 let mut groups: Vec<Vec<&CiIssue>> = Vec::with_capacity(max_groups.min(issues.len()));
458 let mut current: Vec<&CiIssue> = Vec::new();
459 let mut current_key: Option<(&str, u64)> = None;
460 for issue in issues {
461 let key = (issue.path.as_str(), issue.line);
462 if Some(key) != current_key {
463 if !current.is_empty() {
464 groups.push(std::mem::take(&mut current));
465 if groups.len() == max_groups {
466 return GroupedReviewIssues {
467 groups,
468 truncated: true,
469 };
470 }
471 }
472 current_key = Some(key);
473 }
474 current.push(issue);
475 }
476 if !current.is_empty() && groups.len() < max_groups {
477 groups.push(current);
478 }
479 GroupedReviewIssues {
480 groups,
481 truncated: false,
482 }
483}
484
485fn review_comment_truncated(comment: &ReviewComment) -> bool {
486 match comment {
487 ReviewComment::GitHub(comment) => comment.truncated,
488 ReviewComment::GitLab(comment) => comment.truncated,
489 }
490}
491
492pub struct ReviewCommentRenderInput<'a, 'group> {
493 pub provider: CiProvider,
494 pub group: &'a [&'group CiIssue],
495 pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
496 pub diff_index: Option<&'a DiffIndex>,
497 pub path_prefix: &'a str,
499 pub include_guidance: bool,
500 pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
501 pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
502}
503
504#[must_use]
506pub fn render_review_comment_for_group(input: &ReviewCommentRenderInput<'_, '_>) -> ReviewComment {
507 assert!(
508 !input.group.is_empty(),
509 "group_review_issues_by_path_line never yields empty"
510 );
511 let representative = input.group[0];
512 let fingerprint = if input.group.len() == 1 {
513 representative.fingerprint.clone()
514 } else {
515 let constituents: Vec<&str> = input.group.iter().map(|i| i.fingerprint.as_str()).collect();
516 composite_fingerprint(&constituents)
517 };
518
519 let content = build_merged_comment_content(input);
520 let marker_line = format!("\n\n{MARKER_PREFIX_V2}{fingerprint}{MARKER_SUFFIX_V2}");
521 let (body, truncated) = cap_body_with_marker(&content, &marker_line);
522
523 build_review_comment(ReviewCommentInput {
524 provider: input.provider,
525 representative,
526 gitlab_diff_refs: input.gitlab_diff_refs,
527 diff_index: input.diff_index,
528 path_prefix: input.path_prefix,
529 body,
530 fingerprint,
531 truncated,
532 })
533}
534
535#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
536fn build_merged_comment_content(input: &ReviewCommentRenderInput<'_, '_>) -> String {
537 let mut content = String::new();
538 for (index, issue) in input.group.iter().enumerate() {
539 let label = review_label_from_codeclimate(&issue.severity);
540 if index > 0 {
541 content.push_str("\n\n");
542 }
543 write!(
544 content,
545 "**{}** `{}`: {}",
546 label,
547 escape_md(&issue.rule_id),
548 escape_md(&issue.description)
549 )
550 .expect("write to String is infallible");
551 if let Some(suggestion) = (input.suggestion_block)(input.provider, issue) {
552 content.push_str(&suggestion);
553 }
554 if input.include_guidance
555 && let Some(guidance) = (input.guidance_block)(issue)
556 {
557 content.push_str(&guidance);
558 }
559 }
560 content
561}
562
563struct ReviewCommentInput<'a> {
564 provider: CiProvider,
565 representative: &'a CiIssue,
566 gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
567 diff_index: Option<&'a DiffIndex>,
568 path_prefix: &'a str,
569 body: String,
570 fingerprint: String,
571 truncated: bool,
572}
573
574fn build_review_comment(input: ReviewCommentInput<'_>) -> ReviewComment {
575 let ReviewCommentInput {
576 provider,
577 representative,
578 gitlab_diff_refs,
579 diff_index,
580 path_prefix,
581 body,
582 fingerprint,
583 truncated,
584 } = input;
585 match provider {
586 CiProvider::Github => ReviewComment::GitHub(GitHubReviewComment {
587 path: apply_path_prefix(path_prefix, &representative.path),
588 line: u32::try_from(representative.line).unwrap_or(u32::MAX),
589 side: GitHubReviewSide::Right,
590 body,
591 fingerprint,
592 truncated,
593 }),
594 CiProvider::Gitlab => {
595 let old_rel = diff_index
598 .and_then(|di| di.old_path_for_root_relative(&representative.path))
599 .map_or_else(|| representative.path.clone(), Cow::into_owned);
600 let new_path = apply_path_prefix(path_prefix, &representative.path);
601 let old_path = apply_path_prefix(path_prefix, &old_rel);
602 let position = GitLabReviewPosition {
603 base_sha: gitlab_diff_refs.map(|r| r.base_sha.clone()),
604 start_sha: gitlab_diff_refs.map(|r| r.start_sha.clone()),
605 head_sha: gitlab_diff_refs.map(|r| r.head_sha.clone()),
606 position_type: GitLabReviewPositionType::Text,
607 old_path,
608 new_path,
609 new_line: u32::try_from(representative.line).unwrap_or(u32::MAX),
610 };
611 ReviewComment::GitLab(GitLabReviewComment {
612 body,
613 position,
614 fingerprint,
615 truncated,
616 })
617 }
618 }
619}
620
621#[must_use]
622pub fn cap_body_with_marker(content: &str, marker_line: &str) -> (String, bool) {
623 let intact_len = content.len() + marker_line.len();
624 if intact_len <= MAX_COMMENT_BODY_BYTES {
625 let mut out = String::with_capacity(intact_len);
626 out.push_str(content);
627 out.push_str(marker_line);
628 return (out, false);
629 }
630 let reserved = marker_line.len() + TRUNCATION_SUFFIX.len();
631 let budget = MAX_COMMENT_BODY_BYTES.saturating_sub(reserved);
632 let mut cut = budget.min(content.len());
633 while cut > 0 && !content.is_char_boundary(cut) {
634 cut -= 1;
635 }
636 let mut out = String::with_capacity(MAX_COMMENT_BODY_BYTES);
637 out.push_str(&content[..cut]);
638 out.push_str(TRUNCATION_SUFFIX);
639 out.push_str(marker_line);
640 (out, true)
641}
642
643#[must_use]
644pub const fn review_label_from_codeclimate(severity_name: &str) -> &'static str {
645 match severity_name.as_bytes() {
646 b"major" | b"critical" | b"blocker" => "error",
647 _ => "warn",
648 }
649}
650
651#[must_use]
652pub fn github_check_conclusion(issues: &[CiIssue]) -> ReviewCheckConclusion {
653 if issues
654 .iter()
655 .any(|issue| matches!(issue.severity.as_str(), "major" | "critical" | "blocker"))
656 {
657 ReviewCheckConclusion::Failure
658 } else if issues.is_empty() {
659 ReviewCheckConclusion::Success
660 } else {
661 ReviewCheckConclusion::Neutral
662 }
663}
664
665fn build_review_envelope_output(
666 provider: CiProvider,
667 body: String,
668 summary: ReviewEnvelopeSummary,
669 comments: Vec<ReviewComment>,
670 issues: &[CiIssue],
671) -> ReviewEnvelopeOutput {
672 match provider {
673 CiProvider::Github => ReviewEnvelopeOutput {
674 event: Some(ReviewEnvelopeEvent::Comment),
675 body,
676 summary,
677 comments,
678 marker_regex: default_marker_regex(),
679 marker_regex_flags: default_marker_regex_flags(),
680 meta: ReviewEnvelopeMeta {
681 schema: ReviewEnvelopeSchema::V2,
682 provider: ReviewProvider::Github,
683 check_conclusion: Some(github_check_conclusion(issues)),
684 },
685 },
686 CiProvider::Gitlab => ReviewEnvelopeOutput {
687 event: None,
688 body,
689 summary,
690 comments,
691 marker_regex: default_marker_regex(),
692 marker_regex_flags: default_marker_regex_flags(),
693 meta: ReviewEnvelopeMeta {
694 schema: ReviewEnvelopeSchema::V2,
695 provider: ReviewProvider::Gitlab,
696 check_conclusion: None,
697 },
698 },
699 }
700}
701
702#[must_use]
703pub fn summary_fingerprint(body: &str) -> String {
704 fingerprint_hash(&[body])
705}
706
707#[must_use]
708pub fn composite_fingerprint(constituents: &[&str]) -> String {
709 let mut sorted: Vec<&str> = constituents.to_vec();
710 sorted.sort_unstable();
711 let joined = sorted.join(":");
712 format!("merged:{}", fingerprint_hash(&[joined.as_str()]))
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718 use crate::{CodeClimateIssueKind, CodeClimateLines, CodeClimateLocation};
719
720 fn category_for_rule(rule_id: &str) -> &'static str {
721 match rule_id {
722 "fallow/code-duplication" => "Duplication",
723 "fallow/high-complexity" => "Health",
724 "fallow/unused-dependency" => "Dependencies",
725 _ => "Dead code",
726 }
727 }
728
729 #[test]
730 fn extracts_issues_from_codeclimate() {
731 let value = serde_json::json!([{
732 "check_name": "fallow/unused-export",
733 "description": "Export x is never imported",
734 "severity": "minor",
735 "fingerprint": "abc",
736 "location": { "path": "src/a.ts", "lines": { "begin": 7 } }
737 }]);
738 let issues = issues_from_codeclimate(&value);
739 assert_eq!(issues.len(), 1);
740 assert_eq!(issues[0].path, "src/a.ts");
741 assert_eq!(issues[0].line, 7);
742 }
743
744 #[test]
745 fn typed_codeclimate_issues_extract_like_json_codeclimate() {
746 let severities = [
747 (CodeClimateSeverity::Info, "info"),
748 (CodeClimateSeverity::Minor, "minor"),
749 (CodeClimateSeverity::Major, "major"),
750 (CodeClimateSeverity::Critical, "critical"),
751 (CodeClimateSeverity::Blocker, "blocker"),
752 ];
753 let typed = severities
754 .iter()
755 .enumerate()
756 .map(|(index, (severity, _))| CodeClimateIssue {
757 kind: CodeClimateIssueKind::Issue,
758 check_name: format!("fallow/rule-{index}"),
759 description: format!("Finding {index}"),
760 categories: vec!["Complexity".to_owned()],
761 severity: *severity,
762 fingerprint: format!("fp-{index}"),
763 location: CodeClimateLocation {
764 path: format!("src/{index}.ts"),
765 lines: CodeClimateLines {
766 begin: u32::try_from(index + 1).expect("small fixture index"),
767 },
768 },
769 owner: None,
770 group: None,
771 })
772 .collect::<Vec<_>>();
773 let value = serde_json::to_value(&typed).expect("typed fixture serializes");
774
775 assert_eq!(
776 issues_from_codeclimate_issues(&typed),
777 issues_from_codeclimate(&value)
778 );
779 let typed_labels = issues_from_codeclimate_issues(&typed)
780 .into_iter()
781 .map(|issue| issue.severity)
782 .collect::<Vec<_>>();
783 let expected_labels = severities
784 .iter()
785 .map(|(_, label)| (*label).to_owned())
786 .collect::<Vec<_>>();
787 assert_eq!(typed_labels, expected_labels);
788 }
789
790 #[test]
791 fn renders_default_empty_comment() {
792 let body = render_pr_comment(&PrCommentRenderInput {
793 command: "check",
794 provider: CiProvider::Github,
795 issues: &[],
796 marker_id: "fallow-results".to_owned(),
797 max_comments: 50,
798 category_for_rule: &category_for_rule,
799 });
800 assert!(body.contains("<!-- fallow-id: fallow-results"));
801 assert!(body.contains("No GitHub PR/MR findings."));
802 }
803
804 #[test]
805 fn escape_md_escapes_inline_commonmark_specials() {
806 let raw = "foo*bar_baz [a](u) `c` <h> #x !i ~s | p";
807 let escaped = escape_md(raw);
808 for ch in [
809 '*', '_', '[', ']', '(', ')', '`', '<', '>', '#', '!', '~', '|',
810 ] {
811 let raw_count = raw.chars().filter(|c| c == &ch).count();
812 let escaped_count = escaped.matches(&format!("\\{ch}")).count();
813 assert_eq!(
814 raw_count, escaped_count,
815 "char {ch:?}: raw {raw_count} occurrences, escaped {escaped_count} in {escaped:?}"
816 );
817 }
818 }
819
820 #[test]
821 fn escape_md_escapes_ampersand_to_block_numeric_entity_bypass() {
822 let raw = "value *suspicious* here";
823 let escaped = escape_md(raw);
824 assert!(escaped.contains(r"\&"), "got: {escaped}");
825 assert!(escaped.contains(r"\#"), "got: {escaped}");
826 assert!(!escaped.contains(" *suspicious"), "got: {escaped}");
827 }
828
829 #[test]
830 fn summary_label_foreshadows_truncation() {
831 assert_eq!(
832 summary_label("Duplication", 160, 50),
833 "Duplication (160, showing 50)"
834 );
835 assert_eq!(summary_label("Health", 12, 50), "Health (12)");
836 assert_eq!(summary_label("Dependencies", 50, 50), "Dependencies (50)");
837 }
838
839 #[test]
840 fn escape_md_does_not_escape_block_only_markers() {
841 let raw = "fallow/test-only-dependency package.json:12";
842 let escaped = escape_md(raw);
843 assert!(!escaped.contains("\\-"), "should not escape `-`");
844 assert!(!escaped.contains("\\."), "should not escape `.`");
845 assert_eq!(escaped, raw);
846 }
847
848 #[test]
849 fn escape_md_collapses_newlines_to_spaces() {
850 let raw = "first\nsecond\nthird";
851 assert_eq!(escape_md(raw), "first second third");
852 }
853
854 #[test]
855 fn escape_md_leaves_safe_chars_unchanged() {
856 let raw = "Export 'helperFn' is never imported by other modules";
857 assert_eq!(
858 escape_md(raw),
859 r"Export 'helperFn' is never imported by other modules"
860 );
861 }
862
863 #[test]
864 fn is_project_level_rule_covers_config_anchored_dependency_findings() {
865 for rule_id in PROJECT_LEVEL_RULE_IDS {
866 assert!(
867 is_project_level_rule(rule_id),
868 "{rule_id} must be project-level"
869 );
870 }
871 for rule_id in [
872 "fallow/unused-file",
873 "fallow/unused-export",
874 "fallow/unused-type",
875 "fallow/unused-enum-member",
876 "fallow/unused-class-member",
877 "fallow/unused-store-member",
878 "fallow/unresolved-import",
879 "fallow/unlisted-dependency",
880 "fallow/duplicate-export",
881 "fallow/circular-dependency",
882 "fallow/re-export-cycle",
883 "fallow/boundary-violation",
884 "fallow/stale-suppression",
885 "fallow/private-type-leak",
886 "fallow/high-complexity",
887 "fallow/high-crap-score",
888 ] {
889 assert!(
890 !is_project_level_rule(rule_id),
891 "{rule_id} must NOT be project-level"
892 );
893 }
894 }
895
896 #[test]
897 fn escape_md_double_apply_is_safe() {
898 let raw = "code with `backticks` and *stars*";
899 let once = escape_md(raw);
900 let twice = escape_md(&once);
901 assert!(twice.contains(r"\\"));
902 }
903}