taxutils 1.1.7

Rust utilities for NCBI taxonomy data and FASTA files
Documentation
use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};
use taxutils::{
    FilterMode, clean_fasta_headers, extract_accessions, filter_fasta, grep_fasta, parse_taxa,
};

#[derive(Parser)]
#[command(
    name = "tu",
    version,
    about = "Utilities for working with taxonomy data and FASTA files.",
    after_help = "Inputs and query files may be plain, gzip, or zstd (detected by content). Outputs ending in .gz use gzip; .zst/.zstd use zstd; other outputs are plain. Omitted output paths preserve input compression during atomic in-place rewrites."
)]
struct Cli {
    /// Number of worker threads (defaults to available logical CPUs).
    #[arg(long, global = true)]
    threads: Option<usize>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Replace FASTA headers with accession-only headers.
    #[command(
        after_help = "Supports plain, gzip, and zstd input. Output suffix selects compression; omitted output preserves input compression."
    )]
    Clean {
        #[arg(short, long)]
        input: PathBuf,
        #[arg(short, long)]
        output: Option<PathBuf>,
        #[arg(long)]
        verbose: bool,
    },
    /// Keep the first FASTA record per accession (including version).
    #[command(
        after_help = "Supports plain, gzip, and zstd input. Output suffix selects compression; omitted output preserves input compression."
    )]
    Deduplicate {
        #[arg(short, long)]
        input: PathBuf,
        /// Output FASTA; defaults to an atomic in-place rewrite.
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Extract one accession per FASTA header.
    #[command(
        after_help = "Supports plain, gzip, and zstd input. Output suffix selects compression: .gz, .zst, or .zstd; otherwise plain."
    )]
    Extract {
        fasta: PathBuf,
        #[arg(short, long)]
        output: PathBuf,
        #[arg(long, default_value_t = 10_000)]
        batch_size: usize,
    },
    /// Filter FASTA records using accession-to-taxid lookup.
    #[command(
        after_help = "Supports plain, gzip, and zstd input and taxid files. Output suffix selects compression; omitted output preserves input compression."
    )]
    Filter {
        #[arg(short, long)]
        input: PathBuf,
        #[arg(short, long)]
        output: Option<PathBuf>,
        #[arg(
            long,
            conflicts_with = "remove_taxids",
            required_unless_present = "remove_taxids"
        )]
        keep_taxids: Option<String>,
        #[arg(
            long,
            conflicts_with = "keep_taxids",
            required_unless_present = "keep_taxids"
        )]
        remove_taxids: Option<String>,
        #[arg(long, default_value_t = 5000)]
        batch_size: usize,
        #[arg(long)]
        verbose: bool,
    },
    /// Extract FASTA records matching requested accessions.
    #[command(
        after_help = "Supports plain, gzip, and zstd input. Output suffix selects compression: .gz, .zst, or .zstd; otherwise plain."
    )]
    Grep {
        #[arg(short, long)]
        input: PathBuf,
        #[arg(short, long)]
        accessions: String,
        #[arg(short, long)]
        output: PathBuf,
        #[arg(long)]
        no_version: bool,
        #[arg(long, default_value_t = 1_000_000)]
        batch_size: usize,
        #[arg(long)]
        verbose: bool,
    },
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    // Validate here so a bad --threads fails before any work starts; each
    // operation builds its own pool from this value.
    taxutils::threads::resolve(cli.threads)?;
    let threads = cli.threads;
    match cli.command {
        Command::Deduplicate { input, output } => {
            let stats = taxutils::deduplicate_fasta(input, output.as_deref(), threads)?;
            println!(
                "Finished deduplicating FASTA: kept={} removed={}",
                stats.kept, stats.removed
            );
        }
        Command::Extract {
            fasta,
            output,
            batch_size,
        } => {
            let count = extract_accessions(fasta, &output, batch_size, threads)?;
            println!("Wrote {count} accessions to {}", output.display());
        }
        Command::Clean {
            input,
            output,
            verbose,
        } => clean_fasta_headers(input, output.as_deref(), verbose, threads)?,
        Command::Grep {
            input,
            accessions,
            output,
            no_version,
            batch_size,
            verbose,
        } => {
            let totals = grep_fasta(
                input,
                &accessions,
                output,
                !no_version,
                batch_size,
                verbose,
                threads,
            )?;
            println!(
                "Finished grepping FASTA: requested={} scanned={} matched={} missing_accession={}",
                totals.requested, totals.scanned, totals.matched, totals.missing_accession
            );
        }
        Command::Filter {
            input,
            output,
            keep_taxids,
            remove_taxids,
            batch_size,
            verbose,
        } => {
            let (value, option, mode) = if let Some(value) = keep_taxids {
                (value, "--keep-taxids", FilterMode::Keep)
            } else {
                (
                    remove_taxids.expect("clap requires one filtering option"),
                    "--remove-taxids",
                    FilterMode::Remove,
                )
            };
            let taxa = parse_taxa(&value, option)?;
            let totals = filter_fasta(
                input,
                output.as_deref(),
                &taxa,
                mode,
                batch_size,
                verbose,
                threads,
            )?;
            println!(
                "Finished filtering FASTA: kept={} removed={} missing_accession={} missing_taxid={}",
                totals.kept, totals.removed, totals.missing_accession, totals.missing_taxid
            );
        }
    }
    Ok(())
}