Skip to content

Commit

Permalink
Add context.codeblock config to speical enable / disable in codeblo…
Browse files Browse the repository at this point in the history
…ck. (#211)

In `.autocorrectrc`

```yml
# Enable or disable in spatial context
context:
  # Enable or disable to format codeblock in Markdown or AsciiDoc etc.
  codeblock: 1
```

Ref https://github.com/apache/eventmesh-site/pull/226/files#r1645701069
  • Loading branch information
huacnlee authored Jun 20, 2024
1 parent 60f7953 commit 01ef1e2
Show file tree
Hide file tree
Showing 16 changed files with 124 additions and 70 deletions.
4 changes: 4 additions & 0 deletions .autocorrectrc.template
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
rules:
# Default rules: https://github.com/huacnlee/autocorrect/raw/main/autocorrect/.autocorrectrc.default
spellcheck: 2
# Enable or disable in spatial context
context:
# Enable or disable to format codeblock in Markdown or AsciiDoc etc.
codeblock: 1
textRules:
# Config some special rule for some texts
# For example, if we wants to let "Hello你好" just warning, and "Hi你好" to ignore
Expand Down
24 changes: 10 additions & 14 deletions autocorrect-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ where

let mut filetype = autocorrect::get_file_extension(filepath);
if let Some(ref ftype) = cli.filetype {
filetype = ftype.to_owned();
filetype = ftype.to_string();
}
if !autocorrect::is_support_type(&filetype) {
continue;
Expand Down Expand Up @@ -262,15 +262,13 @@ where
// Exit with code = 1
std::process::exit(1);
}
} else if cli.formatter == cli::OutputFormatter::Json {
log::info!("{}", autocorrect::json::to_lint_results_json(lint_results));
} else {
if cli.formatter == cli::OutputFormatter::Json {
log::info!("{}", autocorrect::json::to_lint_results_json(lint_results));
} else {
log::info!(
"{}",
autocorrect::rdjson::to_lint_results_rdjson(lint_results)
)
}
log::info!(
"{}",
autocorrect::rdjson::to_lint_results_rdjson(lint_results)
)
}
} else if cli.fix {
progress::finish(&cli, start_t);
Expand Down Expand Up @@ -365,11 +363,9 @@ fn lint_and_output(
progress::warn(cli);
}

if cli.formatter.is_diff() {
if result.has_error() {
log::debug!("{}\n{}", filepath, result.error);
return;
}
if cli.formatter.is_diff() && result.has_error() {
log::debug!("{}\n{}", filepath, result.error);
return;
}

results.push(result.clone());
Expand Down
11 changes: 4 additions & 7 deletions autocorrect-cli/src/progress.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use owo_colors::OwoColorize;
use std::{
io::{self, Write},
time::SystemTime,
};
use std::time::SystemTime;

use crate::{cli::Cli, logger::SystemTimeDuration as _};

Expand All @@ -11,23 +8,23 @@ pub fn ok(cli: &Cli) {
return;
}

write!(io::stdout(), "{}", ".".green()).unwrap();
print!("{}", ".".green());
}

pub fn warn(cli: &Cli) {
if cli.quiet || !cli.formatter.is_diff() {
return;
}

write!(io::stdout(), "{}", ".".yellow()).unwrap();
print!("{}", ".".yellow());
}

pub fn err(cli: &Cli) {
if cli.quiet || !cli.formatter.is_diff() {
return;
}

write!(io::stdout(), "{}", ".".red()).unwrap();
print!("{}", ".".red());
}

/// print time spend from start_t to now
Expand Down
29 changes: 14 additions & 15 deletions autocorrect-lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ impl Backend {
.map(|old| std::mem::replace(old, doc.clone()));
}

fn get_document<'a>(&'a self, uri: &Url) -> Option<Arc<TextDocumentItem>> {
self.documents.read().unwrap().get(uri).map(|a| a.clone())
fn get_document(&self, uri: &Url) -> Option<Arc<TextDocumentItem>> {
self.documents.read().unwrap().get(uri).cloned()
}

fn remove_document(&self, uri: &Url) {
Expand All @@ -47,7 +47,7 @@ impl Backend {

let input = document.text.as_str();
let path = document.uri.path();
let result = autocorrect::lint_for(input, &path);
let result = autocorrect::lint_for(input, path);

let diagnostics = result
.lines
Expand Down Expand Up @@ -124,7 +124,7 @@ impl Backend {

fn is_ignored(&self, uri: &Url) -> bool {
if let Some(ignorer) = self.ignorer.read().unwrap().as_ref() {
if let Some(filepath) = uri.to_file_path().ok() {
if let Ok(filepath) = uri.to_file_path() {
return ignorer.is_ignored(&filepath.to_string_lossy());
}
}
Expand Down Expand Up @@ -302,12 +302,12 @@ impl LanguageServer for Backend {
self.clear_diagnostics(&text_document.uri).await;
let input = document.text.as_str();

let result = autocorrect::format_for(input, &document.uri.path());
let result = autocorrect::format_for(input, document.uri.path());
let range = Range::new(
Position::new(0, 0),
Position {
line: u32::max_value(),
character: u32::max_value(),
line: u32::MAX,
character: u32::MAX,
},
);
return Ok(Some(vec![TextEdit::new(range, result.out)]));
Expand Down Expand Up @@ -345,7 +345,7 @@ impl LanguageServer for Backend {
vec![(
text_document.uri.clone(),
vec![TextEdit {
range: diagnostic.range.clone(),
range: diagnostic.range,
new_text: diagnostic.message.clone(),
}],
)]
Expand All @@ -370,13 +370,12 @@ pub async fn start() {
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();

let (service, socket) = LspService::new(|client| {
return Backend {
client,
work_dir: RwLock::new(PathBuf::new()),
documents: RwLock::new(HashMap::new()),
ignorer: RwLock::new(None),
};
let (service, socket) = LspService::new(|client| Backend {
client,
work_dir: RwLock::new(PathBuf::new()),
documents: RwLock::new(HashMap::new()),
ignorer: RwLock::new(None),
});

Server::new(stdin, stdout, socket).serve(service).await;
}
4 changes: 4 additions & 0 deletions autocorrect/.autocorrectrc.default
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ rules:
halfwidth-punctuation: 1
# Spellcheck
spellcheck: 0
# Enable or disable in spatial context
context:
# Enable or disable to format codeblock in Markdown or AsciiDoc etc.
codeblock: 1
textRules:
# No default text rules.
spellcheck:
Expand Down
12 changes: 10 additions & 2 deletions autocorrect/src/code/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::*;
use crate::config::toggle;
pub use crate::result::*;
use crate::rule::CJK_RE;
use crate::Config;
use pest::error::Error;
use pest::iterators::{Pair, Pairs};
use pest::RuleType;
Expand Down Expand Up @@ -44,7 +45,6 @@ fn format_pair<R: RuleType, O: Results>(results: &mut O, pair: Pair<R>) {
let rule_name = rule_name.as_str();

// println!("rule: {}, {}", rule_name, item.as_str());

match rule_name {
"string" | "link_string" | "mark_string" | "text" | "inner_text" | "comment"
| "COMMENT" => {
Expand Down Expand Up @@ -182,12 +182,19 @@ fn format_or_lint_for_inline_scripts<R: RuleType, O: Results>(
let part = pair.as_str();
let (base_line, _) = pair.line_col();

let is_enable_context =
rule_name != "codeblock" || Config::current().is_enabled_context("codeblock");

if results.is_lint() {
// Skip lint if AutoCorrect disabled
if !results.is_enabled() {
return;
}

if !is_enable_context {
return;
}

let sub_result = match rule_name {
"inline_style" => Some(lint_for(part, "css")),
"inline_javascript" => Some(lint_for(part, "js")),
Expand All @@ -213,14 +220,15 @@ fn format_or_lint_for_inline_scripts<R: RuleType, O: Results>(
let mut new_part = String::from(part);

// Skip format if AutoCorrect disabled
if results.is_enabled() {
if results.is_enabled() && is_enable_context {
let sub_result = match rule_name {
"inline_style" => Some(format_for(part, "css")),
"inline_javascript" => Some(format_for(part, "js")),
"codeblock" => {
// WARNING: nested codeblock, when call format_for again.
// Because codeblock.data has wrap chars, this make overflowed its stack.
let mut codeblock = Codeblock::from_pair(pair);

let mut result = format_for(&codeblock.code, &codeblock.lang);
codeblock.update_data(&result.out);
result.out = codeblock.data;
Expand Down
34 changes: 34 additions & 0 deletions autocorrect/src/code/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ struct MarkdownParser;

#[cfg(test)]
mod tests {
use crate::config::SeverityMode;

use super::*;
use indoc::indoc;
use pretty_assertions::assert_eq;
Expand Down Expand Up @@ -356,4 +358,36 @@ mod tests {

assert_eq!(expected, format_markdown(raw).out);
}

#[test]
fn test_disable_context_codeblock() {
use std::collections::HashMap;

let last_mode = *crate::config::Config::current()
.context
.get("codeblock")
.unwrap();

crate::config::CURRENT_CONFIG.write().unwrap().context = map! {
"codeblock".to_string() => SeverityMode::Off,
};

let raw = indoc! {r###"
```rust
// 这段应该ignore掉
```
"###};

let expected = indoc! {r###"
```rust
// 这段应该ignore掉
```
"###};

assert_eq!(expected, format_for(raw, "markdown").to_string());

crate::config::CURRENT_CONFIG.write().unwrap().context = map! {
"codeblock".to_string() => last_mode,
};
}
}
36 changes: 20 additions & 16 deletions autocorrect/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ use std::{
collections::HashMap,
fs,
path::Path,
sync::{Arc, RwLock, RwLockReadGuard},
rc::Rc,
sync::{RwLock, RwLockReadGuard},
};

use crate::serde_any;
Expand All @@ -20,7 +21,8 @@ lazy_static! {
env!("CARGO_MANIFEST_DIR"),
"/.autocorrectrc.default"
));
static ref CURRENT_CONFIG: RwLock<Config> = RwLock::new(Config::from_str(&CONFIG_STR).unwrap());
pub(crate) static ref CURRENT_CONFIG: RwLock<Config> =
RwLock::new(Config::from_str(&CONFIG_STR).unwrap());
}

pub trait ConfigFileTypes {
Expand All @@ -45,7 +47,7 @@ impl ConfigFileTypes for HashMap<String, String> {
}
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[derive(Deserialize, Serialize, Default, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Config {
#[serde(default)]
Expand All @@ -58,17 +60,8 @@ pub struct Config {
// Addition file types map, high priority than default
#[serde(default)]
pub file_types: HashMap<String, String>,
}

impl Default for Config {
fn default() -> Self {
Config {
rules: HashMap::new(),
text_rules: HashMap::new(),
spellcheck: SpellcheckConfig::default(),
file_types: HashMap::new(),
}
}
#[serde(default)]
pub context: HashMap<String, SeverityMode>,
}

pub fn load_file(config_file: &str) -> Result<Config, Error> {
Expand Down Expand Up @@ -132,8 +125,8 @@ impl From<std::string::String> for Error {
}

impl Config {
pub fn current() -> Arc<RwLockReadGuard<'static, Config>> {
Arc::new(CURRENT_CONFIG.read().unwrap())
pub fn current() -> Rc<RwLockReadGuard<'static, Config>> {
Rc::new(CURRENT_CONFIG.read().unwrap())
}

pub fn get_file_type(&self, ext: &str) -> Option<&str> {
Expand Down Expand Up @@ -187,6 +180,15 @@ impl Config {

Ok(self.clone())
}

/// Check is enable format in context
pub fn is_enabled_context(&self, name: &str) -> bool {
if let Some(mode) = self.context.get(name) {
return *mode != SeverityMode::Off;
}

false
}
}

// Setup config for test for load tests/.autocorrectrc.test
Expand Down Expand Up @@ -366,6 +368,7 @@ mod tests {
words: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
..Default::default()
},
..Default::default()
};

let config1 = Config {
Expand All @@ -384,6 +387,7 @@ mod tests {
words: vec!["foo1".to_string(), "bar1".to_string()],
..Default::default()
},
..Default::default()
};

config.merge(&config1).unwrap();
Expand Down
3 changes: 2 additions & 1 deletion autocorrect/src/config/severity.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize, Serializer};

#[derive(PartialEq, Eq, Clone, Debug)]
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum SeverityMode {
#[default]
Off = 0,
Error = 1,
Warning = 2,
Expand Down
2 changes: 1 addition & 1 deletion autocorrect/src/keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl Node {
c
};

while node.children.get(&c).is_none() {
while !node.children.contains_key(&c) {
if node.fail.is_none() {
node = self;
break;
Expand Down
2 changes: 1 addition & 1 deletion autocorrect/src/result/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) fn crate_test_lint_results() -> Vec<LintResult> {
let mut lint_result = LintResult::new("hello你好.\n这是第2行");
lint_result.line = 10;
lint_result.col = 12;
lint_result.filepath = "./test/foo/bar.rs".to_owned();
lint_result.filepath = "./test/foo/bar.rs".to_string();
lint_result.push(LineResult {
line: 1,
col: 1,
Expand Down
Loading

0 comments on commit 01ef1e2

Please sign in to comment.