chaintools 0.0.12

work with .chain files in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// Copyright (c) 2026 Alejandro Gonzales-Irribarren <alejandrxgzi@gmail.com>
// Distributed under the terms of the Apache License, Version 2.0.

pub mod anti_repeat;
pub mod bed;
pub mod compare;
pub mod convert;
pub mod filter;
pub mod liftover;
pub mod merge;
pub mod score;
pub mod sort;
mod sort_core;
pub mod split;
pub mod stats;
pub mod swap;

use std::fmt;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};

use chaintools::ChainError;
use clap::{Parser, Subcommand};
use log::LevelFilter;

/// Command-line interface for chaintools.
///
/// Provides the main CLI entry point with global options for
/// thread count and logging level, plus subcommands.
#[derive(Debug, Parser)]
#[command(name = "chaintools")]
#[command(about = "work with .chain files in rust")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(author = env!("CARGO_PKG_AUTHORS"))]
pub struct Cli {
    #[arg(
        short = 't',
        long,
        global = true,
        value_name = "N",
        help_heading = "Global Options",
        default_value_t = num_cpus::get()
    )]
    threads: usize,

    #[arg(
        long,
        global = true,
        value_name = "LEVEL",
        help = "Set CLI logging level: off, error, warn, info, debug, trace",
        help_heading = "Global Options"
    )]
    level: Option<LevelFilter>,

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

/// Subcommands available in the chaintools CLI.
#[derive(Debug, Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Command {
    #[command(
        name = "antirepeat",
        alias = "anti-repeat",
        about = "Filter chains dominated by repeats or degenerate DNA"
    )]
    AntiRepeat(anti_repeat::AntiRepeatArgs),
    #[command(about = "Convert chain files to BED")]
    Bed(bed::BedArgs),
    #[command(about = "Compare exact mappings, coverage, ambiguity, and continuity")]
    Compare(compare::CompareArgs),
    #[command(about = "Convert chain files to VCF, MAF, or BAM")]
    Convert(convert::ConvertArgs),
    #[command(about = "Filter chain files")]
    Filter(filter::FilterArgs),
    #[command(about = "Map BED coordinates through a chain (reference/target -> query)")]
    Liftover(liftover::LiftoverArgs),
    #[command(about = "Merge chain files")]
    Merge(merge::MergeArgs),
    #[command(about = "Recompute chain scores from sequence (UCSC chainScore-compatible)")]
    Score(score::ScoreArgs),
    #[command(about = "Split chain files")]
    Split(split::SplitArgs),
    #[command(about = "Sort chain files")]
    Sort(sort::SortArgs),
    #[command(about = "Summarize alignment, gap, and continuity statistics")]
    Stats(stats::StatsArgs),
    #[command(about = "Swap the target and query sides of chains (UCSC chainSwap)")]
    Swap(swap::SwapArgs),
}

impl std::fmt::Display for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Command::AntiRepeat(_) => f.write_str("antirepeat"),
            Command::Bed(_) => f.write_str("bed"),
            Command::Compare(_) => f.write_str("compare"),
            Command::Convert(_) => f.write_str("convert"),
            Command::Filter(_) => f.write_str("filter"),
            Command::Liftover(_) => f.write_str("liftover"),
            Command::Merge(_) => f.write_str("merge"),
            Command::Score(_) => f.write_str("score"),
            Command::Split(_) => f.write_str("split"),
            Command::Sort(_) => f.write_str("sort"),
            Command::Stats(_) => f.write_str("stats"),
            Command::Swap(_) => f.write_str("swap"),
        }
    }
}

/// Errors that can occur during CLI execution.
///
/// # Variants
///
/// * `Message` - String message error
/// * `Io` - I/O error
/// * `Chain` - Chain parsing error
///
/// # Examples
///
/// ```ignore
/// use chaintools::cli::CliError;
///
/// // Create a message error
/// let msg_err = CliError::Message("invalid configuration".to_string());
///
/// // Handle different error types
/// match msg_err {
///     CliError::Message(msg) => eprintln!("Error: {}", msg),
///     CliError::Io(err) => eprintln!("I/O error: {}", err),
///     CliError::Chain(err) => eprintln!("Chain error: {}", err),
/// }
/// ```
#[derive(Debug)]
pub enum CliError {
    Message(String),
    Io(io::Error),
    Chain(ChainError),
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CliError::Message(message) => f.write_str(message),
            CliError::Io(err) => write!(f, "I/O error: {err}"),
            CliError::Chain(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for CliError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CliError::Io(err) => Some(err),
            CliError::Chain(err) => Some(err),
            CliError::Message(_) => None,
        }
    }
}

impl From<io::Error> for CliError {
    fn from(value: io::Error) -> Self {
        CliError::Io(value)
    }
}

impl From<ChainError> for CliError {
    fn from(value: ChainError) -> Self {
        CliError::Chain(value)
    }
}

/// Main CLI entry point.
///
/// Executes the appropriate subcommand with given I/O streams.
///
/// # Arguments
///
/// * `cli` - Parsed CLI arguments
/// * `stdin` - Input stream
/// * `stdout` - Output stream
/// * `stderr` - Error output stream
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
pub fn run<R, W, E>(cli: Cli, stdin: &mut R, stdout: &mut W, stderr: &mut E) -> Result<(), CliError>
where
    R: BufRead,
    W: Write,
    E: Write,
{
    configure_threads(cli.threads)?;
    let level = resolve_log_level(cli.level);
    configure_logging(level)?;

    log::info!(
        "chaintools [{}] v{}",
        &cli.command,
        env!("CARGO_PKG_VERSION")
    );
    let start = std::time::Instant::now();

    let result = match cli.command {
        Command::AntiRepeat(args) => anti_repeat::run(args, stdin, stdout, stderr),
        Command::Bed(args) => bed::run(args, stdin, stdout, stderr),
        Command::Compare(args) => compare::run(args, stdin, stdout, stderr),
        Command::Convert(args) => convert::run(args, stdin, stdout, stderr),
        Command::Filter(args) => filter::run(args, stdin, stdout, stderr),
        Command::Liftover(args) => liftover::run(args, stdin, stdout, stderr),
        Command::Merge(args) => merge::run(args, stdin, stdout, stderr),
        Command::Score(args) => score::run(args, stdin, stdout, stderr),
        Command::Split(args) => split::run(args, stdin, stdout, stderr),
        Command::Sort(args) => sort::run(args, stdin, stdout, stderr),
        Command::Stats(args) => stats::run(args, stdin, stdout, stderr),
        Command::Swap(args) => swap::run(args, stdin, stdout, stderr),
    };

    log::info!("Execution time: {:?}", start.elapsed());
    result
}

/// Resolves the effective log level for a run.
///
/// Logging is verbose by default: every tool defaults to `Info`, regardless of
/// whether chains are written to a file or to standard output. Logs are emitted
/// on stderr (via `simple_logger`), so they never corrupt the stdout chain
/// stream. An explicit `--level` is always honored; `--level off` silences all
/// logging.
///
/// # Arguments
///
/// * `requested` - The `--level` value, if the user supplied one
///
/// # Output
///
/// Returns the `LevelFilter` to install
fn resolve_log_level(requested: Option<LevelFilter>) -> LevelFilter {
    requested.unwrap_or(LevelFilter::Info)
}

/// Emits a uniform end-of-run summary line at the `Info` level.
///
/// Produces `"{tool} complete: k1=v1, k2=v2, ..."` so every subcommand reports
/// its final counts in a consistent shape.
///
/// # Arguments
///
/// * `tool` - Subcommand name (e.g. `"score"`)
/// * `fields` - Ordered `(label, value)` pairs to render
///
/// # Examples
///
/// ```ignore
/// log_summary("score", &[("read", 1200), ("kept", 980), ("dropped", 220)]);
/// // INFO  score complete: read=1200, kept=980, dropped=220
/// ```
pub(crate) fn log_summary(tool: &str, fields: &[(&str, u64)]) {
    if !log::log_enabled!(log::Level::Info) {
        return;
    }
    let rendered = fields
        .iter()
        .map(|(label, value)| format!("{label}={value}"))
        .collect::<Vec<_>>()
        .join(", ");
    log::info!("{tool} complete: {rendered}");
}

/// Verifies that required and optionally-provided input files exist.
///
/// Runs as an upfront pre-flight check so a missing input fails immediately
/// with a clear message, before any engine is built, any standard input is
/// read, or any output is written. Uses [`Path::try_exists`] so a permission
/// or I/O error while checking is reported distinctly from a genuine absence.
///
/// # Arguments
///
/// * `required` - `(label, path)` pairs that must exist
/// * `optional` - `(label, maybe_path)` pairs; `None` means "use a default such
///   as standard input" and is skipped
///
/// # Output
///
/// Returns `Ok(())` if every present path exists, or `Err(CliError::Message)`
/// naming the first offending file.
///
/// # Examples
///
/// ```ignore
/// ensure_inputs_exist(
///     &[("reference", &args.reference), ("query", &args.query)],
///     &[("input chain", args.chain.as_deref())],
/// )?;
/// ```
pub(crate) fn ensure_inputs_exist(
    required: &[(&str, &Path)],
    optional: &[(&str, Option<&Path>)],
) -> Result<(), CliError> {
    for (label, path) in required {
        check_input_exists(label, path)?;
    }
    for (label, path) in optional {
        if let Some(path) = path {
            check_input_exists(label, path)?;
        }
    }
    Ok(())
}

/// Checks that a chain's block list accounts for exactly both header spans.
///
/// `sum(sizes) + sum(inner target gaps)` must equal the target span, and the
/// same must hold on the query side. Widened to `u64` so a malformed chain is
/// reported instead of overflowing. Shared by `swap` and `liftover`, which both
/// have to trust these spans before transforming coordinates.
///
/// # Arguments
///
/// * `chain` - The chain to check
/// * `offset` - Byte offset of the chain header, for error reporting
///
/// # Output
///
/// Returns `Ok(())` when both sums match, or `Err(ChainError::Format)`
pub(crate) fn validate_block_spans(
    chain: &chaintools::OwnedChain,
    offset: usize,
) -> Result<(), ChainError> {
    let mut reference = 0u64;
    let mut query = 0u64;
    let last = chain.blocks.len().saturating_sub(1);
    for (index, block) in chain.blocks.iter().enumerate() {
        reference += u64::from(block.size);
        query += u64::from(block.size);
        if index < last {
            reference += u64::from(block.gap_reference);
            query += u64::from(block.gap_query);
        }
    }

    let reference_span = span_len(chain.reference_start, chain.reference_end, offset, "target")?;
    let query_span = span_len(chain.query_start, chain.query_end, offset, "query")?;
    if reference != u64::from(reference_span) {
        return Err(span_error(
            offset,
            "chain blocks do not sum to the target span",
        ));
    }
    if query != u64::from(query_span) {
        return Err(span_error(
            offset,
            "chain blocks do not sum to the query span",
        ));
    }
    Ok(())
}

fn span_len(start: u32, end: u32, offset: usize, label: &str) -> Result<u32, ChainError> {
    end.checked_sub(start)
        .ok_or_else(|| span_error(offset, format!("{label} span is inverted")))
}

fn span_error(offset: usize, message: impl Into<String>) -> ChainError {
    ChainError::Format {
        offset,
        msg: message.into().into(),
    }
}

/// Rejects an output path that resolves to the same file as the input chain.
///
/// Writing the output would truncate the input before it is read, so this is a
/// pre-flight check rather than a recoverable error. Nothing to do when the
/// input is standard input.
///
/// # Arguments
///
/// * `label` - Name of the output flag, used in the error message
/// * `output` - The requested output path
/// * `input` - The input chain path, or `None` for standard input
///
/// # Output
///
/// Returns `Ok(())` when the paths differ, or `Err(CliError::Message)`
pub(crate) fn validate_distinct_paths(
    label: &str,
    output: &Path,
    input: Option<&Path>,
) -> Result<(), CliError> {
    let Some(input) = input else {
        return Ok(());
    };
    if resolve_path(output)? == resolve_path(input)? {
        return Err(CliError::Message(format!(
            "{label} must not be the same path as input chain {}",
            input.display()
        )));
    }
    Ok(())
}

/// Resolves a path for comparison, tolerating a not-yet-created output file.
fn resolve_path(path: &Path) -> Result<PathBuf, CliError> {
    if path.exists() {
        return Ok(std::fs::canonicalize(path)?);
    }

    let parent = path.parent().unwrap_or_else(|| Path::new(""));
    let parent = if parent.as_os_str().is_empty() {
        std::env::current_dir()?
    } else {
        std::fs::canonicalize(parent)?
    };
    let file_name = path
        .file_name()
        .ok_or_else(|| CliError::Message(format!("invalid path {}", path.display())))?;
    Ok(parent.join(file_name))
}

/// Checks that a single input file exists, mapping the outcome to a `CliError`.
fn check_input_exists(label: &str, path: &Path) -> Result<(), CliError> {
    match path.try_exists() {
        Ok(true) => Ok(()),
        Ok(false) => Err(CliError::Message(format!(
            "{label} file does not exist: {}",
            path.display()
        ))),
        Err(err) => Err(CliError::Message(format!(
            "cannot access {label} file {}: {err}",
            path.display()
        ))),
    }
}

/// Configures the logging subsystem with the given level.
fn configure_logging(level: LevelFilter) -> Result<(), CliError> {
    log::set_max_level(level);
    if level == LevelFilter::Off {
        return Ok(());
    }

    simple_logger::SimpleLogger::new()
        .with_level(level)
        .init()
        .map_err(|err| CliError::Message(format!("failed to initialize logger: {err}")))?;
    log::set_max_level(level);
    Ok(())
}

#[cfg(feature = "parallel")]
/// Configures the global rayon thread pool.
fn configure_threads(threads: usize) -> Result<(), CliError> {
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build()
        .map_err(|err| {
            CliError::Message(format!("failed to configure global thread pool: {err}"))
        })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn parses_reserved_globals_before_subcommand() {
        let cli = Cli::try_parse_from([
            "chaintools",
            "--threads",
            "4",
            "--level",
            "debug",
            "filter",
            "--chain",
            "input.chain",
        ])
        .expect("global options should parse");

        assert_eq!(cli.threads, 4);
        assert_eq!(cli.level, Some(LevelFilter::Debug));
        assert!(matches!(cli.command, Command::Filter(_)));
    }

    #[test]
    fn parses_reserved_globals_after_subcommand() {
        let cli = Cli::try_parse_from([
            "chaintools",
            "filter",
            "--threads",
            "2",
            "--level",
            "trace",
            "--chain",
            "input.chain",
        ])
        .expect("global options should parse after subcommand");

        assert_eq!(cli.threads, 2);
        assert_eq!(cli.level, Some(LevelFilter::Trace));
        assert!(matches!(cli.command, Command::Filter(_)));
    }

    #[test]
    fn bed_long_short_parses_as_subcommand_flag() {
        let cli = Cli::try_parse_from(["chaintools", "bed", "-L", "--side", "reference"])
            .expect("bed long-format short flag should parse after subcommand");

        assert_eq!(cli.level, None);
        assert!(matches!(cli.command, Command::Bed(_)));
    }

    #[test]
    fn rejects_unknown_log_level() {
        let err = Cli::try_parse_from(["chaintools", "--level", "chatty", "filter"])
            .expect_err("unknown log level should be rejected");

        assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
    }

    #[test]
    fn defaults_to_info_when_unspecified() {
        let cli = Cli::try_parse_from(["chaintools", "filter"]).expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Info);
    }

    #[test]
    fn honors_requested_level() {
        let cli =
            Cli::try_parse_from(["chaintools", "--level", "debug", "filter"]).expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Debug);
    }

    #[test]
    fn explicit_off_silences_logging() {
        let cli =
            Cli::try_parse_from(["chaintools", "--level", "off", "filter"]).expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Off);
    }

    #[test]
    fn stdout_output_still_defaults_to_info() {
        // Verbose-by-default: a tool writing chains to stdout (no --out-chain)
        // still logs at Info on stderr; previously this was forced Off.
        let cli = Cli::try_parse_from([
            "chaintools",
            "anti-repeat",
            "--reference",
            "target.2bit",
            "--query",
            "query.2bit",
        ])
        .expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Info);
    }

    #[test]
    fn stdout_output_honors_requested_level() {
        // This combination (stdout output + explicit --level) used to be
        // rejected; verbose-by-default now allows it.
        let cli =
            Cli::try_parse_from(["chaintools", "--level", "info", "sort"]).expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Info);
    }

    #[test]
    fn out_chain_output_defaults_to_info() {
        let cli = Cli::try_parse_from(["chaintools", "filter", "--out-chain", "out.chain"])
            .expect("args parse");
        assert_eq!(resolve_log_level(cli.level), LevelFilter::Info);
    }
}

#[cfg(not(feature = "parallel"))]
/// Returns an error if threads is requested without parallel feature.
fn configure_threads(threads: usize) -> Result<(), CliError> {
    if threads == 1 {
        return Ok(());
    } else {
        return Err(CliError::Message(
            "--threads requires chaintools to be built with the `parallel` feature".to_owned(),
        ));
    }
}