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 ====";
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")
};
let (before_section, after_section) = if codeowners_path.exists() {
read_existing_codeowners(&codeowners_path)?
} else {
(String::new(), String::new())
};
let mut entries = Vec::new();
collect_entries(features, base_path, project_dir, &mut entries, owner_prefix);
write_codeowners_file(&codeowners_path, &before_section, &entries, &after_section)?;
eprintln!(
"✅ CODEOWNERS file generated at: {}",
codeowners_path.display()
);
Ok(())
}
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?);
}
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 => {
let before = lines[..start].join("\n");
let after = if end + 1 < lines.len() {
lines[end + 1..].join("\n")
} else {
String::new()
};
Ok((before, after))
}
_ => {
Ok((lines.join("\n"), String::new()))
}
}
}
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,
);
}
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 {
let should_skip = parent_owner.is_some_and(|parent| feature.owner == parent);
if !should_skip {
let feature_path = std::path::PathBuf::from(&feature.path);
let full_path = base_path.join(&feature_path);
let codeowners_path = if let Some(proj_dir) = project_dir {
if let Ok(relative) = full_path.strip_prefix(proj_dir) {
relative.to_path_buf()
} else {
full_path
}
} else {
full_path
};
let path_str = codeowners_path.to_str().unwrap_or("").replace('\\', "/");
let path_str = if path_str.starts_with('/') {
path_str
} else {
format!("/{}", path_str)
};
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));
}
}
collect_entries_with_parent(
&feature.features,
base_path,
project_dir,
entries,
Some(&feature.owner),
owner_prefix,
);
}
}
fn format_owner(owner: &str, prefix: &str) -> String {
if prefix.is_empty() || owner.starts_with(prefix) {
owner.to_string()
} else {
format!("{}{}", prefix, owner)
}
}
fn write_codeowners_file(
codeowners_path: &Path,
before_section: &str,
entries: &[String],
after_section: &str,
) -> Result<()> {
let mut file = fs::File::create(codeowners_path)?;
if !before_section.is_empty() {
writeln!(file, "{}", before_section)?;
if !before_section.ends_with('\n') {
writeln!(file)?;
}
}
writeln!(file, "{}", SECTION_START)?;
for entry in entries {
writeln!(file, "{}", entry)?;
}
writeln!(file, "{}", SECTION_END)?;
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(())
}