whittle 1.0.0

Coordinate-consistent trimming of long-read uBAM and tagged FASTQ
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
//! Input and output format detection, and the FASTQ, BAM and directory readers.

pub mod bam;
pub mod bgzf;
pub mod counting;
pub mod dir;
pub mod fastq;
pub mod tagged;

use std::io::Read;
use std::path::Path;

/// A read-file format as detected from an extension or stream header, and
/// the value of `--input-format`/`--output-format`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Format {
    /// Plain FASTQ.
    Fastq,
    /// gzip-compressed FASTQ.
    FastqGz,
    /// BGZF-compressed FASTQ.
    #[value(name = "fastq-bgz", alias = "fastq-bgzf")]
    FastqBgzf,
    /// Unaligned BAM.
    Bam,
}

impl Format {
    /// Returns the human-facing label used in log and summary output: `FASTQ`,
    /// `FASTQ.gz`, `FASTQ.bgz`, `BAM`.
    pub fn label(&self) -> &'static str {
        match self {
            Format::Fastq => "FASTQ",
            Format::FastqGz => "FASTQ.gz",
            Format::FastqBgzf => "FASTQ.bgz",
            Format::Bam => "BAM",
        }
    }

    /// Returns the spelling `--input-format`/`--output-format` accept for this
    /// format, for messages that suggest the flag.
    pub fn flag_value(&self) -> &'static str {
        match self {
            Format::Fastq => "fastq",
            Format::FastqGz => "fastq-gz",
            Format::FastqBgzf => "fastq-bgz",
            Format::Bam => "bam",
        }
    }

    /// Returns the coarse format family that decides whether an (in, out) pair
    /// reads as a conversion in the startup banner's operation line: the
    /// FASTQ variants collapse to the `FASTQ` family (a `Fastq` to `FastqGz`
    /// run is a compression change, not a format conversion), while `Bam` is
    /// its own family.
    pub fn family(&self) -> &'static str {
        match self {
            Format::Fastq | Format::FastqGz | Format::FastqBgzf => "FASTQ",
            Format::Bam => "BAM",
        }
    }
}

/// Detects the format from the file extension: `.fastq`/`.fq`, their `.gz`
/// variants, a bare `.gz`, `.bgz`/`.bgzf`, and `.bam`.
pub fn from_extension(path: &Path) -> Option<Format> {
    let name = path.file_name()?.to_str()?.to_ascii_lowercase();
    // Any trailing `.gz` is gzip-compressed FASTQ (the only gzip format handled),
    // so a bare `out.gz` is `FastqGz` as well as `.fastq.gz`/`.fq.gz`.
    if name.ends_with(".bgz") || name.ends_with(".bgzf") {
        Some(Format::FastqBgzf)
    } else if name.ends_with(".gz") {
        Some(Format::FastqGz)
    } else if name.ends_with(".fastq") || name.ends_with(".fq") {
        Some(Format::Fastq)
    } else if name.ends_with(".bam") {
        Some(Format::Bam)
    } else {
        None
    }
}

/// Detects the input format from the first bytes of a stream whose extension
/// does not decide it, or stdin: gzip magic is gzipped FASTQ and `@` is FASTQ.
/// The caller has already ruled out a BGZF header, which BAM and BGZF FASTQ
/// share; only the decoded first block tells them apart (`detect_bgzf_block`).
pub fn detect_input(sniff: &[u8]) -> anyhow::Result<Format> {
    if sniff.starts_with(&[0x1f, 0x8b]) {
        Ok(Format::FastqGz)
    } else if sniff.starts_with(b"BAM\x01") {
        // A bare (non-BGZF) BAM stream cannot be read: the reader always wraps
        // input in a BGZF decoder. Detection fails with a precise message
        // instead of surfacing an opaque BGZF framing error.
        anyhow::bail!(
            "input looks like an uncompressed (non-BGZF) BAM stream; a BGZF-compressed BAM \
             is required (re-compress with `samtools view -b`)"
        )
    } else if sniff.first() == Some(&b'@') {
        Ok(Format::Fastq)
    } else {
        anyhow::bail!("cannot determine input format; pass --input-format")
    }
}

/// Returns true when a stream detected as `detected` may be read under a
/// forced `--input-format` of `forced`: the same format, or BGZF FASTQ under
/// `fastq-gz`, since a BGZF stream is valid gzip.
pub fn forced_format_accepts(forced: Format, detected: Format) -> bool {
    forced == detected || (forced == Format::FastqGz && detected == Format::FastqBgzf)
}

/// Returns advisory text when an output path carries an extension that names
/// no supported format (`out.fasta`, `out.txt`), so the fallback to `resolved`
/// is visible rather than silent. `None` for stdout, a path without an
/// extension, or a recognized extension.
pub fn unknown_extension_warning(path: Option<&Path>, resolved: Format) -> Option<String> {
    let path = path?;
    let name = path.file_name()?.to_str()?;
    let ext = name
        .rsplit_once('.')
        .filter(|(stem, _)| !stem.is_empty())?
        .1;
    if ext.is_empty() || from_extension(path).is_some() {
        return None;
    }
    Some(format!(
        "-o/--output extension .{ext} names no supported format; writing {} (pass --output-format \
         to choose)",
        resolved.label()
    ))
}

/// Returns advisory text when an explicit `--input-format`/`--output-format`
/// (`forced`) disagrees with what `path`'s extension suggests, e.g.
/// `--output-format fastq` on an `out.fastq.gz` path. `None` when there is no
/// forced format, the path has no recognized extension, the path is
/// stdin/stdout (`None`), or the two agree. `flag` names the CLI flag for the
/// message.
pub fn format_mismatch_warning(
    flag: &str,
    forced: Option<Format>,
    path: Option<&Path>,
) -> Option<String> {
    let forced = forced?;
    let detected = from_extension(path?)?;
    (detected != forced).then(|| {
        format!(
            "{flag} {} but the file extension looks like {}",
            forced.label(),
            detected.label()
        )
    })
}

/// Returns true if `sniff` begins with a BGZF block header: gzip magic, deflate
/// method and the `FEXTRA` flag carrying the mandatory `BC` subfield. This
/// distinguishes a BGZF stream from plain-gzip FASTQ, which shares the leading
/// `1f 8b` but sets neither `FEXTRA` nor `BC`. Requires the full 18-byte block
/// header.
pub(crate) fn is_bgzf(sniff: &[u8]) -> bool {
    sniff.len() >= 18
        && sniff[0] == 0x1f
        && sniff[1] == 0x8b
        && sniff[2] == 0x08 // CM = DEFLATE
        && (sniff[3] & 0x04) != 0 // FLG.FEXTRA set
        && sniff[12] == b'B' // first extra subfield SI1
        && sniff[13] == b'C' // SI2; "BC" marks BGZF
}

/// Returns true if the file at `path` starts with a BGZF block header. Best
/// effort for thread budgeting: a file that cannot be read is not BGZF here and
/// reports its error when opened for records.
pub fn is_bgzf_file(path: &Path) -> bool {
    let mut header = [0u8; 18];
    std::fs::File::open(path)
        .and_then(|mut f| f.read_exact(&mut header))
        .is_ok_and(|()| is_bgzf(&header))
}

/// Fills `buf` from `source` until it is full or the source ends, since one
/// `read` may return fewer bytes than asked for. Returns the number of bytes
/// read.
pub(crate) fn fill(source: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
    let mut n = 0;
    while n < buf.len() {
        let r = source.read(&mut buf[n..])?;
        if r == 0 {
            break;
        }
        n += r;
    }
    Ok(n)
}

/// Tells BGZF from plain gzip on a stream whose extension says `.gz`, by the
/// first block header. The probed bytes are replayed ahead of `source`, so the
/// stream is unchanged. BGZF is framed in independent blocks that inflate on
/// several threads; plain gzip decodes on one.
pub fn probe_gz(source: &mut Box<dyn Read + Send>) -> anyhow::Result<Format> {
    let mut probe = [0u8; 18];
    let n = fill(source, &mut probe)?;
    let format = if is_bgzf(&probe[..n]) {
        Format::FastqBgzf
    } else {
        Format::FastqGz
    };
    let rest = std::mem::replace(source, Box::new(std::io::empty()));
    *source = Box::new(std::io::Cursor::new(probe[..n].to_vec()).chain(rest));
    Ok(format)
}

/// Identifies the payload carried by one complete BGZF block. BAM begins with
/// `BAM\x01`; FASTQ begins with `@`. A block without payload, as in the
/// end-of-file marker that is all an empty `bgzip` output holds, is an empty
/// BGZF FASTQ: a BAM stream always opens with its header. The caller replays
/// the original compressed block into the selected reader after this probe.
pub(crate) fn detect_bgzf_block(block: &[u8]) -> anyhow::Result<Format> {
    let mut reader = noodles_bgzf::io::Reader::new(std::io::Cursor::new(block));
    let mut probe = [0u8; 4];
    let n = fill(&mut reader, &mut probe)?;
    if n == 0 {
        Ok(Format::FastqBgzf)
    } else if probe[..n].starts_with(b"BAM\x01") {
        Ok(Format::Bam)
    } else if probe.first() == Some(&b'@') {
        Ok(Format::FastqBgzf)
    } else {
        anyhow::bail!("BGZF input is neither BAM nor FASTQ")
    }
}

/// Resolves the output format from the path extension, else mirrors the input
/// format, except that output is never auto-compressed: a `.gz` (`FastqGz`)
/// input with no output extension defaults to plain `Fastq`, so gzip output
/// happens only when the caller asks (`-o *.gz` or `--output-format fastq-gz`).
pub fn resolve_output(path: Option<&Path>, input: Format) -> Format {
    // An explicit output extension always wins.
    if let Some(f) = path.and_then(from_extension) {
        return f;
    }
    match input {
        Format::FastqGz | Format::FastqBgzf => Format::Fastq,
        other => other,
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;

    #[test]
    fn format_labels() {
        assert_eq!(Format::Fastq.label(), "FASTQ");
        assert_eq!(Format::FastqGz.label(), "FASTQ.gz");
        assert_eq!(Format::FastqBgzf.label(), "FASTQ.bgz");
        assert_eq!(Format::Bam.label(), "BAM");
    }

    #[test]
    fn format_families() {
        assert_eq!(Format::Fastq.family(), "FASTQ");
        assert_eq!(Format::FastqGz.family(), "FASTQ");
        assert_eq!(Format::FastqBgzf.family(), "FASTQ");
        assert_eq!(Format::Bam.family(), "BAM");
    }

    #[test]
    fn extensions() {
        assert_eq!(from_extension(Path::new("x.fastq")), Some(Format::Fastq));
        assert_eq!(from_extension(Path::new("x.fq")), Some(Format::Fastq));
        assert_eq!(
            from_extension(Path::new("x.fastq.gz")),
            Some(Format::FastqGz)
        );
        assert_eq!(from_extension(Path::new("x.fq.gz")), Some(Format::FastqGz));
        assert_eq!(
            from_extension(Path::new("x.fastq.bgz")),
            Some(Format::FastqBgzf)
        );
        assert_eq!(
            from_extension(Path::new("x.fq.bgzf")),
            Some(Format::FastqBgzf)
        );
        assert_eq!(from_extension(Path::new("x.gz")), Some(Format::FastqGz)); // bare .gz
        assert_eq!(from_extension(Path::new("x.bam")), Some(Format::Bam));
        assert_eq!(from_extension(Path::new("x.txt")), None);
    }

    #[test]
    fn stdin_sniff_falls_back_to_magic() {
        // gzip magic `1f 8b` is `FastqGz`; `@` is `Fastq`.
        assert_eq!(detect_input(&[0x1f, 0x8b, 0x08]).unwrap(), Format::FastqGz);
        assert_eq!(detect_input(b"@read").unwrap(), Format::Fastq);
        let err = detect_input(b"").unwrap_err().to_string();
        assert!(err.contains("--input-format"), "Got: {err}");
    }

    /// A bare `BAM\x01` stream (no BGZF framing) cannot be read by the
    /// BGZF-wrapping reader, so detection fails with a clear message rather
    /// than claiming `Format::Bam` and surfacing an opaque BGZF error.
    #[test]
    fn naked_non_bgzf_bam_is_rejected() {
        let err = detect_input(b"BAM\x01rest").unwrap_err().to_string();
        assert!(
            err.to_ascii_lowercase().contains("bgzf"),
            "Message should name BGZF, got: {err}"
        );
    }

    #[test]
    fn format_mismatch_warning_fires_on_disagreement() {
        let w = format_mismatch_warning(
            "--output-format",
            Some(Format::Fastq),
            Some(Path::new("out.fastq.gz")),
        );
        assert_eq!(
            w.as_deref(),
            Some("--output-format FASTQ but the file extension looks like FASTQ.gz")
        );
    }

    #[test]
    fn format_mismatch_warning_silent_when_absent_or_agreeing() {
        // No forced format, a matching extension, an unknown extension, and
        // stdin all stay silent.
        assert_eq!(
            format_mismatch_warning("--input-format", None, Some(Path::new("x.bam"))),
            None
        );
        assert_eq!(
            format_mismatch_warning(
                "--input-format",
                Some(Format::Bam),
                Some(Path::new("x.bam"))
            ),
            None
        );
        assert_eq!(
            format_mismatch_warning(
                "--input-format",
                Some(Format::Bam),
                Some(Path::new("x.txt"))
            ),
            None
        );
        assert_eq!(
            format_mismatch_warning("--input-format", Some(Format::Bam), None),
            None
        );
    }

    /// A BGZF header (gzip magic, FLG.FEXTRA, "BC" subfield) can carry BAM or
    /// FASTQ; `is_bgzf` tells it from a plain gzip header, whose length alone
    /// does not decide.
    #[test]
    fn is_bgzf_needs_the_fextra_flag_and_the_bc_subfield() {
        let mut header = vec![
            0x1f, 0x8b, 0x08, 0x04, // magic, CM=deflate, FLG=FEXTRA
            0x00, 0x00, 0x00, 0x00, // MTIME
            0x00, 0xff, // XFL, OS
            0x06, 0x00, // XLEN = 6
            b'B', b'C', 0x02, 0x00, // "BC" subfield, SLEN=2
            0x1b, 0x00, // BSIZE
        ];
        assert!(is_bgzf(&header));

        // A plain-gzip stream (FLG = 0, no BC) is not BGZF even with a
        // full-length header present.
        header[3] = 0x00; // clear FEXTRA
        assert!(!is_bgzf(&header));
        assert_eq!(detect_input(&header).unwrap(), Format::FastqGz);

        // A gzip-magic buffer shorter than a block header cannot be BGZF.
        assert!(!is_bgzf(&[0x1f, 0x8b, 0x08, 0x04]));
    }

    /// `fill` reads until the buffer is full or the source ends, across a
    /// source that returns one byte per `read`.
    #[test]
    fn fill_reads_until_full_or_end() {
        struct OneByte<'a>(&'a [u8]);
        impl Read for OneByte<'_> {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                match (self.0.split_first(), buf.first_mut()) {
                    (Some((&b, rest)), Some(slot)) => {
                        *slot = b;
                        self.0 = rest;
                        Ok(1)
                    },
                    _ => Ok(0),
                }
            }
        }
        let mut buf = [0u8; 4];
        assert_eq!(fill(&mut OneByte(b"abcdef"), &mut buf).unwrap(), 4);
        assert_eq!(&buf, b"abcd");
        assert_eq!(fill(&mut OneByte(b"ab"), &mut buf).unwrap(), 2);
        assert_eq!(&buf[..2], b"ab");
    }

    #[test]
    fn uppercase_extensions_are_recognized() {
        assert_eq!(
            from_extension(Path::new("X.FASTQ.GZ")),
            Some(Format::FastqGz)
        );
        assert_eq!(from_extension(Path::new("X.FQ")), Some(Format::Fastq));
        assert_eq!(
            from_extension(Path::new("X.Fastq.BGZ")),
            Some(Format::FastqBgzf)
        );
        assert_eq!(from_extension(Path::new("X.BAM")), Some(Format::Bam));
    }

    #[test]
    fn is_bgzf_file_reads_the_block_header() {
        use std::io::Write;

        let dir = tempfile::tempdir().unwrap();
        let mut w = noodles_bgzf::io::Writer::new(Vec::new());
        w.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        let bgzf = dir.path().join("a.fastq.gz");
        std::fs::write(&bgzf, w.finish().unwrap()).unwrap();
        assert!(is_bgzf_file(&bgzf));

        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        let gz = dir.path().join("b.fastq.gz");
        std::fs::write(&gz, enc.finish().unwrap()).unwrap();
        assert!(!is_bgzf_file(&gz));

        let short = dir.path().join("c.fastq.gz");
        std::fs::write(&short, [0x1f, 0x8b, 0x08]).unwrap();
        assert!(!is_bgzf_file(&short));
        assert!(!is_bgzf_file(&dir.path().join("missing.fastq.gz")));
    }

    fn read_all(source: &mut Box<dyn Read + Send>) -> Vec<u8> {
        let mut out = Vec::new();
        source.read_to_end(&mut out).unwrap();
        out
    }

    #[test]
    fn probe_gz_tells_bgzf_from_plain_gzip_and_replays_the_bytes() {
        use std::io::Write;

        let mut w = noodles_bgzf::io::Writer::new(Vec::new());
        w.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        let bgzf = w.finish().unwrap();
        let mut source: Box<dyn Read + Send> = Box::new(std::io::Cursor::new(bgzf.clone()));
        assert_eq!(probe_gz(&mut source).unwrap(), Format::FastqBgzf);
        assert_eq!(read_all(&mut source), bgzf);

        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        enc.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        let gz = enc.finish().unwrap();
        let mut source: Box<dyn Read + Send> = Box::new(std::io::Cursor::new(gz.clone()));
        assert_eq!(probe_gz(&mut source).unwrap(), Format::FastqGz);
        assert_eq!(read_all(&mut source), gz);

        // Shorter than a block header: plain gzip, bytes preserved.
        let short = vec![0x1f, 0x8b, 0x08];
        let mut source: Box<dyn Read + Send> = Box::new(std::io::Cursor::new(short.clone()));
        assert_eq!(probe_gz(&mut source).unwrap(), Format::FastqGz);
        assert_eq!(read_all(&mut source), short);
    }

    #[test]
    fn complete_bgzf_fastq_block_is_identified() {
        use std::io::Write;

        let mut writer = noodles_bgzf::io::Writer::new(Vec::new());
        writer.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        let compressed = writer.finish().unwrap();
        let first_block_size =
            usize::from(u16::from_le_bytes([compressed[16], compressed[17]])) + 1;
        assert_eq!(
            detect_bgzf_block(&compressed[..first_block_size]).unwrap(),
            Format::FastqBgzf
        );
    }

    #[test]
    fn output_mirrors_input_when_no_path() {
        assert_eq!(resolve_output(None, Format::Bam), Format::Bam);
        assert_eq!(resolve_output(None, Format::Fastq), Format::Fastq);
        assert_eq!(
            resolve_output(Some(Path::new("o.bam")), Format::Fastq),
            Format::Bam
        );
    }

    #[test]
    fn output_never_auto_compresses_gz_input() {
        // A `.gz` input with no output path or format defaults to plain FASTQ;
        // output is never auto-compressed.
        assert_eq!(resolve_output(None, Format::FastqGz), Format::Fastq);
        // gzip output is available when requested via a `.gz` output path
        // extension.
        assert_eq!(
            resolve_output(Some(Path::new("o.fastq.gz")), Format::Fastq),
            Format::FastqGz
        );
    }
}