tree2md 0.14.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
mod cli;
mod content;
mod domain;
mod fs_tree;
mod hotspot;
mod language;
mod output;
mod profile;
mod render;
mod safety;
mod terminal;
mod util;

use domain::filter::MatchSpec;
use fs_tree::build::build_tree_with_spec;
use fs_tree::ProgressTracker;
use std::io;
use std::path::Path;
use terminal::animation::AnimationRunner;
use terminal::capabilities::TerminalCapabilities;
use terminal::detect::TerminalDetector;

/// Restore default SIGPIPE behavior (terminate on broken pipe).
/// Rust sets SIG_IGN by default, which causes `print!` to panic
/// when piping to programs like `head` or `less`.
#[cfg(unix)]
fn reset_sigpipe() {
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

#[cfg(not(unix))]
fn reset_sigpipe() {}

fn main() -> io::Result<()> {
    // Restore default SIGPIPE behavior so piping to head/less doesn't panic
    reset_sigpipe();

    let args = cli::parse();

    // Determine display root
    let display_root = Path::new(&args.target)
        .canonicalize()
        .unwrap_or_else(|_| std::path::PathBuf::from(&args.target));

    // Get the root path for pattern matching
    let root_path = Path::new(&args.target)
        .canonicalize()
        .unwrap_or_else(|_| Path::new(&args.target).to_path_buf());

    // Set up progress tracking and animation
    let detector = TerminalDetector::new();
    let is_tty = detector.is_tty();
    let show_animation = args.is_fun_enabled(is_tty) && !args.no_anim && is_tty;

    let progress_tracker = if show_animation {
        Some(ProgressTracker::new())
    } else {
        None
    };

    let mut animation_runner = AnimationRunner::new(show_animation, progress_tracker.clone());

    // Read git history for --hot while the tree is walked
    let heat_job = args.hot_span().map(|span| {
        let dir = root_path.clone();
        std::thread::spawn(move || hotspot::collect(&dir, &span))
    });

    // Build tree using unified WalkBuilder approach. The spec is built once:
    // `--paths-from -` reads stdin, which a second walk could not read again.
    let spec = MatchSpec::from_args(&args, Path::new(&args.target))?;
    let mut root_node =
        build_tree_with_spec(&args.target, &args, &spec, &root_path, &display_root)?;

    // Stop animation once tree is built
    animation_runner.complete();

    let hot = heat_job
        .and_then(join_heat_job)
        .map(|heat| hot_spots(heat, &args, &spec, &root_node, &root_path, &display_root));
    if let Some(hot) = &hot {
        if args.hot_top.is_some() {
            hot.keep_top(&mut root_node);
        }
        if args.sort == cli::SortOrder::Hot {
            hot.sort_tree(&mut root_node);
        }
    }

    // Create terminal capabilities and renderer
    let capabilities = TerminalCapabilities::new();
    let mut renderer = render::create_renderer(&args, &capabilities, hot.as_ref());
    let output = renderer.render_tree(&root_node);

    // Print to stdout
    print!("{}", output);

    Ok(())
}

/// Wait for the git history read, warning when it is unavailable.
fn join_heat_job(
    job: std::thread::JoinHandle<Result<hotspot::HeatMap, String>>,
) -> Option<hotspot::HeatMap> {
    match job.join() {
        Ok(Ok(heat)) => {
            if heat.shallow {
                eprintln!(
                    "Warning: --hot: shallow clone, so commits before its depth are not counted"
                );
            }
            Some(heat)
        }
        Ok(Err(reason)) => {
            eprintln!("Warning: --hot: {}; hot spots skipped", reason);
            None
        }
        Err(_) => {
            eprintln!("Warning: --hot: reading git history failed; hot spots skipped");
            None
        }
    }
}

/// Rank the history of the files the filters show. With `-L` the tree stops
/// at the depth limit, so the files beneath it are collected by a walk
/// without the limit: they still count toward their directories and the
/// ranking, and the same filters decide which ones.
fn hot_spots(
    mut heat: hotspot::HeatMap,
    args: &cli::Args,
    spec: &MatchSpec,
    tree: &fs_tree::Node,
    root_path: &Path,
    display_root: &Path,
) -> hotspot::HotSpots {
    let visible = match args.level {
        None => hotspot::visible_files(tree),
        Some(_) => {
            let unlimited = cli::Args {
                level: None,
                ..args.clone()
            };
            build_tree_with_spec(&args.target, &unlimited, spec, root_path, display_root)
                .map(|full| hotspot::visible_files(&full))
                .unwrap_or_else(|_| hotspot::visible_files(tree))
        }
    };
    heat.retain_files(|path| visible.contains(path));
    hotspot::HotSpots::new(
        heat,
        args.hot_metric.unwrap_or_default(),
        args.hot_top.unwrap_or(hotspot::TOP_N),
        root_path,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use cli::Args;
    use language::detect_lang;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_detect_lang() {
        assert_eq!(detect_lang("test.rs").map(|l| l.name), Some("rust"));
        assert_eq!(detect_lang("test.go").map(|l| l.name), Some("go"));
        assert_eq!(detect_lang("test.py").map(|l| l.name), Some("python"));
        assert_eq!(detect_lang("test.unknown"), None);
    }

    #[test]
    fn test_build_tree() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create test files
        fs::create_dir(temp_path.join("src")).unwrap();
        fs::write(temp_path.join("src/main.rs"), "fn main() {}").unwrap();
        fs::write(temp_path.join("README.md"), "# Test").unwrap();

        let args = Args::parse_from(&["tree2md", temp_path.to_str().unwrap()]);
        let display_root = temp_path.to_path_buf();
        let target = temp_path.to_str().unwrap();
        let spec = MatchSpec::from_args(&args, temp_path).unwrap();
        let tree = build_tree_with_spec(target, &args, &spec, temp_path, &display_root).unwrap();

        assert!(tree.is_dir);
        assert!(tree.children.len() >= 2);
    }
}