use anyhow::Result;
use clap::Parser;
use indicatif::{ProgressBar, ProgressStyle};
use std::collections::HashSet;
mod build;
mod checker;
mod codeowners;
mod coverage_parser;
mod dependency_resolver;
mod feature_metadata_detector;
mod features_toml_parser;
mod file_scanner;
mod git_helper;
mod http_server;
mod import_detector;
mod models;
mod printer;
mod readme_parser;
mod scan;
mod skip_dirs;
use build::{BuildConfig, create_build};
use checker::run_checks;
use codeowners::generate_codeowners;
use http_server::serve_features_with_watching;
use models::Feature;
use printer::print_features;
use scan::{ScanConfig, scan_features};
#[derive(Parser)]
#[command(name = "features")]
#[command(author = env!("CARGO_PKG_AUTHORS"))]
#[command(about = env!("CARGO_PKG_DESCRIPTION"))]
#[command(arg_required_else_help = true)]
struct Cli {
#[arg(required = false)]
path: Option<std::path::PathBuf>,
#[arg(short = 'V', long)]
version: bool,
#[arg(long)]
json: bool,
#[arg(long)]
flat: bool,
#[arg(long)]
description: bool,
#[arg(long)]
list_owners: bool,
#[arg(long)]
check: bool,
#[arg(long)]
serve: bool,
#[arg(long, default_value = "3000")]
port: u16,
#[arg(long)]
build: bool,
#[arg(long, default_value = "build")]
build_dir: std::path::PathBuf,
#[arg(long)]
skip_changes: bool,
#[arg(long)]
find_owner: Option<String>,
#[arg(long)]
coverage_dir: Option<std::path::PathBuf>,
#[arg(long)]
coverage: bool,
#[arg(long)]
generate_codeowners: bool,
#[arg(long)]
project_dir: Option<std::path::PathBuf>,
#[arg(long)]
codeowners_path: Option<std::path::PathBuf>,
#[arg(long, default_value = "@")]
codeowners_prefix: String,
#[arg(long)]
ignore_path: Vec<std::path::PathBuf>,
#[arg(long)]
include_skipped_dirs: bool,
}
fn resolve_ignore_paths(
ignore_paths: &[std::path::PathBuf],
current_dir: &std::path::Path,
) -> Vec<std::path::PathBuf> {
ignore_paths
.iter()
.filter_map(|raw_path| {
let candidate = if raw_path.is_absolute() {
raw_path.clone()
} else {
current_dir.join(raw_path)
};
match std::fs::canonicalize(&candidate) {
Ok(canonical) => Some(canonical),
Err(_) => {
eprintln!(
"Warning: --ignore-path '{}' does not exist, skipping.",
raw_path.display()
);
None
}
}
})
.collect()
}
fn flatten_features(features: &[Feature]) -> Vec<Feature> {
let mut flat_features = Vec::new();
for feature in features {
let flat_feature = Feature {
name: feature.name.clone(),
description: feature.description.clone(),
owner: feature.owner.clone(),
is_owner_inherited: feature.is_owner_inherited,
path: feature.path.clone(),
features: Vec::new(), meta: feature.meta.clone(),
changes: Vec::new(),
decisions: Vec::new(),
stats: feature.stats.clone(),
dependencies: feature.dependencies.clone(),
};
flat_features.push(flat_feature);
let nested_flat = flatten_features(&feature.features);
flat_features.extend(nested_flat);
}
flat_features
}
#[derive(Debug, serde::Serialize)]
struct OwnerInfo {
owner: String,
#[serde(skip_serializing_if = "std::ops::Not::not")]
inherited: bool,
feature_name: String,
feature_path: String,
}
fn find_owner_for_path(
target_path: &std::path::Path,
features: &[Feature],
base_path: &std::path::Path,
) -> Option<OwnerInfo> {
let canonical_target = std::fs::canonicalize(target_path).ok()?;
fn find_closest_feature(
target: &std::path::Path,
features: &[Feature],
_parent_owner: Option<&str>,
base_path: &std::path::Path,
) -> Option<OwnerInfo> {
let mut best_match: Option<OwnerInfo> = None;
let mut best_match_depth = usize::MAX;
for feature in features {
let feature_path = base_path.join(&feature.path);
if let Ok(canonical_feature_path) = std::fs::canonicalize(&feature_path) {
if target.starts_with(&canonical_feature_path) {
let depth = target
.strip_prefix(&canonical_feature_path)
.ok()
.map(|p| p.components().count())
.unwrap_or(usize::MAX);
if let Some(nested_match) = find_closest_feature(
target,
&feature.features,
Some(&feature.owner),
base_path,
) {
if best_match.is_none() || depth < best_match_depth {
best_match = Some(nested_match);
best_match_depth = depth;
}
} else {
if depth < best_match_depth {
let owner = OwnerInfo {
owner: feature.owner.clone(),
inherited: feature.is_owner_inherited,
feature_name: feature.name.clone(),
feature_path: feature.path.clone(),
};
best_match = Some(owner);
best_match_depth = depth;
}
}
}
}
}
best_match
}
find_closest_feature(&canonical_target, features, None, base_path)
}
fn extract_unique_owners(features: &[Feature]) -> Vec<String> {
let mut owners_set = HashSet::new();
fn collect_owners(features: &[Feature], owners_set: &mut HashSet<String>) {
for feature in features {
owners_set.insert(feature.owner.clone());
collect_owners(&feature.features, owners_set);
}
}
collect_owners(features, &mut owners_set);
let mut owners: Vec<String> = owners_set.into_iter().collect();
owners.sort(); owners
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Cli::parse();
if args.version {
println!("{}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
if let Some(target_file) = &args.find_owner {
let target_path = std::path::PathBuf::from(target_file);
if !target_path.exists() {
eprintln!("Error: Path '{}' does not exist.", target_file);
std::process::exit(1);
}
let base_path = if let Some(p) = &args.path {
p.clone()
} else {
std::env::current_dir()?
};
let current_dir = std::env::current_dir()?;
let ignore_paths = resolve_ignore_paths(&args.ignore_path, ¤t_dir);
let config = ScanConfig::new(¤t_dir)
.skip_changes(args.skip_changes)
.ignore_paths(ignore_paths)
.ownership_only(true)
.include_skipped_dirs(args.include_skipped_dirs);
let features = scan_features(&base_path, config)?;
match find_owner_for_path(&target_path, &features, &base_path) {
Some(owner_info) => {
if args.json {
let json = serde_json::to_string_pretty(&owner_info)?;
println!("{}", json);
} else {
println!(
"Owner: {}{}",
owner_info.owner,
if owner_info.inherited {
" (inherited)"
} else {
""
}
);
println!("Feature: {}", owner_info.feature_name);
println!("Feature Path: {}", owner_info.feature_path);
}
}
None => {
eprintln!("No feature found for path: {}", target_file);
std::process::exit(1);
}
}
return Ok(());
}
let path = match args.path {
Some(p) => p,
None => {
eprintln!("Error: The path argument is required.");
eprintln!("Try 'features --help' for more information.");
std::process::exit(1);
}
};
let spinner = if args.serve {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.template("{spinner:.green} {msg}")
.unwrap()
.tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
);
pb.set_message(format!(
"Starting Features CLI v{}...",
env!("CARGO_PKG_VERSION")
));
pb.enable_steady_tick(std::time::Duration::from_millis(100));
Some(pb)
} else {
None
};
let current_dir = std::env::current_dir()?;
let should_add_coverage = args.serve || args.build || args.json || args.coverage;
let ignore_paths = resolve_ignore_paths(&args.ignore_path, ¤t_dir);
let ownership_only = args.generate_codeowners && !args.serve && !args.build && !args.check;
let mut config = ScanConfig::new(¤t_dir)
.skip_changes(args.skip_changes)
.with_coverage(should_add_coverage)
.ignore_paths(ignore_paths.clone())
.ownership_only(ownership_only)
.include_skipped_dirs(args.include_skipped_dirs);
if let Some(ref coverage_dir) = args.coverage_dir {
config = config.coverage_dir(coverage_dir);
}
if let Some(ref project_dir) = args.project_dir {
config = config.project_dir(project_dir);
}
let features = scan_features(&path, config)?;
if args.generate_codeowners {
let output_dir = args.project_dir.as_deref().unwrap_or(¤t_dir);
generate_codeowners(
&features,
&path,
args.project_dir.as_deref(),
output_dir,
args.codeowners_path.as_deref(),
&args.codeowners_prefix,
)?;
}
if args.serve {
if let Some(pb) = spinner {
pb.set_message("Server is starting...");
let pb_clone = pb.clone();
serve_features_with_watching(
&features,
args.port,
path.clone(),
Some(Box::new(move || {
pb_clone.finish_and_clear();
})),
args.skip_changes,
ignore_paths.clone(),
args.include_skipped_dirs,
)
.await?;
} else {
serve_features_with_watching(
&features,
args.port,
path.clone(),
None,
args.skip_changes,
ignore_paths.clone(),
args.include_skipped_dirs,
)
.await?;
}
} else if args.build {
let build_config = BuildConfig::new(args.build_dir);
create_build(&features, build_config, args.skip_changes).await?;
} else if args.check {
run_checks(&features)?;
} else if args.generate_codeowners {
} else if args.list_owners {
let unique_owners = extract_unique_owners(&features);
if args.json {
let json = serde_json::to_string_pretty(&unique_owners)?;
println!("{}", json);
} else {
eprintln!("Unique owners found in {}:", path.display());
for owner in unique_owners {
println!("{}", owner);
}
}
} else {
let output_features = if args.flat {
flatten_features(&features)
} else {
features
};
if args.json {
let json = serde_json::to_string_pretty(&output_features)?;
println!("{}", json);
} else {
eprintln!("Features found in {}:", path.display());
if output_features.is_empty() {
eprintln!("No features found.");
} else {
print_features(&output_features, 0, args.description);
}
}
}
Ok(())
}