Skip to content

Commit

Permalink
fix: fix newline character different in windows
Browse files Browse the repository at this point in the history
  • Loading branch information
He1pa committed Sep 22, 2023
1 parent ad93bae commit d866f36
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
30 changes: 27 additions & 3 deletions kclvm/tools/src/fix/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ pub fn diag_to_suggestion(
Ok(suggestions)
}

fn is_newline_at_index(s: &str, index: usize) -> bool {
let length = s.len();

if index >= length {
return false;
}

let bytes = s.as_bytes();

if bytes[index] == b'\n' {
return true;
}
#[cfg(target_os = "windows")]
if bytes[index] == b'\r' && index + 1 < length && bytes[index + 1] == b'\n' {
return true;
}

false
}

pub(crate) fn text_range(text: &str, range: &KCLRange) -> anyhow::Result<Range<usize>, Error> {
let mut lines_length = vec![];
let lines_text: Vec<&str> = text.split('\n').collect();
Expand All @@ -105,11 +125,15 @@ pub(crate) fn text_range(text: &str, range: &KCLRange) -> anyhow::Result<Range<u
lines_length.get(range.0.line as usize - 1).unwrap() + range.0.column.unwrap_or(0) as usize;
let mut end =
lines_length.get(range.1.line as usize - 1).unwrap() + range.1.column.unwrap_or(0) as usize;
if let Some(ch) = text.chars().nth(end) {
if ch == '\n' {
end += 1;

if is_newline_at_index(text, end) {
if cfg!(windows) {
end += "\r\n".len()
} else {
end += "\n".len()
}
}

Ok(Range { start, end })
}

Expand Down
3 changes: 3 additions & 0 deletions kclvm/tools/src/fix/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ fn test_lint() {
match fix(diags) {
Ok(_) => {
let src = fs::read_to_string("./src/fix/test_data/fix_import.k").unwrap();
#[cfg(target_os = "windows")]
assert_eq!(src, "import math\r\n\r\na = math.pow(1, 1)".to_string());
#[cfg(not(target_os = "windows"))]
assert_eq!(src, "import math\n\na = math.pow(1, 1)".to_string());
fs::write(
"./src/fix/test_data/fix_import.k",
Expand Down

0 comments on commit d866f36

Please sign in to comment.