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

feat: walk_dir function (finds all files in sub directories) #6530

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ path = "named-pipe-multi-client.rs"
[[example]]
name = "dump"
path = "dump.rs"

[[example]]
name = "walk"
path = "walk.rs"
11 changes: 11 additions & 0 deletions examples/walk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use std::error::Error;
use tokio::fs::walk_dir;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut rx = walk_dir("./").await?; // awaiting this function starts
while let Some(item) = rx.recv().await {
println!("{:?}", item);
}
Ok(())
}
3 changes: 3 additions & 0 deletions tokio/src/fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ pub use self::copy::copy;
mod try_exists;
pub use self::try_exists::try_exists;

mod walk_dir;
pub use self::walk_dir::walk_dir;

#[cfg(test)]
mod mocks;

Expand Down
40 changes: 40 additions & 0 deletions tokio/src/fs/walk_dir.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::path::PathBuf;

use crate::io;
use crate::sync::mpsc;
use crate::sync::mpsc::Receiver;

const WALKER_CHANNEL_BUFFER_SIZE: usize = 32;

/// Search for all files under that 'path' recursively, and send the file paths over the channel
/// # Example:
/// use tokio::fs::walk_dir;
/// let mut rx = walk_dir("./").await.unwrap();
/// while let Some(item) = rx.recv().await {
/// println!("{:?}", item);
/// }
pub async fn walk_dir(path: impl AsRef<str>) -> io::Result<Receiver<PathBuf>> {
let path = PathBuf::from(path.as_ref());

let (tx, rx) = mpsc::channel::<PathBuf>(WALKER_CHANNEL_BUFFER_SIZE);

crate::spawn(async move {
let mut dirs = Vec::<PathBuf>::with_capacity(1000);
dirs.push(path);

while let Some(dir) = dirs.pop() {
let mut ls = super::read_dir(dir).await?;

while let Ok(Some(item)) = ls.next_entry().await {
if item.metadata().await?.is_dir() {
dirs.push(item.path());
} else {
tx.send(item.path()).await.unwrap_or(());
}
}
}
Ok::<(), std::io::Error>(())
});

Ok(rx)
}
Loading