mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-06-06 13:53:54 +02:00
feat(fs): add the size method to get the size of a file or directory (#2095)
This commit is contained in:
@@ -897,6 +897,55 @@ pub fn exists<R: Runtime>(
|
||||
Ok(resolved_path.exists())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn size<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
global_scope: GlobalScope<Entry>,
|
||||
command_scope: CommandScope<Entry>,
|
||||
path: SafeFilePath,
|
||||
options: Option<BaseOptions>,
|
||||
) -> CommandResult<u64> {
|
||||
let resolved_path = resolve_path(
|
||||
&webview,
|
||||
&global_scope,
|
||||
&command_scope,
|
||||
path,
|
||||
options.as_ref().and_then(|o| o.base_dir),
|
||||
)?;
|
||||
|
||||
let metadata = resolved_path.metadata()?;
|
||||
|
||||
if metadata.is_file() {
|
||||
Ok(metadata.len())
|
||||
} else {
|
||||
let size = get_dir_size(&resolved_path).map_err(|e| {
|
||||
format!(
|
||||
"failed to get size at path: {} with error: {e}",
|
||||
resolved_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(size)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_dir_size(path: &PathBuf) -> CommandResult<u64> {
|
||||
let mut size = 0;
|
||||
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let metadata = entry.metadata()?;
|
||||
|
||||
if metadata.is_file() {
|
||||
size += metadata.len();
|
||||
} else if metadata.is_dir() {
|
||||
size += get_dir_size(&entry.path())?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub fn resolve_file<R: Runtime>(
|
||||
webview: &Webview<R>,
|
||||
|
||||
@@ -417,6 +417,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
|
||||
commands::write_file,
|
||||
commands::write_text_file,
|
||||
commands::exists,
|
||||
commands::size,
|
||||
#[cfg(feature = "watch")]
|
||||
watcher::watch,
|
||||
#[cfg(feature = "watch")]
|
||||
|
||||
Reference in New Issue
Block a user