Skip to content

Commit

Permalink
Avoid rewriting sorted file (#68)
Browse files Browse the repository at this point in the history
… and improve CRLF logic.
  • Loading branch information
ssrlive authored Oct 19, 2024
1 parent 55ec890 commit 4fc090b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.VSCodeCounter/
/target
**/*.rs.bk

Expand Down
26 changes: 19 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,15 @@ fn check_toml(path: &str, matches: &ArgMatches, config: &Config) -> IoResult<boo
let toml_raw = read_to_string(&path)
.map_err(|_| format!("No file found at: {}", path.display()))?;

let crlf = toml_raw.contains("\r\n");

let mut sorted = sort::sort_toml(
&toml_raw,
sort::MATCHER,
flag_set("grouped", matches),
&config.table_order,
);
let mut sorted_str = sorted.to_string();
let is_sorted = toml_raw == sorted_str;

let is_formatted =
// if no-format is not found apply formatting
Expand All @@ -85,7 +86,7 @@ fn check_toml(path: &str, matches: &ArgMatches, config: &Config) -> IoResult<boo
true
};

if config.crlf && !sorted_str.contains("\r\n") {
if (config.crlf || crlf) && !sorted_str.contains("\r\n") {
sorted_str = sorted_str.replace('\n', "\r\n")
}

Expand All @@ -94,6 +95,7 @@ fn check_toml(path: &str, matches: &ArgMatches, config: &Config) -> IoResult<boo
return Ok(true);
}

let is_sorted = toml_raw == sorted_str;
if flag_set("check", matches) {
if !is_sorted {
write_red(
Expand All @@ -112,11 +114,21 @@ fn check_toml(path: &str, matches: &ArgMatches, config: &Config) -> IoResult<boo
return Ok(is_sorted && is_formatted);
}

write_file(&path, &sorted_str)?;
write_green(
"Finished: ",
format!("Cargo.toml for {:?} has been rewritten", krate.to_string_lossy()),
)?;
if !is_sorted {
write_file(&path, &sorted_str)?;
write_green(
"Finished: ",
format!("Cargo.toml for {:?} has been rewritten", krate.to_string_lossy()),
)?;
} else {
write_green(
"Finished: ",
format!(
"Cargo.toml for {} is sorted already, no changes made",
krate.to_string_lossy()
),
)?;
}

Ok(true)
}
Expand Down

0 comments on commit 4fc090b

Please sign in to comment.