Skip to content

Commit

Permalink
Fix clippy warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
huacnlee committed Jun 20, 2024
1 parent 460cf50 commit fd063d3
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 65 deletions.
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;
}
20 changes: 5 additions & 15 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 Down Expand Up @@ -45,7 +46,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 @@ -60,17 +61,6 @@ pub struct Config {
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(),
}
}
}

pub fn load_file(config_file: &str) -> Result<Config, Error> {
let config_path = Path::new(config_file);
if !Path::exists(config_path) {
Expand Down Expand Up @@ -132,8 +122,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
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
11 changes: 3 additions & 8 deletions autocorrect/src/result/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,15 @@ use serde_repr::*;

use crate::config::toggle;

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Eq, Debug, Clone, Copy)]
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Eq, Debug, Default, Clone, Copy)]
#[repr(u8)]
pub enum Severity {
#[default]
Pass = 0,
Error = 1,
Warning = 2,
}

impl Default for Severity {
fn default() -> Self {
Severity::Pass
}
}

impl Severity {
pub fn is_error(&self) -> bool {
self == &Severity::Error
Expand Down Expand Up @@ -146,7 +141,7 @@ impl Results for FormatResult {

fn error(&mut self, err: &str) {
// Revert out to raw when has error, make sure return raw value.
self.out = self.raw.clone();
self.out = String::from(&self.raw);
self.error = String::from(err);
}

Expand Down
3 changes: 1 addition & 2 deletions autocorrect/src/result/rdjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ pub(crate) fn to_rdjson_diagnostics(lint_result: &LintResult) -> Vec<String> {
pub fn to_lint_results_rdjson(lint_results: Vec<LintResult>) -> String {
let diagnostics = lint_results
.iter()
.map(|r| to_rdjson_diagnostics(r))
.flatten()
.flat_map(to_rdjson_diagnostics)
.collect::<Vec<_>>()
.join(",");
format!(
Expand Down
4 changes: 2 additions & 2 deletions autocorrect/src/rule/fullwidth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ lazy_static! {
}

// fullwidth correct punctuations near the CJK chars
pub fn format<'h>(text: &'h str) -> String {
let out = PUNCTUATION_WITH_LEFT_CJK_RE.replace_all(&text, |cap: &regex::Captures| {
pub fn format(text: &str) -> String {
let out = PUNCTUATION_WITH_LEFT_CJK_RE.replace_all(text, |cap: &regex::Captures| {
fullwidth_replace_part(&cap[0])
});

Expand Down

0 comments on commit fd063d3

Please sign in to comment.