use clap::Args;
use octocode::indexer;
use octocode::storage;
use crate::commands::OutputFormat;
#[derive(Args, Debug)]
pub struct ViewArgs {
pub files: Vec<String>,
#[arg(long, value_enum, default_value = "cli")]
pub format: OutputFormat,
}
pub async fn execute(args: &ViewArgs) -> Result<(), anyhow::Error> {
let current_dir = std::env::current_dir()?;
let index_path = storage::get_project_database_path(¤t_dir)?;
if !index_path.exists() {
println!("Note: No index found. The view command works without an index, but you can run 'octocode index' to create one if needed for other commands.");
}
let mut matching_files = Vec::new();
for pattern in &args.files {
let pattern_path = if std::path::Path::new(pattern).is_relative() {
current_dir.join(pattern)
} else {
std::path::PathBuf::from(pattern)
};
if pattern_path.is_file() {
matching_files.push(pattern_path);
} else {
let glob_pattern = match globset::Glob::new(pattern) {
Ok(g) => g.compile_matcher(),
Err(e) => {
println!("Invalid glob pattern '{}': {}", pattern, e);
continue;
}
};
let walker = indexer::NoindexWalker::create_walker(¤t_dir).build();
for result in walker {
let entry = match result {
Ok(entry) => entry,
Err(_) => continue,
};
if !entry.file_type().is_some_and(|ft| ft.is_file()) {
continue;
}
let relative_path =
indexer::PathUtils::to_relative_string(entry.path(), ¤t_dir);
if glob_pattern.is_match(&relative_path) {
matching_files.push(entry.path().to_path_buf());
}
}
}
}
if matching_files.is_empty() {
println!("No matching files found.");
return Ok(());
}
let signatures = indexer::extract_file_signatures(&matching_files)?;
if args.format.is_json() {
indexer::render_signatures_json(&signatures)?
} else if args.format.is_md() {
let markdown = indexer::signatures_to_markdown(&signatures);
println!("{}", markdown);
} else if args.format.is_text() {
let text_output = indexer::render_signatures_text(&signatures);
println!("{}", text_output);
} else if args.format.is_cli() {
indexer::render_signatures_cli(&signatures);
} else {
indexer::render_signatures_cli(&signatures);
}
Ok(())
}