From add0a9dfcd4716447517e480686bfe65dbfa8ca3 Mon Sep 17 00:00:00 2001 From: Johannes Altmanninger Date: Mon, 16 Sep 2024 21:18:54 +0200 Subject: [PATCH] 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. --- src/bin/fish_indent.rs | 41 +++++++++++++++++------------------------ 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/src/bin/fish_indent.rs b/src/bin/fish_indent.rs index 141e3637f..af572ebe9 100644 --- a/src/bin/fish_indent.rs +++ b/src/bin/fish_indent.rs @@ -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 @@ enum OutputType { } } 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,29 +972,22 @@ enum OutputType { 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()); + if output_wtext != src { + match fs::File::create(OsStr::from_bytes(&wcs2string(output_location))) { + Ok(mut file) => { + let _ = file.write_all(&wcs2string(&output_wtext)); + } + Err(err) => { + eprintf!( + "%s", + wgettext_fmt!( + "Opening \"%s\" failed: %s\n", + 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(); } } }