From a17e53d87bc6da0a638ea40c055c074a1523c5ef Mon Sep 17 00:00:00 2001 From: Gustavo Noronha Silva Date: Mon, 14 Nov 2022 08:55:48 -0300 Subject: [PATCH 1/3] Protect against overwriting external changes When saving, check that the file has not changed before our last known save before writing the file. Only overwrite external changes if asked to force. --- helix-term/tests/test/commands.rs | 2 +- helix-term/tests/test/helpers.rs | 6 ++++++ helix-term/tests/test/write.rs | 36 +++++++++++++++++++++++++++++-- helix-view/src/document.rs | 24 ++++++++++++++++++++- 4 files changed, 64 insertions(+), 4 deletions(-) diff --git a/helix-term/tests/test/commands.rs b/helix-term/tests/test/commands.rs index e78e6c9f9964..2a5e12b85a12 100644 --- a/helix-term/tests/test/commands.rs +++ b/helix-term/tests/test/commands.rs @@ -67,7 +67,7 @@ async fn test_buffer_close_concurrent() -> anyhow::Result<()> { const RANGE: RangeInclusive = 1..=1000; for i in RANGE { - let cmd = format!("%c{}:w", i); + let cmd = format!("%c{}:w!", i); command.push_str(&cmd); } diff --git a/helix-term/tests/test/helpers.rs b/helix-term/tests/test/helpers.rs index 2c5043d68cf2..266c778af604 100644 --- a/helix-term/tests/test/helpers.rs +++ b/helix-term/tests/test/helpers.rs @@ -322,6 +322,12 @@ impl AppBuilder { } } +pub async fn run_event_loop_to_idle(app: &mut Application) { + let (_, rx) = tokio::sync::mpsc::unbounded_channel(); + let mut rx_stream = UnboundedReceiverStream::new(rx); + app.event_loop_until_idle(&mut rx_stream).await; +} + pub fn assert_file_has_content(file: &mut File, content: &str) -> anyhow::Result<()> { file.flush()?; file.sync_all()?; diff --git a/helix-term/tests/test/write.rs b/helix-term/tests/test/write.rs index d0128edcaddf..7eca93167f6c 100644 --- a/helix-term/tests/test/write.rs +++ b/helix-term/tests/test/write.rs @@ -1,5 +1,5 @@ use std::{ - io::{Read, Write}, + io::{Read, Seek, SeekFrom, Write}, ops::RangeInclusive, }; @@ -37,6 +37,38 @@ async fn test_write() -> anyhow::Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread")] +async fn test_overwrite_protection() -> anyhow::Result<()> { + let mut file = tempfile::NamedTempFile::new()?; + let mut app = helpers::AppBuilder::new() + .with_file(file.path(), None) + .build()?; + + helpers::run_event_loop_to_idle(&mut app).await; + + file.as_file_mut() + .write_all(helpers::platform_line("extremely important content").as_bytes())?; + + file.as_file_mut().flush()?; + file.as_file_mut().sync_all()?; + + test_key_sequence(&mut app, Some(":x"), None, false).await?; + + file.as_file_mut().flush()?; + file.as_file_mut().sync_all()?; + + file.seek(SeekFrom::Start(0))?; + let mut file_content = String::new(); + file.as_file_mut().read_to_string(&mut file_content)?; + + assert_eq!( + helpers::platform_line("extremely important content"), + file_content + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread")] async fn test_write_quit() -> anyhow::Result<()> { let mut file = tempfile::NamedTempFile::new()?; @@ -76,7 +108,7 @@ async fn test_write_concurrent() -> anyhow::Result<()> { .build()?; for i in RANGE { - let cmd = format!("%c{}:w", i); + let cmd = format!("%c{}:w!", i); command.push_str(&cmd); } diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 087085283391..a67c83d4dfb4 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -13,6 +13,7 @@ use std::future::Future; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; +use std::time::SystemTime; use helix_core::{ encoding, @@ -127,6 +128,10 @@ pub struct Document { pub savepoint: Option, + // Last time we wrote to the file. This will carry the time the file was last opened if there + // were no saves. + last_saved_time: SystemTime, + last_saved_revision: usize, version: i32, // should be usize? pub(crate) modified_since_accessed: bool, @@ -368,6 +373,7 @@ impl Document { version: 0, history: Cell::new(History::default()), savepoint: None, + last_saved_time: SystemTime::now(), last_saved_revision: 0, modified_since_accessed: false, language_server: None, @@ -557,9 +563,11 @@ impl Document { let encoding = self.encoding; + let last_saved_time = self.last_saved_time; + // We encode the file according to the `Document`'s encoding. let future = async move { - use tokio::fs::File; + use tokio::{fs, fs::File}; if let Some(parent) = path.parent() { // TODO: display a prompt asking the user if the directories should be created if !parent.exists() { @@ -571,6 +579,17 @@ impl Document { } } + // Protect against overwriting changes made externally + if !force { + if let Ok(metadata) = fs::metadata(&path).await { + if let Ok(mtime) = metadata.modified() { + if last_saved_time < mtime { + bail!("file modified by an external process, use :w! to force"); + } + } + } + } + let mut file = File::create(&path).await?; to_writer(&mut file, encoding, &text).await?; @@ -644,6 +663,8 @@ impl Document { self.append_changes_to_history(view.id); self.reset_modified(); + self.last_saved_time = SystemTime::now(); + self.detect_indent_and_line_ending(); Ok(()) @@ -979,6 +1000,7 @@ impl Document { rev ); self.last_saved_revision = rev; + self.last_saved_time = SystemTime::now(); } /// Get the document's latest saved revision. From 0343d92b718d266e27abf51325708f67a85ef1b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Delafargue?= Date: Fri, 3 Feb 2023 14:48:21 +0100 Subject: [PATCH 2/3] Make overwrite protection configurable + small fixes Co-authored-by: LeoniePhiline <22329650+LeoniePhiline@users.noreply.github.com> Co-authored-by: Pascal Kuthe --- book/src/configuration.md | 1 + helix-term/tests/test/helpers.rs | 2 +- helix-term/tests/test/write.rs | 2 +- helix-view/src/document.rs | 7 +++++-- helix-view/src/editor.rs | 3 +++ 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/book/src/configuration.md b/book/src/configuration.md index 7514a3d0fcc3..20723ce39b6b 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -57,6 +57,7 @@ on unix operating systems. | `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file. | `[]` | | `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` | | `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` | +| `prevent-external-modifications` | Prevent saving a file that has been modified from the outside, based on its last modification date (`mtime`). Disabling this check can be useful on systems where `mtime` values are unreliable | `true` | ### `[editor.statusline]` Section diff --git a/helix-term/tests/test/helpers.rs b/helix-term/tests/test/helpers.rs index 173fd1bd3e38..fb12ef12cff2 100644 --- a/helix-term/tests/test/helpers.rs +++ b/helix-term/tests/test/helpers.rs @@ -319,7 +319,7 @@ impl AppBuilder { } } -pub async fn run_event_loop_to_idle(app: &mut Application) { +pub async fn run_event_loop_until_idle(app: &mut Application) { let (_, rx) = tokio::sync::mpsc::unbounded_channel(); let mut rx_stream = UnboundedReceiverStream::new(rx); app.event_loop_until_idle(&mut rx_stream).await; diff --git a/helix-term/tests/test/write.rs b/helix-term/tests/test/write.rs index 7eca93167f6c..dd1a21027769 100644 --- a/helix-term/tests/test/write.rs +++ b/helix-term/tests/test/write.rs @@ -44,7 +44,7 @@ async fn test_overwrite_protection() -> anyhow::Result<()> { .with_file(file.path(), None) .build()?; - helpers::run_event_loop_to_idle(&mut app).await; + helpers::run_event_loop_until_idle(&mut app).await; file.as_file_mut() .write_all(helpers::platform_line("extremely important content").as_bytes())?; diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 6fcc56a78bef..c9d54aef49d6 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -165,6 +165,7 @@ impl fmt::Debug for Document { .field("changes", &self.changes) .field("old_state", &self.old_state) // .field("history", &self.history) + .field("last_saved_time", &self.last_saved_time) .field("last_saved_revision", &self.last_saved_revision) .field("version", &self.version) .field("modified_since_accessed", &self.modified_since_accessed) @@ -585,6 +586,8 @@ impl Document { let last_saved_time = self.last_saved_time; + let prevent_external_modifications = self.config.load().prevent_external_modifications; + // We encode the file according to the `Document`'s encoding. let future = async move { use tokio::{fs, fs::File}; @@ -600,11 +603,11 @@ impl Document { } // Protect against overwriting changes made externally - if !force { + if !force && prevent_external_modifications { if let Ok(metadata) = fs::metadata(&path).await { if let Ok(mtime) = metadata.modified() { if last_saved_time < mtime { - bail!("file modified by an external process, use :w! to force"); + bail!("file modified by an external process, use :w! to overwrite"); } } } diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 042f5bdb4269..3dcea0155711 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -274,6 +274,8 @@ pub struct Config { /// Whether to color modes with different colors. Defaults to `false`. pub color_modes: bool, pub soft_wrap: SoftWrap, + /// Whether to check for external modifications upon saving. Defaults to `true`. + pub prevent_external_modifications: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -764,6 +766,7 @@ impl Default for Config { indent_guides: IndentGuidesConfig::default(), color_modes: false, soft_wrap: SoftWrap::default(), + prevent_external_modifications: true, } } } From f64ff107bc9d1802d67f8ea07c575f1d294ef9ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Delafargue?= Date: Mon, 6 Feb 2023 09:00:51 +0100 Subject: [PATCH 3/3] remove config field for overwrite protection After discussing it further, it's best to have it done every time, a couple options can be explored to reduce false positives in the future. --- book/src/configuration.md | 1 - helix-view/src/document.rs | 4 +--- helix-view/src/editor.rs | 3 --- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/book/src/configuration.md b/book/src/configuration.md index 20723ce39b6b..7514a3d0fcc3 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -57,7 +57,6 @@ on unix operating systems. | `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file. | `[]` | | `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` | | `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` | -| `prevent-external-modifications` | Prevent saving a file that has been modified from the outside, based on its last modification date (`mtime`). Disabling this check can be useful on systems where `mtime` values are unreliable | `true` | ### `[editor.statusline]` Section diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index c9d54aef49d6..d308d013ff5f 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -586,8 +586,6 @@ impl Document { let last_saved_time = self.last_saved_time; - let prevent_external_modifications = self.config.load().prevent_external_modifications; - // We encode the file according to the `Document`'s encoding. let future = async move { use tokio::{fs, fs::File}; @@ -603,7 +601,7 @@ impl Document { } // Protect against overwriting changes made externally - if !force && prevent_external_modifications { + if !force { if let Ok(metadata) = fs::metadata(&path).await { if let Ok(mtime) = metadata.modified() { if last_saved_time < mtime { diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 3dcea0155711..042f5bdb4269 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -274,8 +274,6 @@ pub struct Config { /// Whether to color modes with different colors. Defaults to `false`. pub color_modes: bool, pub soft_wrap: SoftWrap, - /// Whether to check for external modifications upon saving. Defaults to `true`. - pub prevent_external_modifications: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -766,7 +764,6 @@ impl Default for Config { indent_guides: IndentGuidesConfig::default(), color_modes: false, soft_wrap: SoftWrap::default(), - prevent_external_modifications: true, } } }