fish_indent: clean up file writing logic

Fix 7308dbc7a (fish_indent: Prevent overwriting file with identical content,
2024-07-21) in a different way by passing O_TRUNC again.
If we don't want regressions we could use code review.
This commit is contained in:
Johannes Altmanninger 2024-09-16 21:18:54 +02:00
parent e27f4a3744
commit add0a9dfcd

View file

@ -7,7 +7,7 @@
#![allow(clippy::uninlined_format_args)]
use std::ffi::{CString, OsStr};
use std::fs::OpenOptions;
use std::fs;
use std::io::{stdin, Read, Write};
use std::os::unix::ffi::OsStrExt;
use std::sync::atomic::Ordering;
@ -889,7 +889,7 @@ fn throwing_main() -> i32 {
}
} else {
let arg = args[i];
match std::fs::File::open(OsStr::from_bytes(&wcs2string(arg))) {
match fs::File::open(OsStr::from_bytes(&wcs2string(arg))) {
Ok(file) => {
match read_file(file) {
Ok(s) => src = s,
@ -972,18 +972,10 @@ fn throwing_main() -> i32 {
colored_output = no_colorize(&output_wtext);
}
OutputType::File => {
match OpenOptions::new()
.write(true)
.open(OsStr::from_bytes(&wcs2string(output_location)))
{
Ok(mut file) => {
// If the output is the same as the input, don't write it.
if output_wtext != src {
let text = wcs2string(&output_wtext);
let _ = file.write_all(&text);
// Truncate the file in case it shrunk.
let _ = file.set_len(text.len().try_into().unwrap());
}
match fs::File::create(OsStr::from_bytes(&wcs2string(output_location))) {
Ok(mut file) => {
let _ = file.write_all(&wcs2string(&output_wtext));
}
Err(err) => {
eprintf!(
@ -998,6 +990,7 @@ fn throwing_main() -> i32 {
}
}
}
}
OutputType::Ansi => {
colored_output = colorize(&output_wtext, &colors, EnvStack::globals());
}