Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/rule002 #32

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@ use crate::{
};

mod rule001_heading_case;
mod rule002_admonition_types;

use rule001_heading_case::Rule001HeadingCase;
use rule002_admonition_types::Rule002AdmonitionTypes;

static ALL_RULES: Lazy<Vec<Box<dyn Rule>>> =
Lazy::new(|| vec![Box::new(Rule001HeadingCase::default())]);
static ALL_RULES: Lazy<Vec<Box<dyn Rule>>> = Lazy::new(|| {
vec![
Box::new(Rule001HeadingCase::default()),
Box::new(Rule002AdmonitionTypes::default()),
]
});

#[allow(private_bounds)] // RuleClone is used within this module tree only
pub trait Rule: Send + Sync + Debug + RuleName + RuleClone {
Expand Down Expand Up @@ -92,6 +98,26 @@ impl RuleSettings {
Self::from_key_value(key, toml::Value::Array(array))
}

fn get_array_of_strings(&self, key: &str) -> Option<Vec<String>> {
let table = &self.0;
if let Some(toml::Value::Array(array)) = table.get(key) {
let mut vec = Vec::new();
for value in array {
if let toml::Value::String(string) = value {
vec.push(string.to_lowercase());
}
}

if vec.is_empty() {
return None;
} else {
return Some(vec);
}
}

None
}

fn get_array_of_regexes(
&self,
key: &str,
Expand Down
13 changes: 5 additions & 8 deletions src/rules/rule001_heading_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,7 @@ impl Rule for Rule001HeadingCase {
let lint_error = if fixes.is_empty() {
None
} else {
LintError::from_node_with_fix(
ast,
context,
self.name(),
"Heading should be sentence case",
level,
fixes,
)
LintError::from_node_with_fix(ast, context, self.name(), &self.message(), level, fixes)
};

lint_error.map(|lint_error| vec![lint_error])
Expand All @@ -77,6 +70,10 @@ enum Case {
}

impl Rule001HeadingCase {
fn message(&self) -> String {
"Heading should be sentence case".to_string()
}

fn check_text_sentence_case(
&self,
text: &Text,
Expand Down
225 changes: 225 additions & 0 deletions src/rules/rule002_admonition_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
use log::{trace, warn};
use markdown::mdast::Node;
use regex::Regex;
use supa_mdx_macros::RuleName;

use crate::{
errors::{LintError, LintLevel},
geometry::{AdjustedOffset, AdjustedRange, DenormalizedLocation},
};

use super::{Rule, RuleContext, RuleName, RuleSettings};

#[derive(Debug, Default, Clone, RuleName)]
pub struct Rule002AdmonitionTypes {
admonition_types: Vec<String>,
}

impl Rule for Rule002AdmonitionTypes {
fn default_level(&self) -> LintLevel {
LintLevel::Error
}

fn setup(&mut self, settings: Option<&RuleSettings>) {
if let Some(settings) = settings {
if let Some(vec) = settings.get_array_of_strings("admonition_types") {
self.admonition_types = vec;
}
}
}

fn check(&self, ast: &Node, context: &RuleContext, level: LintLevel) -> Option<Vec<LintError>> {
if !matches!(ast, Node::MdxJsxFlowElement(_)) {
return None;
};

self.check_ast(ast, context, level)
.map(|lint_error| vec![lint_error])
}
}

impl Rule002AdmonitionTypes {
fn message(&self, got: Option<&str>) -> String {
match got {
Some(got) => format!(
"Allowed admonition types are: {}. Got: \"{got}\".",
self.admonition_types.join(", "),
),
None => "Missing admonition type.".to_string(),
}
}

fn check_ast(&self, node: &Node, context: &RuleContext, level: LintLevel) -> Option<LintError> {
trace!("Checking ast for node: {node:?}");

match node {
Node::MdxJsxFlowElement(element)
if element
.name
.as_ref()
.map_or(false, |name| name == "Admonition") =>
{
for attr in &element.attributes {
match attr {
markdown::mdast::AttributeContent::Property(mdx_jsx_attribute)
if mdx_jsx_attribute.name == "type" =>
{
if let Some(markdown::mdast::AttributeValue::Literal(type_name)) =
&mdx_jsx_attribute.value
{
let allowed_type_name = self.admonition_types.contains(type_name);
if allowed_type_name {
return None;
} else {
return self.create_lint_error_wrong_type(
node, context, level, type_name,
);
}
}
}
_ => {}
}
}

self.create_lint_error_missing_type(node, context, level)
}
_ => None,
}
}

fn create_lint_error_missing_type(
&self,
node: &Node,
context: &RuleContext,
level: LintLevel,
) -> Option<LintError> {
LintError::from_node(node, context, self.name(), &self.message(None), level)
}

fn create_lint_error_wrong_type(
&self,
node: &Node,
context: &RuleContext,
level: LintLevel,
type_name: &str,
) -> Option<LintError> {
let node_source = node
.position()
.map(|pos| {
let start = AdjustedOffset::from_unist(&pos.start, context);
let end = AdjustedOffset::from_unist(&pos.end, context);
context
.rope()
.byte_slice(Into::<usize>::into(start)..Into::<usize>::into(end))
})
.map(|slice| slice.to_string());
if let Some(node_source) = node_source {
match Regex::new(r#"\b(type)\s*=\s*["']"#) {
Ok(type_regex) => {
if let Some(match_result) =
type_regex.captures(&node_source).and_then(|cap| cap.get(1))
{
let mut start_point =
AdjustedOffset::from_unist(&node.position().unwrap().start, context);
start_point.increment(match_result.start());
let mut end_point = start_point;
end_point.increment("type".len());

let range = AdjustedRange::new(start_point, end_point);
let location = DenormalizedLocation::from_offset_range(range, context);

return Some(LintError {
rule: self.name().to_string(),
level,
message: self.message(Some(type_name)),
location,
fix: None,
});
}
}
Err(_) => {
warn!("Error extracting type from admonition to fine-tune lint location: {node_source}");
}
}
}

LintError::from_node(
node,
context,
self.name(),
&self.message(Some(type_name)),
level,
)
}
}

#[cfg(test)]
mod tests {
use crate::{
parser::parse,
rules::{Rule, RuleContext},
LintLevel,
};

use super::Rule002AdmonitionTypes;

#[test]
fn test_admonition_types_wrong_type() {
let mdx = r#"---
title: Hello
---
<Admonition type="wrong">
Some text.
</Admonition>"#;

let rule = Rule002AdmonitionTypes::default();
let parse_result = parse(mdx).unwrap();
let context = RuleContext::new(parse_result, None).unwrap();

let admonition = context.parse_result.ast.children().unwrap().get(0).unwrap();
let result = rule.check(admonition, &context, LintLevel::Error);

assert!(result.is_some());
assert!(result.as_ref().unwrap().len() == 1);
let location = &result.as_ref().unwrap().get(0).unwrap().location;
assert!(location.start.row == 4);
assert!(location.start.column == 12);
assert!(location.end.row == 4);
assert!(location.end.column == 16);
}

#[test]
fn test_admonition_types_missing_type() {
let mdx = r#"<Admonition>
Some text.
</Admonition>"#;

let rule = Rule002AdmonitionTypes::default();
let parse_result = parse(mdx).unwrap();
let context = RuleContext::new(parse_result, None).unwrap();

let admonition = context.parse_result.ast.children().unwrap().get(0).unwrap();
let result = rule.check(admonition, &context, LintLevel::Error);

assert!(result.is_some());
assert!(result.unwrap().len() == 1);
}

#[test]
fn test_admonition_types_correct_type() {
let mdx = r#"<Admonition type="note">
Some text.
</Admonition>"#;

let mut rule = Rule002AdmonitionTypes::default();
rule.admonition_types = vec!["note".to_string()];
let parse_result = parse(mdx).unwrap();
let context = RuleContext::new(parse_result, None).unwrap();

let admonition = context.parse_result.ast.children().unwrap().get(0).unwrap();
let result = rule.check(admonition, &context, LintLevel::Error);

assert!(result.is_none());
}
}
15 changes: 15 additions & 0 deletions tests/rule002/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::process::Command;

use assert_cmd::prelude::*;
use predicates::prelude::*;

#[test]
fn integration_test_rule002() {
let mut cmd = Command::cargo_bin("supa-mdx-lint").unwrap();
cmd.arg("tests/rule002/rule002.mdx")
.arg("--config")
.arg("tests/rule002/supa-mdx-lint.config.toml");
cmd.assert()
.failure()
.stdout(predicate::str::contains("2 errors"));
}
25 changes: 25 additions & 0 deletions tests/rule002/rule002.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Test admonition types

<Admonition type="notfound">

Some text

</Admonition>

<Admonition type="caution">

Some text

</Admonition>

<Admonition>

Forgot to put a type

</Admonition>

<OtherComponent>

Something

</OtherComponent>
2 changes: 2 additions & 0 deletions tests/rule002/supa-mdx-lint.config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[Rule002AdmonitionTypes]
admonition_types = ["note", "tip", "caution", "deprecation", "danger"]
1 change: 1 addition & 0 deletions tests/rules.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod rule002;
2 changes: 1 addition & 1 deletion tests/supa-mdx-lint.config.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ignore_patterns = ["*00x.mdx"]
ignore_patterns = ["*00x.mdx", "rule*/**"]

[Rule001HeadingCase]
may_uppercase = ["Supabase"]