Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Get A List Of Directories In A Directory

Get a list of directories in a single directory (non-recursively) excluding hidden folders whose names start with a "."

Code

use std::path::PathBuf;
use std::io;
use std::fs::{self, DirEntry};

fn main() {
  let dir = PathBuf::from(".");
  match get_dirs_in_dir(&dir) {
    Ok(dirs) => {dbg!(dirs);},
    Err(e) => println!("{}", e)
  }
}

fn get_dirs_in_dir(dir: &PathBuf) -> io::Result<Vec<PathBuf>> {
  Result::from_iter(fs::read_dir(dir)?
    .map(|entry| {
      let entry = entry?;
      Ok(entry)
    })
    .filter_map(|entry: Result<DirEntry, io::Error>| {
      let path = entry.unwrap().path();
      if path.is_dir() {
        match path.file_name() {
          Some(file_name) =>  {
            if file_name.to_string_lossy().starts_with(".") {
              None 
            } else {
              Some(Ok(path))
            }
          },
          None => None
        }
      } else {
        None
      }
    })
  )
}

Results

[_active_nvim_run:8:18] dirs = [
    "./images",
    "./files_folder_1",
    "./site_folder",
    "./glob_test",
    "./audio",
    "./files",
    "./files_folder_2",
    "./create",
    "./recursive_test",
]