devMe
devMe

Reputation: 363

How to get the current dir in walkdir without using std::env::curren_dir

so i've been working on these little project and i want to get the current folders files and directories. i use walkdir crate and i'm be able to get the files via providing relative but i can't get the files in the current directory i'm hoping to use '.' for the current directory like use in code . and like vim . but i can't figure out how to do this correctly is there any way good way to do this or crate to achive this?.

use walkdir::{WalkDir,DirEntry};
use std::error::Error;
use std::env::current_dir;

fn is_hidden(entry: &DirEntry) -> bool {

    entry.file_name()
        .to_str()
        .map(|s| s.starts_with("."))
        .unwrap_or(false)
}

pub fn get_dir_files(mut path: String)->Result<(),Box<dyn Error>>{

    if path == "." {
       let pathtwo = current_dir().unwrap();
        path = pathtwo.to_str().unwrap().to_owned();        
        println!("{}",pathtwo.display());
    }
    let walker = WalkDir::new(path).into_iter();
    for entry in walker.filter_entry(|e| !is_hidden(e)) {

        println!("{}",entry?.path().display());
    }

    Ok(())
}

Upvotes: 0

Views: 46

Answers (1)

Timsib Adnap
Timsib Adnap

Reputation: 542

The implementation of is_hidden ignores the . (i.e. current directory) as it starts with .. To fix this we can add a condition to the is_hidden function to check if it is the current directory. Like this

use walkdir::{DirEntry, WalkDir};

fn is_hidden(entry: &DirEntry) -> bool {
    entry.path().to_str().unwrap() != "." // Add condition to check current working directory
        && entry
            .file_name()
            .to_str()
            .map(|s| s.starts_with("."))
            .unwrap_or(false)
}

pub fn get_dir_files(path: &str) {
    let walker = WalkDir::new(path).into_iter();

    for entry in walker.filter_entry(|e| !is_hidden(e)) {
        println!("{}", entry.unwrap().path().display());
    }
}

fn main() {
    get_dir_files(".");
}

Upvotes: 0

Related Questions