index : smol-guess.git

ascending towards madness

use std::path::PathBuf;

use git2::{Repository, TreeWalkMode};

/// Retrieves a list of file paths from a bare Git repository.
///
/// The `get_bare_repository_files` function takes a `PathBuf` representing the path to a
/// bare Git repository and returns a vector of `PathBuf` representing the file paths in the repository.
///
/// # Parameters
///
/// - `path`: The path to the bare Git repository.
///
/// # Returns
///
/// A vector of `PathBuf` containing the file paths in the bare Git repository.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
/// use smolguess::repository::get_bare_repository_files;
///
/// let repo_path = PathBuf::from("/path/to/bare/repo.git");
/// let files = get_bare_repository_files(repo_path);
///
/// for file in files {
///     println!("File: {}", file.display());
/// }
/// ```
pub fn get_bare_repository_files(path: PathBuf) -> Vec<PathBuf> {
    if let Ok(repo) = Repository::open_bare(path) {
        if let Ok(current_tree) = repo.head().map(|head| head.peel_to_tree()) {
            let mut files: Vec<PathBuf> = Vec::new();

            match current_tree {
                Ok(tree) => {
                    tree.walk(TreeWalkMode::PreOrder, |root, entry| {
                        if entry
                            .kind()
                            .map_or(false, |kind| kind.eq(&git2::ObjectType::Blob))
                        {
                            files.push(PathBuf::from(format!(
                                "{}{}",
                                root,
                                entry.name().expect("Error getting file name")
                            )));
                        }
                        git2::TreeWalkResult::Ok
                    })
                    .expect("Error walking through tree");
                }
                Err(e) => {
                    println!("{:?}", e);
                }
            };

            files
        } else {
            println!("Error retrieving tree");
            Vec::new()
        }
    } else {
        println!("Could not open repository");
        Vec::new()
    }
}