walkdown 0.1.2

walking down the directory tree
Documentation
/*
walkdown - Simple recursive directory walker

Written by Radim Kolar <hsn@sendmail.cz> 2025
https://gitlab.com/hsn10/walkdown

This is free and unencumbered software released into the public domain.
For more information, please refer to <https://unlicense.org/>

CC0: This work has been marked as dedicated to the public domain.
For more information, please refer to <https://creativecommons.org/public-domain/cc0/>

SPDX-License-Identifier: Unlicense OR CC0-1.0
*/

#![forbid(unsafe_code)]
#![forbid(missing_docs)]

//! Directory walker helper

use std::path::Path;
use std::path::PathBuf;

/**
   Walking down the directory structure.

   Walks down directory structure, executing task in each directory.

   For convience directory is changed to task directory before execution
   and full path is passed to task as argument.
*/
pub fn walkdown(
   start: impl AsRef<Path>,
   task: &mut impl FnMut(PathBuf) -> std::io::Result<()>,
) -> std::io::Result<()> {
   // check if requested start directory exists
   let start_dir = start.as_ref().to_path_buf();
   if !start_dir.is_dir() {
      return Err(std::io::Error::new(
         std::io::ErrorKind::NotFound,
         format!(
            "The directory '{}' does not exist or is not a directory.",
            start_dir.display()
         ),
      ));
   }

   // save original directory before we start to do anything
   let original_dir = std::env::current_dir()?;

   // change directory to starting point
   std::env::set_current_dir(&start_dir)?;

   // remember full path to our starting point
   let base_dir = std::env::current_dir()?;

   // run task there
   task(base_dir.clone())?;

   for entry in std::fs::read_dir(".")? {
      let entry = entry?;
      let path = entry.path();
      if path.is_dir() {
         walkdown(&path, task)?; // Recurse into subdirectory
      }
   }
   std::env::set_current_dir(&original_dir)?;

   Ok(())
}