Skip to content

Commit

Permalink
refactor(server): vendor get_size function from fx_extra
Browse files Browse the repository at this point in the history
  • Loading branch information
orhun committed Dec 11, 2024
1 parent a5c3740 commit 84305fb
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
uts2ts = "0.4.1"
path-clean = "1.0.1"
fs_extra = "1.3.0"

[dependencies.config]
version = "0.14.0"
Expand Down
5 changes: 1 addition & 4 deletions src/paste.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,11 @@ impl Paste {
}

if let Some(max_dir_size) = config.server.max_upload_dir_size {
// The unwrap here should be fine as the max value of u64 will be within the limits
let file_size = u64::try_from(self.data.len()).unwrap_or_default();
let upload_dir = self.type_.get_path(&config.server.upload_path)?;
let current_size_of_upload_dir = fs_extra::dir::get_size(upload_dir)
let current_size_of_upload_dir = util::get_dir_size(&upload_dir)
.map_err(|_| error::ErrorInternalServerError("Internal server error occured"))?;

let expected_size_of_upload_dir = current_size_of_upload_dir.add(file_size);

if expected_size_of_upload_dir > max_dir_size {
return Err(error::ErrorInsufficientStorage(
"upload directory size limit exceeded",
Expand Down
25 changes: 25 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,31 @@ pub fn safe_path_join<B: AsRef<Path>, P: AsRef<Path>>(base: B, part: P) -> IoRes
Ok(new_path)
}

/// Returns the size of the directory at the given path.
///
/// This function is recursive, and will calculate the size of all files and directories.
/// If a symlink is encountered, the size of the symlink itself is counted, not its target.
///
/// Adopted from <https://docs.rs/fs_extra/latest/src/fs_extra/dir.rs.html>
pub fn get_dir_size(path: &Path) -> IoResult<u64> {
let path_metadata = path.symlink_metadata()?;
let mut size_in_bytes = 0;
if path_metadata.is_dir() {
for entry in std::fs::read_dir(&path)? {
let entry = entry?;
let entry_metadata = entry.metadata()?;
if entry_metadata.is_dir() {
size_in_bytes += get_dir_size(&entry.path())?;
} else {
size_in_bytes += entry_metadata.len();
}
}
} else {
size_in_bytes = path_metadata.len();
}
Ok(size_in_bytes)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 84305fb

Please sign in to comment.