markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use crate::markdown;
use std::path::{Path, PathBuf};

use crate::WorkspaceIndex;

const MAX_DEPTH: usize = 5;

enum PendingEntry {
    Directory { path: PathBuf, depth: usize },
    Line(String),
}

#[must_use]
pub(crate) fn build(
    workspace: &WorkspaceIndex,
    dir: &Path,
    paths: &[String],
    max_depth: Option<u32>,
) -> String {
    let depth_limit = max_depth.map_or(MAX_DEPTH, |depth| {
        usize::try_from(depth).unwrap_or(usize::MAX)
    });
    let mut lines = Vec::new();

    let owned: Vec<String>;
    let effective: &[String] = if paths.is_empty() {
        owned = discover_source_dirs(workspace, dir);

        &owned
    } else {
        paths
    };

    for path in effective {
        let target = dir.join(path);

        if workspace.is_dir(&target) {
            lines.push(format!("{path}/"));
            collect_entries(workspace, &target, &mut lines, 1, depth_limit);
        }
    }

    if lines.is_empty() {
        return String::new();
    }

    markdown::code_block("", lines.join("\n"))
}

fn is_dir_empty(workspace: &WorkspaceIndex, dir: &Path) -> bool {
    !workspace.has_files_below(dir)
}

fn discover_source_dirs(workspace: &WorkspaceIndex, dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = workspace
        .child_dirs(dir)
        .filter_map(|path| path.file_name()?.to_str().map(str::to_owned))
        .collect();

    names.sort();

    names
}

fn collect_entries(
    workspace: &WorkspaceIndex,
    root: &Path,
    lines: &mut Vec<String>,
    depth: usize,
    max_depth: usize,
) {
    let mut pending = vec![PendingEntry::Directory {
        path: root.to_path_buf(),
        depth,
    }];

    while let Some(entry) = pending.pop() {
        let (root, depth) = match entry {
            PendingEntry::Directory { path, depth } => (path, depth),

            PendingEntry::Line(line) => {
                lines.push(line);

                continue;
            }
        };

        if depth > max_depth {
            continue;
        }

        let mut dirs = workspace
            .child_dirs(&root)
            .filter_map(|path| {
                let name = path.file_name()?.to_string_lossy().into_owned();

                Some((name, path.to_path_buf()))
            })
            .collect::<Vec<_>>();
        let mut files = workspace
            .files_in(&root)
            .filter_map(|path| {
                let name = path.file_name()?.to_string_lossy().into_owned();

                Some((name, path.to_path_buf()))
            })
            .collect::<Vec<_>>();

        dirs.sort_by(|a, b| a.0.cmp(&b.0));
        files.sort_by(|a, b| a.0.cmp(&b.0));

        let indent = "  ".repeat(depth);
        let mut entries = Vec::new();

        for (name, path) in dirs {
            if is_dir_empty(workspace, &path) {
                continue;
            }

            let desc = crate::domain::file_description(workspace, &path.join("mod.rs"))
                .or_else(|| crate::domain::file_description(workspace, &path.join("lib.rs")));
            let line = match desc {
                Some(description) => format!("{indent}{name}/ - {description}"),
                None => format!("{indent}{name}/"),
            };

            entries.push(PendingEntry::Line(line));
            entries.push(PendingEntry::Directory {
                path,
                depth: depth + 1,
            });
        }

        for (name, path) in files {
            let line = if name == "mod.rs" || name == "lib.rs" {
                format!("{indent}{name}")
            } else {
                match crate::domain::file_description(workspace, &path) {
                    Some(description) => format!("{indent}{name} - {description}"),
                    None => format!("{indent}{name}"),
                }
            };

            entries.push(PendingEntry::Line(line));
        }

        pending.extend(entries.into_iter().rev());
    }
}

#[cfg(test)]
mod tests;