features-cli 0.14.0

A CLI tool for discovering the features in a folder
Documentation
use anyhow::Result;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::Path;

use crate::models::Feature;

const SECTION_START: &str = "# ==== GENERATED BY FEATURES-CLI ====";
const SECTION_END: &str = "# ==== END SECTION GENERATED BY FEATURES-CLI ====";

/// Generate or update a CODEOWNERS file with feature ownership information.
///
/// # Arguments
///
/// * `features` - List of features to generate CODEOWNERS entries for
/// * `base_path` - Base path of the project (where features are located)
/// * `project_dir` - Optional project directory to calculate relative paths
/// * `output_dir` - Directory where the CODEOWNERS file should be created
/// * `codeowners_path_override` - Optional custom path and filename for CODEOWNERS file
/// * `owner_prefix` - Prefix to add to owner names (default: "@")
///
/// # Behavior
///
/// - Creates CODEOWNERS if it doesn't exist
/// - Updates existing CODEOWNERS while preserving custom content
/// - Generated content is placed between section markers
/// - Content outside markers is preserved
/// - Paths are normalized with forward slashes and leading `/`
/// - Owners automatically get the specified prefix if not already present
pub fn generate_codeowners(
    features: &[Feature],
    base_path: &Path,
    project_dir: Option<&Path>,
    output_dir: &Path,
    codeowners_path_override: Option<&Path>,
    owner_prefix: &str,
) -> Result<()> {
    let codeowners_path = if let Some(custom_path) = codeowners_path_override {
        custom_path.to_path_buf()
    } else {
        output_dir.join("CODEOWNERS")
    };

    // Read existing file content if it exists
    let (before_section, after_section) = if codeowners_path.exists() {
        read_existing_codeowners(&codeowners_path)?
    } else {
        (String::new(), String::new())
    };

    // Generate the CODEOWNERS entries
    let mut entries = Vec::new();
    collect_entries(features, base_path, project_dir, &mut entries, owner_prefix);

    // Write the CODEOWNERS file
    write_codeowners_file(&codeowners_path, &before_section, &entries, &after_section)?;

    eprintln!(
        "✅ CODEOWNERS file generated at: {}",
        codeowners_path.display()
    );
    Ok(())
}

/// Read an existing CODEOWNERS file and extract content before and after the generated section
fn read_existing_codeowners(codeowners_path: &Path) -> Result<(String, String)> {
    let file = fs::File::open(codeowners_path)?;
    let reader = BufReader::new(file);
    let mut lines = Vec::new();

    for line in reader.lines() {
        lines.push(line?);
    }

    // Find the section markers
    let start_idx = lines.iter().position(|l| l.trim() == SECTION_START);
    let end_idx = lines.iter().position(|l| l.trim() == SECTION_END);

    match (start_idx, end_idx) {
        (Some(start), Some(end)) if start < end => {
            // Extract content before and after the generated section
            let before = lines[..start].join("\n");
            let after = if end + 1 < lines.len() {
                lines[end + 1..].join("\n")
            } else {
                String::new()
            };
            Ok((before, after))
        }
        _ => {
            // No valid section found, keep all content as "before"
            Ok((lines.join("\n"), String::new()))
        }
    }
}

/// Recursively collect CODEOWNERS entries from features
fn collect_entries(
    features: &[Feature],
    base_path: &Path,
    project_dir: Option<&Path>,
    entries: &mut Vec<String>,
    owner_prefix: &str,
) {
    collect_entries_with_parent(
        features,
        base_path,
        project_dir,
        entries,
        None,
        owner_prefix,
    );
}

/// Recursively collect CODEOWNERS entries from features with parent owner tracking
fn collect_entries_with_parent(
    features: &[Feature],
    base_path: &Path,
    project_dir: Option<&Path>,
    entries: &mut Vec<String>,
    parent_owner: Option<&str>,
    owner_prefix: &str,
) {
    for feature in features {
        // Skip this feature if it has the same owner as its parent
        let should_skip = parent_owner.is_some_and(|parent| feature.owner == parent);

        if !should_skip {
            // Calculate the path for CODEOWNERS
            let feature_path = std::path::PathBuf::from(&feature.path);
            let full_path = base_path.join(&feature_path);

            // Determine the final path to write
            let codeowners_path = if let Some(proj_dir) = project_dir {
                // Remove project_dir from the full_path if present
                if let Ok(relative) = full_path.strip_prefix(proj_dir) {
                    relative.to_path_buf()
                } else {
                    full_path
                }
            } else {
                full_path
            };

            // Convert to forward slashes and add leading slash for CODEOWNERS format
            let path_str = codeowners_path.to_str().unwrap_or("").replace('\\', "/");

            let path_str = if path_str.starts_with('/') {
                path_str
            } else {
                format!("/{}", path_str)
            };

            // Add owner with prefix, but skip if owner is empty
            if feature.owner.is_empty() {
                let unknown_owner = format_owner("Unknown", owner_prefix);
                entries.push(format!("{} {}", path_str, unknown_owner));
            } else {
                let owner = format_owner(&feature.owner, owner_prefix);
                entries.push(format!("{} {}", path_str, owner));
            }
        }

        // Recursively collect from nested features, passing current feature's owner
        collect_entries_with_parent(
            &feature.features,
            base_path,
            project_dir,
            entries,
            Some(&feature.owner),
            owner_prefix,
        );
    }
}

/// Format owner with specified prefix if not already present
fn format_owner(owner: &str, prefix: &str) -> String {
    if prefix.is_empty() || owner.starts_with(prefix) {
        owner.to_string()
    } else {
        format!("{}{}", prefix, owner)
    }
}

/// Write the CODEOWNERS file with preserved content and generated section
fn write_codeowners_file(
    codeowners_path: &Path,
    before_section: &str,
    entries: &[String],
    after_section: &str,
) -> Result<()> {
    let mut file = fs::File::create(codeowners_path)?;

    // Write content before the generated section
    if !before_section.is_empty() {
        writeln!(file, "{}", before_section)?;
        if !before_section.ends_with('\n') {
            writeln!(file)?;
        }
    }

    // Write the generated section
    writeln!(file, "{}", SECTION_START)?;
    for entry in entries {
        writeln!(file, "{}", entry)?;
    }
    writeln!(file, "{}", SECTION_END)?;

    // Write content after the generated section
    if !after_section.is_empty() {
        if !after_section.starts_with('\n') {
            writeln!(file)?;
        }
        write!(file, "{}", after_section)?;
        if !after_section.ends_with('\n') {
            writeln!(file)?;
        }
    }

    Ok(())
}