Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add --no-swap flag #193

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
175 changes: 172 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ console = "0.15.7"
insta = "1.34.0"
ansi-to-html = "0.1.3"
regex-automata = "0.4.3"
rstest = "0.17.0"

[profile.release]
opt-level = 3
Expand Down
4 changes: 4 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ w - match full words only
/// use captured values like $1, $2, etc.
pub replace_with: String,

#[arg(long)]
/// Overwrite file in place instead of creating tmp file and swapping atomically
pub in_place: bool,

/// The path to file(s). This is optional - sd can also read from STDIN.
///
/// Note: sd modifies files in-place by default. See documentation for
Expand Down
17 changes: 16 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,12 @@ fn try_main() -> Result<()> {
for (source, replaced) in sources.iter().zip(replaced) {
match source {
Source::File(path) => {
if let Err(e) = write_with_temp(path, &replaced) {
let result = if !options.in_place {
write_with_temp(path, &replaced)
} else {
write_in_place(path, &replaced)
};
if let Err(e) = result {
failed_jobs.push((path.to_owned(), e));
}
}
Expand Down Expand Up @@ -130,3 +135,13 @@ fn write_with_temp(path: &PathBuf, data: &[u8]) -> Result<()> {

Ok(())
}

fn write_in_place(path: &PathBuf, data: &[u8]) -> Result<()> {
let path = fs::canonicalize(path)?;

let mut source = fs::OpenOptions::new().write(true).open(path)?;
source.write_all(&data)?;
source.set_len(data.len() as u64)?;

Ok(())
}