use std::path::PathBuf;
use anyhow::Result;
use clap::Args;
use tldr_core::types::ComplexityMetrics;
use tldr_core::{calculate_complexity, detect_or_parse_language, validate_file_path, Language};
use crate::commands::daemon_router::{params_with_file_function, try_daemon_route};
use crate::output::{format_complexity_text, OutputFormat, OutputWriter};
#[derive(Debug, Args)]
pub struct ComplexityArgs {
pub file: PathBuf,
pub function: String,
#[arg(long, short = 'l')]
pub lang: Option<Language>,
}
impl ComplexityArgs {
pub fn run(&self, format: OutputFormat, quiet: bool) -> Result<()> {
let writer = OutputWriter::new(format, quiet);
let validated_path = validate_file_path(self.file.to_str().unwrap_or_default(), None)?;
let project = validated_path.parent().unwrap_or(&validated_path);
if let Some(result) = try_daemon_route::<ComplexityMetrics>(
project,
"complexity",
params_with_file_function(&validated_path, &self.function),
) {
if writer.is_text() {
writer.write_text(&format_complexity_text(&result))?;
} else {
writer.write(&result)?;
}
return Ok(());
}
let language =
detect_or_parse_language(self.lang.as_ref().map(|l| l.as_str()), &validated_path)?;
writer.progress(&format!(
"Calculating complexity for {} in {} ({:?})...",
self.function,
validated_path.display(),
language
));
let result = calculate_complexity(
validated_path.to_str().unwrap_or_default(),
&self.function,
language,
)?;
if writer.is_text() {
writer.write_text(&format_complexity_text(&result))?;
} else {
writer.write(&result)?;
}
Ok(())
}
}