walkup 1.0.2

Finds a file by walking up the directory tree
Documentation
/*
walkup - Simple up directory hierarchy walker

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

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)]
#![forbid(clippy::missing_errors_doc)]

//! Searches for a file by walking up the directory tree.

use std::fs;
use std::path::{Path, PathBuf};

/**
  Walks directories up to find a file.

  Searches for a file. If file does not exists in the current directory,
  the search will continue in the parrent directory until the root is
  reached or the file is found.

  `filename` must point to a file, not directory and that file must be readable
  for to be returned as a valid result.

  ### Parameters

  `start` - where to start searching for a file. For searching from
          current directory up, use ".". `start` directory is
          normalized using [`make_absolute`] function.

  `filename` - the filename we are searching for

  ### Returns

  Option with `PathBuf` if file `filename` is found and can be opened for reading.

  ## Example

```rust
use walkup::walk_up;
// parameters are: start directory, file name
let res = walk_up ( "/usr/src/usr.bin/aucat/", "Makefile.inc" );
if let Some(path) = res {
   println!("Makefile.inc found at {}", path.display());
}
```
*/
pub fn walk_up (start: impl AsRef<Path>, filename: impl AsRef<Path>) -> Option <PathBuf> {

   let p1 = make_absolute(start);
   for ancestor in p1.ancestors() {
      /* prepare empty PathBuf */
      let mut fullname: PathBuf = PathBuf::with_capacity(256);
      /* put directory name to PathBuf */
      fullname.push(ancestor);
      /* create file name we are searching for by appending
         filename to directory.
       */
      let mut fullname: PathBuf = fullname.join(filename.as_ref());
      /* check if file exists. Try read its metadata */
      if let Ok(metadata) = fs::metadata(&fullname) {
         /* check metadata if its file and not a directory */
         if metadata.is_file() {
            /* try to open file to see if it is readable */
            if fs::File::open(&fullname).is_ok() {
               fullname.shrink_to_fit();
               return Some(fullname);
            }
         }
      }
   }
   None
}

/**
  Convert path to absolute form.

  This is alternative implementation to _fs::canonicalize_.
  It works slightly differently on Windows and produces more
  predictable names.

  If function can't query current directory input will be
  returned unchanged.

  ### Parameters

  `path` - what we want to convert

  ### Returns

  PathBuf containing normalized `path`
```rust
use walkup::make_absolute;
let res = make_absolute ( "./demo" );
println!("Absolute path is {}", res.display());
```

*/
pub fn make_absolute(path: impl AsRef<Path>) -> PathBuf {
   // Convert trait AsRef to a Path reference
   let path = path.as_ref();
   if path.is_relative() {
      if let Ok(current_dir) = std::env::current_dir() {
         return current_dir.join(path);
      }
   }
   // path is already absolute or we can't get current_dir()
   // In this case convert reference back to PathBuf
   path.to_path_buf()
}

#[cfg(test)]
#[path = "tests.rs"]
mod test_walkup;