Skip to content

Commit

Permalink
add readonly test
Browse files Browse the repository at this point in the history
  • Loading branch information
kirawi committed Apr 11, 2024
1 parent 0adc9a8 commit ed77676
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 4 deletions.
37 changes: 37 additions & 0 deletions helix-term/tests/test/commands/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,43 @@ async fn test_symlink_write() -> anyhow::Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_symlink_write_fail() -> anyhow::Result<()> {
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(not(unix))]
use std::os::windows::fs::symlink_file as symlink;

let dir = tempfile::tempdir()?;

let file = helpers::new_readonly_tempfile_in_dir(&dir)?;
let symlink_path = dir.path().join("linked");
symlink(file.path(), &symlink_path)?;

let mut app = helpers::AppBuilder::new()
.with_file(&symlink_path, None)
.build()?;

test_key_sequence(
&mut app,
Some("ihello<esc>:wq<ret>"),
Some(&|app| {
let mut docs: Vec<_> = app.editor.documents().collect();
assert_eq!(1, docs.len());

let doc = docs.pop().unwrap();
assert_eq!(Some(&path::normalize(&symlink_path)), doc.path());
assert_eq!(&Severity::Error, app.editor.get_status().unwrap().1);
}),
false,
)
.await?;

assert!(symlink_path.is_symlink());

Ok(())
}

async fn edit_file_with_content(file_content: &[u8]) -> anyhow::Result<()> {
let mut file = tempfile::NamedTempFile::new()?;

Expand Down
12 changes: 12 additions & 0 deletions helix-term/tests/test/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,18 @@ pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
Ok(file)
}

/// Creates a new temporary file in the directory that is set to read only. Useful for
/// testing write failures.
pub fn new_readonly_tempfile_in_dir(
dir: impl AsRef<std::path::Path>,
) -> anyhow::Result<NamedTempFile> {
let mut file = tempfile::NamedTempFile::new_in(dir)?;
let metadata = file.as_file().metadata()?;
let mut perms = metadata.permissions();
perms.set_readonly(true);
file.as_file_mut().set_permissions(perms)?;
Ok(file)
}
pub struct AppBuilder {
args: Args,
config: Config,
Expand Down
8 changes: 4 additions & 4 deletions helix-view/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,16 +893,16 @@ impl Document {
}
}
}
let write_path = tokio::fs::read_link(&path)
.await
.unwrap_or_else(|_| path.clone());

if readonly(&path) {
if readonly(&write_path) {
bail!(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"Path is read only"
));
}
let write_path = tokio::fs::read_link(&path)
.await
.unwrap_or_else(|_| path.clone());
let backup = if path.exists() {
let path_ = write_path.clone();
// hacks: we use tempfile to handle the complex task of creating
Expand Down

0 comments on commit ed77676

Please sign in to comment.