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)] #![allow(clippy::uninlined_format_args)]
use std::ffi::{CString, OsStr}; use std::ffi::{CString, OsStr};
use std::fs::OpenOptions; use std::fs;
use std::io::{stdin, Read, Write}; use std::io::{stdin, Read, Write};
use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStrExt;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
@ -889,7 +889,7 @@ fn throwing_main() -> i32 {
} }
} else { } else {
let arg = args[i]; 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) => { Ok(file) => {
match read_file(file) { match read_file(file) {
Ok(s) => src = s, Ok(s) => src = s,
@ -972,29 +972,22 @@ fn throwing_main() -> i32 {
colored_output = no_colorize(&output_wtext); colored_output = no_colorize(&output_wtext);
} }
OutputType::File => { OutputType::File => {
match OpenOptions::new() if output_wtext != src {
.write(true) match fs::File::create(OsStr::from_bytes(&wcs2string(output_location))) {
.open(OsStr::from_bytes(&wcs2string(output_location))) Ok(mut file) => {
{ let _ = file.write_all(&wcs2string(&output_wtext));
Ok(mut file) => { }
// If the output is the same as the input, don't write it. Err(err) => {
if output_wtext != src { eprintf!(
let text = wcs2string(&output_wtext); "%s",
let _ = file.write_all(&text); wgettext_fmt!(
// Truncate the file in case it shrunk. "Opening \"%s\" failed: %s\n",
let _ = file.set_len(text.len().try_into().unwrap()); output_location,
err.to_string()
)
);
return STATUS_CMD_ERROR.unwrap();
} }
}
Err(err) => {
eprintf!(
"%s",
wgettext_fmt!(
"Opening \"%s\" failed: %s\n",
output_location,
err.to_string()
)
);
return STATUS_CMD_ERROR.unwrap();
} }
} }
} }