Skip to content

Commit

Permalink
Merge pull request chmln#115 from SimplyDanny/follow-symlink-when-wri…
Browse files Browse the repository at this point in the history
…ting

Fix chmln#94: Do not replace symlink with output file
  • Loading branch information
chmln authored May 6, 2021
2 parents 9ab3372 + 39e8b8f commit f0e3961
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/replacer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{utils, Error, Result};
use regex::bytes::Regex;
use std::{fs::File, io::prelude::*, path::Path};
use std::{fs, fs::File, io::prelude::*, path::Path};

pub(crate) struct Replacer {
regex: Regex,
Expand Down Expand Up @@ -132,7 +132,7 @@ impl Replacer {
}

let source = File::open(path)?;
let meta = source.metadata()?;
let meta = fs::metadata(path)?;
let mmap_source = unsafe { Mmap::map(&source)? };
let replaced = self.replace(&mmap_source);

Expand All @@ -153,7 +153,7 @@ impl Replacer {
drop(mmap_source);
drop(source);

target.persist(path)?;
target.persist(fs::canonicalize(path)?)?;
Ok(())
}
}
Expand Down
32 changes: 32 additions & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ mod cli {
assert_eq!(content, std::fs::read_to_string(path).unwrap());
}

fn create_soft_link<P: AsRef<std::path::Path>>(
src: &P,
dst: &P,
) -> Result<()> {
#[cfg(target_family = "unix")]
std::os::unix::fs::symlink(src, dst)?;
#[cfg(target_family = "windows")]
std::os::windows::fs::symlink_file(src, dst)?;

Ok(())
}

#[test]
fn in_place() -> Result<()> {
let mut file = tempfile::NamedTempFile::new()?;
Expand Down Expand Up @@ -41,6 +53,26 @@ mod cli {
Ok(())
}

#[test]
fn in_place_following_symlink() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path();
let file = path.join("file");
let link = path.join("link");

create_soft_link(&file, &link)?;
std::fs::write(&file, "abc123def")?;

sd().args(&["abc\\d+", "", link.to_str().unwrap()])
.assert()
.success();

assert_file(&file.to_path_buf(), "def");
assert!(std::fs::symlink_metadata(link)?.file_type().is_symlink());

Ok(())
}

#[test]
fn replace_into_stdout() -> Result<()> {
let mut file = tempfile::NamedTempFile::new()?;
Expand Down

0 comments on commit f0e3961

Please sign in to comment.