chaintools 0.0.4

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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
// Copyright (c) 2026 Alejandro Gonzales-Irribarren <alejandrxgzi@gmail.com>
// Distributed under the terms of the Apache License, Version 2.0.

use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use chaintools::{io::storage::is_gz_path, StreamingReader};
use clap::{Args, ValueEnum};
#[cfg(feature = "gzip")]
use flate2::{read::MultiGzDecoder, write::GzEncoder, Compression};

use super::sort_core::{
    emit_sorted_chains, write_metadata_lines, SortAccumulator, SortCriterion,
    OUTPUT_BUFFER_CAPACITY,
};
use super::CliError;

const BYTES_PER_GB: f64 = 1_000_000_000.0;
const DEFAULT_MAX_GB: f64 = 16.0;
const COPY_BUFFER_CAPACITY: usize = 1024 * 1024;

/// Command-line arguments for the merge subcommand.
///
/// Provides options for merging multiple chain files together, with optional
/// sorting and gzip compression support.
///
/// # Examples
///
/// ```bash
/// chaintools merge --chains a.chain b.chain --out-chain merged.chain --sort-by score
/// ```
#[derive(Debug, Args)]
pub struct MergeArgs {
    #[arg(
        short = 'c',
        long = "chains",
        value_name = "PATH",
        num_args = 1..,
        conflicts_with = "file",
        required_unless_present = "file",
        help = "Input chain files to merge"
    )]
    chains: Option<Vec<PathBuf>>,

    #[arg(
        short = 'f',
        long = "file",
        value_name = "PATH",
        conflicts_with = "chains",
        required_unless_present = "chains",
        help = "Path to a file listing one input chain path per line"
    )]
    file: Option<PathBuf>,

    #[arg(
        short = 'o',
        long = "out-chain",
        value_name = "PATH",
        required = true,
        help = "Path for the merged chain output"
    )]
    out_chain: PathBuf,

    #[arg(
        short = 'S',
        long = "sort-by",
        value_name = "KEY",
        value_enum,
        help = "Sort merged output by the selected primary key"
    )]
    sort_by: Option<MergeSortBy>,

    #[arg(
        short = 'G',
        long = "gzip",
        help = "Compress merged output with gzip. Requires the `gzip` feature."
    )]
    gzip: bool,

    #[arg(
        short = 'M',
        long = "max-gb",
        value_name = "GB",
        default_value_t = DEFAULT_MAX_GB,
        help = "Maximum in-memory working set in gigabytes before spilling sorted runs to temporary files"
    )]
    max_gb: f64,
}

impl MergeArgs {
    fn max_in_memory_bytes(&self) -> Result<u64, CliError> {
        if !self.max_gb.is_finite() {
            return Err(CliError::Message(
                "--max-gb must be a finite number".to_owned(),
            ));
        }
        if self.max_gb <= 0.0 {
            return Err(CliError::Message(
                "--max-gb must be greater than zero".to_owned(),
            ));
        }

        let bytes = (self.max_gb * BYTES_PER_GB).ceil();
        if bytes > u64::MAX as f64 {
            return Err(CliError::Message(
                "--max-gb is too large to represent".to_owned(),
            ));
        }

        Ok(bytes as u64)
    }
}

/// Sort criteria for merged output.
///
/// # Variants
///
/// * `Score` - Sort by chain score (descending)
/// * `Id` - Sort by chain ID
/// * `Reference` - Sort by reference sequence name and position
/// * `Query` - Sort by query sequence name and position
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum MergeSortBy {
    Score,
    Id,
    Reference,
    Query,
}

impl MergeSortBy {
    fn criterion(self) -> SortCriterion {
        match self {
            MergeSortBy::Score => SortCriterion::Score,
            MergeSortBy::Id => SortCriterion::Id,
            MergeSortBy::Reference => SortCriterion::Reference,
            MergeSortBy::Query => SortCriterion::Query,
        }
    }
}

/// Runs the merge subcommand.
///
/// Merges multiple chain files into a single output file, with optional
/// sorting and gzip compression.
///
/// # Arguments
///
/// * `args` - Merge arguments with input paths and output
/// * `_stdin` - Unused (input via --chains or --file)
/// * `_stdout` - Unused (output via --out-chain)
/// * `_stderr` - Error/logging output
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
///
/// # Examples
///
/// ```bash
/// # Merge multiple files
/// chaintools merge --chains a.chain b.chain c.chain --out-chain merged.chain
///
/// # Merge and sort by score
/// chaintools merge --chains a.chain b.chain --out-chain sorted.chain --sort-by score
/// ```
pub fn run<R, W, E>(
    args: MergeArgs,
    _stdin: &mut R,
    _stdout: &mut W,
    _stderr: &mut E,
) -> Result<(), CliError>
where
    R: BufRead,
    W: Write,
    E: Write,
{
    validate_output_args(&args)?;
    let inputs = collect_input_paths(&args)?;
    validate_input_paths(&args.out_chain, &inputs)?;

    log::info!(
        "merge: {} input file(s) -> {}",
        inputs.len(),
        args.out_chain.display()
    );

    if let Some(sort_by) = args.sort_by {
        log::info!("merging sorted by {sort_by:?}");
        let max_in_memory_bytes = args.max_in_memory_bytes()?;
        let temp_dir = output_directory(&args.out_chain);
        let mut accumulator =
            SortAccumulator::new(sort_by.criterion(), max_in_memory_bytes, &temp_dir);

        for path in &inputs {
            log::debug!("reading {}", path.display());
            let mut reader = StreamingReader::from_path(path)?;
            accumulator.push_stream(&mut reader)?;
        }

        // Capture counts before `finish` consumes the accumulator.
        let chains = accumulator.chains_pushed();
        let runs_spilled = accumulator.runs_spilled();
        let (metadata, sorted) = accumulator.finish()?;
        emit_sorted_output(&args, &metadata, sorted, sort_by.criterion())?;
        super::log_summary(
            "merge",
            &[
                ("files", inputs.len() as u64),
                ("chains", chains),
                ("runs_spilled", runs_spilled),
            ],
        );
    } else {
        log::info!("concatenating {} input(s) (unsorted)", inputs.len());
        emit_unsorted_output(&args, &inputs)?;
        super::log_summary("merge", &[("files", inputs.len() as u64)]);
    }

    Ok(())
}

/// Validates output arguments for merge command.
#[cfg(feature = "gzip")]
fn validate_output_args(_args: &MergeArgs) -> Result<(), CliError> {
    Ok(())
}

#[cfg(not(feature = "gzip"))]
/// Validates output arguments for merge command.
///
/// Returns an error if gzip is requested but the gzip feature is not enabled.
fn validate_output_args(args: &MergeArgs) -> Result<(), CliError> {
    if args.gzip {
        return Err(CliError::Message(
            "--gzip requires chaintools to be built with the `gzip` feature".to_owned(),
        ));
    }
    Ok(())
}

/// Collects input chain file paths from arguments.
///
/// Reads paths from --chains directly or from a file listing paths.
///
/// # Arguments
///
/// * `args` - Merge command arguments
///
/// # Output
///
/// Returns `Ok(Vec<PathBuf>)` with input paths or `Err(CliError)` on failure
fn collect_input_paths(args: &MergeArgs) -> Result<Vec<PathBuf>, CliError> {
    if let Some(paths) = &args.chains {
        return Ok(paths.clone());
    }

    let list_path = args
        .file
        .as_ref()
        .expect("clap enforces either --chains or --file");
    let file = File::open(list_path)?;
    let mut reader = BufReader::with_capacity(COPY_BUFFER_CAPACITY, file);
    let mut line = String::new();
    let mut paths = Vec::new();

    loop {
        line.clear();
        let read = reader.read_line(&mut line)?;
        if read == 0 {
            break;
        }
        let trimmed = line.trim_end_matches(['\n', '\r']);
        if trimmed.trim().is_empty() {
            continue;
        }
        paths.push(PathBuf::from(trimmed.trim()));
    }

    if paths.is_empty() {
        return Err(CliError::Message(format!(
            "{} does not list any input chain files",
            list_path.display()
        )));
    }

    Ok(paths)
}

/// Validates that output path differs from all input paths.
///
/// Ensures the output chain file is not the same as any input file.
///
/// # Arguments
///
/// * `out_chain` - Output chain path
/// * `inputs` - Input chain paths
///
/// # Output
///
/// Returns `Ok(())` if valid or `Err(CliError)` if output matches an input
fn validate_input_paths(out_chain: &Path, inputs: &[PathBuf]) -> Result<(), CliError> {
    let output = normalize_output_path(out_chain)?;

    for input in inputs {
        let normalized_input = normalize_existing_path(input)?;
        if normalized_input == output {
            return Err(CliError::Message(format!(
                "--out-chain must not be the same path as input chain {}",
                input.display()
            )));
        }
    }

    Ok(())
}

/// Normalizes an existing input path to its canonical form.
///
/// # Arguments
///
/// * `path` - Input path to normalize
///
/// # Output
///
/// Returns `Ok(PathBuf)` with the canonical path or `Err(CliError)` on failure
fn normalize_existing_path(path: &Path) -> Result<PathBuf, CliError> {
    std::fs::canonicalize(path).map_err(CliError::from)
}

/// Normalizes an output path (which may not exist yet).
///
/// If the path exists, canonicalizes it. Otherwise, resolves relative to current directory.
///
/// # Arguments
///
/// * `path` - Output path to normalize
///
/// # Output
///
/// Returns `Ok(PathBuf)` with the normalized path or `Err(CliError)` on failure
fn normalize_output_path(path: &Path) -> Result<PathBuf, CliError> {
    if path.exists() {
        return normalize_existing_path(path);
    }

    if path.is_absolute() {
        return Ok(path.to_path_buf());
    }

    Ok(std::env::current_dir()?.join(path))
}

/// Returns the directory containing the output chain file.
///
/// # Arguments
///
/// * `out_chain` - Output chain path
///
/// # Output
///
/// Returns the parent directory or "." if no parent
fn output_directory(out_chain: &Path) -> PathBuf {
    out_chain
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
        .to_path_buf()
}

/// Emits sorted output by merging all runs.
///
/// Opens all run files, performs k-way merge, and writes sorted chains.
///
/// # Arguments
///
/// * `args` - Merge command arguments
/// * `metadata` - Metadata lines to output
/// * `sorted` - Sorted runs to merge
/// * `sort_by` - Sort criterion
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn emit_sorted_output(
    args: &MergeArgs,
    metadata: &[Vec<u8>],
    sorted: super::sort_core::SortedInput,
    sort_by: SortCriterion,
) -> Result<(), CliError> {
    #[cfg(feature = "gzip")]
    if args.gzip {
        let writer = open_output_writer(&args.out_chain)?;
        let mut encoder = GzEncoder::new(writer, Compression::fast());
        write_metadata_lines(&mut encoder, metadata)?;
        emit_sorted_chains(&mut encoder, sorted, sort_by)?;
        encoder.try_finish()?;
        encoder.get_mut().flush()?;
        return Ok(());
    }

    let mut writer = open_output_writer(&args.out_chain)?;
    write_metadata_lines(&mut writer, metadata)?;
    emit_sorted_chains(&mut writer, sorted, sort_by)?;
    writer.flush()?;
    Ok(())
}

/// Emits unsorted output by appending all input files.
///
/// Concatenates input chain files with proper record separation.
///
/// # Arguments
///
/// * `args` - Merge command arguments
/// * `inputs` - Input chain file paths
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn emit_unsorted_output(args: &MergeArgs, inputs: &[PathBuf]) -> Result<(), CliError> {
    #[cfg(feature = "gzip")]
    if args.gzip {
        let writer = open_output_writer(&args.out_chain)?;
        let mut encoder = GzEncoder::new(writer, Compression::fast());
        append_unsorted_inputs(inputs, &mut encoder)?;
        encoder.try_finish()?;
        encoder.get_mut().flush()?;
        return Ok(());
    }

    let mut writer = open_output_writer(&args.out_chain)?;
    append_unsorted_inputs(inputs, &mut writer)?;
    writer.flush()?;
    Ok(())
}

/// Opens a buffered writer for the output chain file.
///
/// # Arguments
///
/// * `path` - Output file path
///
/// # Output
///
/// Returns `Ok(BufWriter<File>)` or `Err(CliError)` on failure
fn open_output_writer(path: &Path) -> Result<BufWriter<File>, CliError> {
    let file = File::create(path)?;
    Ok(BufWriter::with_capacity(OUTPUT_BUFFER_CAPACITY, file))
}

/// Appends all unsorted input files to the writer.
///
/// # Arguments
///
/// * `inputs` - Input file paths
/// * `writer` - Output writer
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn append_unsorted_inputs<W: Write>(inputs: &[PathBuf], writer: &mut W) -> Result<(), CliError> {
    let mut boundary = BoundaryState::default();

    for path in inputs {
        append_unsorted_input(path, writer, &mut boundary)?;
    }

    Ok(())
}

/// Appends a single unsorted input file to the writer.
///
/// Handles gzip detection and decompression, ensuring proper record separation.
///
/// # Arguments
///
/// * `path` - Input file path
/// * `writer` - Output writer
/// * `boundary` - State for tracking record boundaries
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn append_unsorted_input<W: Write>(
    path: &Path,
    writer: &mut W,
    boundary: &mut BoundaryState,
) -> Result<(), CliError> {
    #[cfg(feature = "gzip")]
    if is_gz_path(path) {
        let file = File::open(path)?;
        let reader = BufReader::with_capacity(COPY_BUFFER_CAPACITY, file);
        let decoder = MultiGzDecoder::new(reader);
        let reader = BufReader::with_capacity(COPY_BUFFER_CAPACITY, decoder);
        return copy_reader(reader, writer, boundary);
    }

    #[cfg(not(feature = "gzip"))]
    if is_gz_path(path) {
        return Err(CliError::Chain(chaintools::io::storage::gzip_feature_error()));
    }

    let file = File::open(path)?;
    let reader = BufReader::with_capacity(COPY_BUFFER_CAPACITY, file);
    copy_reader(reader, writer, boundary)
}

/// Copies data from a reader to a writer, tracking boundaries.
///
/// Reads the entire reader and writes to the writer while observing
/// boundary state for record separation.
///
/// # Arguments
///
/// * `reader` - Input reader
/// * `writer` - Output writer
/// * `boundary` - State for tracking record boundaries
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn copy_reader<R: Read, W: Write>(
    mut reader: R,
    writer: &mut W,
    boundary: &mut BoundaryState,
) -> Result<(), CliError> {
    let mut buffer = [0u8; COPY_BUFFER_CAPACITY];
    let read = reader.read(&mut buffer)?;
    if read == 0 {
        return Ok(());
    }

    ensure_record_separator(writer, boundary)?;
    writer.write_all(&buffer[..read])?;
    boundary.observe(&buffer[..read]);

    loop {
        let read = reader.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        writer.write_all(&buffer[..read])?;
        boundary.observe(&buffer[..read]);
    }

    Ok(())
}

/// Ensures proper record separation between input files.
///
/// Adds blank lines if needed based on the trailing newlines of the previous file.
///
/// # Arguments
///
/// * `writer` - Output writer
/// * `boundary` - State for tracking record boundaries
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn ensure_record_separator<W: Write>(
    writer: &mut W,
    boundary: &mut BoundaryState,
) -> Result<(), CliError> {
    if !boundary.wrote_any {
        return Ok(());
    }

    match boundary.trailing_newlines() {
        0 => {
            writer.write_all(b"\n\n")?;
            boundary.observe(b"\n\n");
        }
        1 => {
            writer.write_all(b"\n")?;
            boundary.observe(b"\n");
        }
        _ => {}
    }

    Ok(())
}

#[derive(Default)]
struct BoundaryState {
    wrote_any: bool,
    penultimate: Option<u8>,
    last: Option<u8>,
}

impl BoundaryState {
    fn trailing_newlines(&self) -> u8 {
        match (self.penultimate, self.last) {
            (_, Some(b'\n')) if self.penultimate == Some(b'\n') => 2,
            (_, Some(b'\n')) => 1,
            _ => 0,
        }
    }

    fn observe(&mut self, buf: &[u8]) {
        if buf.is_empty() {
            return;
        }

        self.wrote_any = true;
        match buf.len() {
            1 => {
                self.penultimate = self.last;
                self.last = Some(buf[0]);
            }
            len => {
                self.penultimate = Some(buf[len - 2]);
                self.last = Some(buf[len - 1]);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::ffi::OsString;
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
    #[cfg(feature = "gzip")]
    use std::{fs, io::Cursor};

    #[derive(Debug, Parser)]
    struct MergeHarness {
        #[command(flatten)]
        args: MergeArgs,
    }

    static NEXT_TEMP_ID: AtomicUsize = AtomicUsize::new(0);

    struct TempPath {
        path: PathBuf,
    }

    impl TempPath {
        fn new(suffix: &str) -> Self {
            let id = NEXT_TEMP_ID.fetch_add(1, AtomicOrdering::Relaxed);
            let mut path = std::env::temp_dir();
            path.push(format!(
                "chaintools-merge-test-{}-{id}.{suffix}",
                std::process::id()
            ));
            Self { path }
        }

        fn arg(&self) -> OsString {
            self.path.as_os_str().to_owned()
        }
    }

    impl Drop for TempPath {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.path);
        }
    }

    fn arg(value: &str) -> OsString {
        OsString::from(value)
    }

    fn write_file(path: &Path, contents: &[u8]) {
        std::fs::write(path, contents).expect("write temp file");
    }

    #[cfg(feature = "gzip")]
    fn write_gzip(path: &Path, contents: &[u8]) {
        let file = File::create(path).expect("create gzip");
        let mut encoder = GzEncoder::new(file, Compression::fast());
        encoder.write_all(contents).expect("write gzip");
        encoder.finish().expect("finish gzip");
    }

    fn run_ok(args: Vec<OsString>) -> Vec<u8> {
        let cli = MergeHarness::try_parse_from(std::iter::once(arg("merge")).chain(args))
            .expect("merge args should parse");
        let mut stdin = std::io::Cursor::new(Vec::<u8>::new());
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        run(cli.args, &mut stdin, &mut stdout, &mut stderr).expect("merge should run");
        stdout
    }

    fn run_err(args: Vec<OsString>) -> CliError {
        let cli = MergeHarness::try_parse_from(std::iter::once(arg("merge")).chain(args))
            .expect("merge args should parse");
        let mut stdin = std::io::Cursor::new(Vec::<u8>::new());
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        run(cli.args, &mut stdin, &mut stdout, &mut stderr).expect_err("merge should fail")
    }

    #[test]
    fn merge_concatenates_inputs_in_order() {
        let input_a = TempPath::new("chain");
        let input_b = TempPath::new("chain");
        let output = TempPath::new("chain");
        write_file(
            &input_a.path,
            b"chain 10 chr1 100 + 0 10 qry1 100 + 0 10 1\n10\n",
        );
        write_file(
            &input_b.path,
            b"chain 20 chr2 100 + 0 20 qry2 100 + 0 20 2\n20\n\n",
        );

        let stdout = run_ok(vec![
            arg("--chains"),
            input_a.arg(),
            input_b.arg(),
            arg("--out-chain"),
            output.arg(),
        ]);

        assert_eq!(stdout, b"");
        assert_eq!(
            std::fs::read_to_string(&output.path).unwrap(),
            "chain 10 chr1 100 + 0 10 qry1 100 + 0 10 1\n10\n\nchain 20 chr2 100 + 0 20 qry2 100 + 0 20 2\n20\n\n"
        );
    }

    #[test]
    fn merge_reads_inputs_from_file_list() {
        let input_a = TempPath::new("chain");
        let input_b = TempPath::new("chain");
        let list = TempPath::new("txt");
        let output = TempPath::new("chain");
        write_file(
            &input_a.path,
            b"chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\n",
        );
        write_file(
            &input_b.path,
            b"chain 6 chr2 10 + 0 6 qry2 10 + 0 6 2\n6\n\n",
        );
        write_file(
            &list.path,
            format!("{}\n\n{}\n", input_a.path.display(), input_b.path.display()).as_bytes(),
        );

        run_ok(vec![
            arg("--file"),
            list.arg(),
            arg("--out-chain"),
            output.arg(),
        ]);

        assert_eq!(
            std::fs::read_to_string(&output.path).unwrap(),
            "chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\nchain 6 chr2 10 + 0 6 qry2 10 + 0 6 2\n6\n\n"
        );
    }

    #[test]
    fn merge_rejects_same_input_and_output_path() {
        let input = TempPath::new("chain");
        write_file(&input.path, b"chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\n");

        let err = run_err(vec![
            arg("--chains"),
            input.arg(),
            arg("--out-chain"),
            input.arg(),
        ]);

        assert!(err
            .to_string()
            .contains("--out-chain must not be the same path as input chain"));
    }

    #[test]
    fn merge_sorts_by_reference() {
        let input_a = TempPath::new("chain");
        let input_b = TempPath::new("chain");
        let output = TempPath::new("chain");
        write_file(
            &input_a.path,
            b"#a\nchain 5 chr2 100 + 0 5 qry2 100 + 0 5 2\n5\n\n",
        );
        write_file(
            &input_b.path,
            b"#b\nchain 5 chr1 100 + 0 5 qry1 100 + 0 5 1\n5\n\n",
        );

        run_ok(vec![
            arg("--chains"),
            input_a.arg(),
            input_b.arg(),
            arg("--out-chain"),
            output.arg(),
            arg("--sort-by"),
            arg("reference"),
        ]);

        assert_eq!(
            std::fs::read_to_string(&output.path).unwrap(),
            "#a\n#b\nchain 5 chr1 100 + 0 5 qry1 100 + 0 5 1\n5\n\nchain 5 chr2 100 + 0 5 qry2 100 + 0 5 2\n5\n\n"
        );
    }

    #[test]
    fn merge_sorts_by_id() {
        let input_a = TempPath::new("chain");
        let input_b = TempPath::new("chain");
        let output = TempPath::new("chain");
        write_file(
            &input_a.path,
            b"chain 5 chr2 100 + 0 5 qry2 100 + 0 5 20\n5\n\n",
        );
        write_file(
            &input_b.path,
            b"chain 9 chr1 100 + 0 5 qry1 100 + 0 5 10\n5\n\n",
        );

        run_ok(vec![
            arg("--chains"),
            input_a.arg(),
            input_b.arg(),
            arg("--out-chain"),
            output.arg(),
            arg("--sort-by"),
            arg("id"),
        ]);

        assert_eq!(
            std::fs::read_to_string(&output.path).unwrap(),
            "chain 9 chr1 100 + 0 5 qry1 100 + 0 5 10\n5\n\nchain 5 chr2 100 + 0 5 qry2 100 + 0 5 20\n5\n\n"
        );
    }

    #[cfg(feature = "gzip")]
    #[test]
    fn merge_reads_gzip_input_and_writes_gzip_output() {
        let input_a = TempPath::new("chain.gz");
        let input_b = TempPath::new("chain");
        let output = TempPath::new("chain.gz");
        write_gzip(&input_a.path, b"chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n");
        write_file(
            &input_b.path,
            b"chain 6 chr2 10 + 0 6 qry2 10 + 0 6 2\n6\n\n",
        );

        run_ok(vec![
            arg("--chains"),
            input_a.arg(),
            input_b.arg(),
            arg("--out-chain"),
            output.arg(),
            arg("--gzip"),
        ]);

        let mut decoder = MultiGzDecoder::new(Cursor::new(fs::read(&output.path).unwrap()));
        let mut decoded = String::new();
        decoder.read_to_string(&mut decoded).expect("decode gzip");

        assert_eq!(
            decoded,
            "chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\nchain 6 chr2 10 + 0 6 qry2 10 + 0 6 2\n6\n\n"
        );
    }

    #[cfg(not(feature = "gzip"))]
    #[test]
    fn merge_rejects_gzip_without_feature() {
        let input = TempPath::new("chain");
        let output = TempPath::new("chain.gz");
        write_file(&input.path, b"chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\n");

        let err = run_err(vec![
            arg("--chains"),
            input.arg(),
            arg("--out-chain"),
            output.arg(),
            arg("--gzip"),
        ]);

        assert!(err
            .to_string()
            .contains("--gzip requires chaintools to be built with the `gzip` feature"));
    }

    #[test]
    fn zero_memory_budget_is_rejected() {
        let input = TempPath::new("chain");
        let output = TempPath::new("chain");
        write_file(&input.path, b"chain 5 chr1 10 + 0 5 qry1 10 + 0 5 1\n5\n\n");

        let err = run_err(vec![
            arg("--chains"),
            input.arg(),
            arg("--out-chain"),
            output.arg(),
            arg("--sort-by"),
            arg("score"),
            arg("--max-gb"),
            arg("0"),
        ]);

        assert!(err
            .to_string()
            .contains("--max-gb must be greater than zero"));
    }
}