Skip to content

Commit

Permalink
fix: do not mutate read-only files (#1155)
Browse files Browse the repository at this point in the history
* fix: do not mutate read-only files

fixes #1071
related #700

* support is_writable on windows

---------

Co-authored-by: Jake Runzer <jakerunzer@gmail.com>
  • Loading branch information
iloveitaly and coffee-cup authored Sep 17, 2024
1 parent afb5f45 commit cf46f86
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/nixpacks/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@ use anyhow::Result;
use ignore::WalkBuilder;
use std::{fs, io, path::Path};

#[cfg(unix)]
fn is_writable<P: AsRef<Path>>(path: P) -> io::Result<bool> {
use std::os::unix::fs::PermissionsExt;
let metadata = fs::metadata(path)?;
let permissions = metadata.permissions();
Ok(permissions.mode() & 0o200 != 0)
}

#[cfg(windows)]
fn is_writable<P: AsRef<Path>>(path: P) -> io::Result<bool> {
use std::os::windows::fs::MetadataExt;
let metadata = fs::metadata(path)?;
Ok(!metadata.file_attributes() & 1 != 0)
}

/// Copies a directory and all its contents to the destination path, recursively.
pub fn recursive_copy_dir<T: AsRef<Path>, Q: AsRef<Path>>(source: T, dest: Q) -> Result<()> {
let walker = WalkBuilder::new(&source)
Expand Down Expand Up @@ -30,9 +45,12 @@ pub fn recursive_copy_dir<T: AsRef<Path>, Q: AsRef<Path>>(source: T, dest: Q) ->
// copy files
else if file_type.is_file() {
fs::copy(from, &to)?;
// replace CRLF with LF
if let Ok(data) = fs::read_to_string(from) {
fs::write(&to, data.replace("\r\n", "\n"))?;

if is_writable(&to)? {
// replace CRLF with LF
if let Ok(data) = fs::read_to_string(from) {
fs::write(&to, data.replace("\r\n", "\n"))?;
}
}
}
}
Expand Down

0 comments on commit cf46f86

Please sign in to comment.