sucher 0.6.0

A fast terminal viewer for files that are awkward in a browser: markdown, spreadsheets, PDF, images, video, docx, pptx, Keynote, archives and binary.
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
// The single file-classification registry (ADR 0001).
//
// One `Format` enum answers both questions the app used to answer with two
// diverging tables: *which viewer opens a file* and *how the browser presents
// it* (colour / glyph / label). Adding a file type touches exactly one place.
//
// Classification is a PURE function `classify(ext, is_dir, head)` — extension
// first, with a byte `head` disambiguating only unknown / extension-less files —
// unit-tested without the filesystem. The thin `classify_path` wrapper does the
// only IO (reading the head when the extension can't decide).

use crate::highlight;
use crate::theme;
use ratatui::style::Color;
use std::fs;
use std::io::Read;
use std::path::Path;

/// How many bytes of a file's head disambiguate an unknown extension.
const HEAD_BYTES: usize = 8 * 1024;

/// A classified file. Each variant answers "which viewer opens me" (`opens`)
/// and "how does the browser show me" (`color` / `glyph` / `label`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Format {
    Directory,
    Markdown,
    Html,
    Text,
    Sheet,
    // Only ever constructed with the `data` feature (ADR 0016); the variant is
    // unconditional so the grid's dispatch arms compile in the lean build too.
    #[cfg_attr(not(feature = "data"), allow(dead_code))]
    Data,
    Image,
    Svg,
    Pdf,
    Video,
    Docx,
    Pptx,
    Epub,
    Ipynb,
    Keynote,
    Doc,
    Audio,
    Archive,
    Binary,
}

/// Classify a file from its (already-lowercased) extension, its directory-ness,
/// and an optional byte `head`. PURE — no IO.
///
/// A known extension wins outright and ignores `head`. For an unknown or empty
/// extension we consult `head`: textual → [`Format::Text`], otherwise
/// [`Format::Binary`]. `head == None` (the directory list, which classifies by
/// extension only) also yields `Binary` for an unknown extension.
pub fn classify(ext: &str, is_dir: bool, head: Option<&[u8]>) -> Format {
    if is_dir {
        return Format::Directory;
    }
    match ext {
        "md" | "markdown" | "mdx" => Format::Markdown,
        // HTML is reduced to markdown (ADR 0008), not shown as source.
        "html" | "htm" | "xhtml" => Format::Html,
        // Tabular data — including csv/tsv — belongs in the grid viewer.
        "xlsx" | "xls" | "xlsm" | "xlsb" | "ods" | "csv" | "tsv" => Format::Sheet,
        // Data files (ADR 0016): the DuckDB-backed grid — Parquet, JSONL, SQLite,
        // DuckDB. Feature-gated: without `data` these fall through to their prior
        // handling (parquet → Binary hexdump, jsonl → Text), so the classifier is
        // honest about what this build can actually open.
        #[cfg(feature = "data")]
        "parquet" | "pq" | "jsonl" | "ndjson" | "sqlite" | "sqlite3" | "db" | "db3" | "duckdb"
        | "ddb" => Format::Data,
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tiff" | "tif" | "ico" => Format::Image,
        "pdf" => Format::Pdf,
        "mp4" | "mov" | "mkv" | "webm" | "avi" | "m4v" => Format::Video,
        "docx" => Format::Docx,
        "pptx" => Format::Pptx,
        // EPUB is a zip of XHTML reduced to markdown, like docx/pptx (ADR 0009).
        "epub" => Format::Epub,
        // A Jupyter notebook is a JSON document of cells reduced to markdown.
        "ipynb" => Format::Ipynb,
        "key" => Format::Keynote,
        "doc" | "rtf" | "odt" | "ppt" => Format::Doc,
        "mp3" | "wav" | "flac" | "ogg" | "m4a" | "aac" => Format::Audio,
        "zip" | "gz" | "tar" | "tgz" | "bz2" | "xz" | "7z" | "rar" | "zst" => Format::Archive,
        // SVG is XML markup we can now both rasterise and show as source.
        "svg" => Format::Svg,
        // Any other known source / plain-text extension.
        e if highlight::is_text_ext(e) => Format::Text,
        // Unknown or empty extension: the head decides text vs binary.
        _ => match head {
            Some(h) if looks_textual(h) => Format::Text,
            _ => Format::Binary,
        },
    }
}

/// True when `head` looks like text: no NUL byte AND valid UTF-8, tolerating an
/// incomplete final multi-byte sequence split by the read boundary (its
/// `valid_up_to()` falls within the last 3 bytes of the head). Empty head → false.
fn looks_textual(head: &[u8]) -> bool {
    if head.is_empty() || head.contains(&0) {
        return false;
    }
    match std::str::from_utf8(head) {
        Ok(_) => true,
        // Accept only a truncated trailing char (a UTF-8 sequence is at most 4
        // bytes, so a boundary split leaves ≤ 3 valid-but-incomplete bytes).
        Err(e) => e.valid_up_to() >= head.len().saturating_sub(3),
    }
}

/// IO wrapper around [`classify`]: computes `is_dir` and the lowercased
/// extension, and — only when the extension can't decide — reads up to
/// [`HEAD_BYTES`] of the file to distinguish text from binary.
pub fn classify_path(path: &Path) -> Format {
    let is_dir = path.is_dir();
    let ext = path
        .extension()
        .map(|e| e.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    // `classify` with no head returns `Binary` exactly for an unknown/empty
    // extension; that's the only case worth a file read.
    match classify(&ext, is_dir, None) {
        Format::Binary => classify(&ext, is_dir, read_head(path).as_deref()),
        other => other,
    }
}

/// Read up to [`HEAD_BYTES`] of a file's head; None on any IO error.
fn read_head(path: &Path) -> Option<Vec<u8>> {
    let mut f = fs::File::open(path).ok()?;
    let mut buf = vec![0u8; HEAD_BYTES];
    let n = f.read(&mut buf).ok()?;
    buf.truncate(n);
    Some(buf)
}

impl Format {
    /// Human-readable category name (browser label + "no viewer for …" text).
    pub fn label(&self) -> &'static str {
        match self {
            Format::Directory => "Directory",
            Format::Markdown => "Markdown",
            Format::Html => "HTML",
            Format::Text => "Text",
            Format::Sheet => "Spreadsheet",
            Format::Data => "Data",
            Format::Image => "Image",
            Format::Svg => "SVG",
            Format::Pdf => "PDF",
            Format::Video => "Video",
            Format::Docx => "Word Document",
            Format::Pptx => "Presentation",
            Format::Epub => "E-book",
            Format::Ipynb => "Notebook",
            Format::Keynote => "Keynote",
            Format::Doc => "Document",
            Format::Audio => "Audio",
            Format::Archive => "Archive",
            Format::Binary => "File",
        }
    }

    /// Single-column glyph for the browser list; ASCII-safe Unicode.
    pub fn glyph(&self) -> &'static str {
        match self {
            Format::Directory => "",
            Format::Image | Format::Svg => "",
            Format::Video => "",
            Format::Audio => "",
            Format::Pdf => "",
            Format::Sheet => "",
            // A distinct glyph from Sheet's — same grid viewer, different family
            // (queryable data files vs spreadsheets).
            Format::Data => "",
            Format::Keynote => "",
            Format::Markdown
            | Format::Html
            | Format::Docx
            | Format::Pptx
            | Format::Epub
            | Format::Ipynb
            | Format::Doc => "",
            Format::Text => "",
            Format::Archive => "",
            Format::Binary => "·",
        }
    }

    /// Palette colour for the browser (see `crate::theme`).
    pub fn color(&self) -> Color {
        match self {
            Format::Directory => theme::palette().dir,
            Format::Image | Format::Svg | Format::Keynote => theme::palette().image,
            Format::Video | Format::Audio => theme::palette().video,
            Format::Pdf => theme::palette().pdf,
            // Data files share the tabular colour — they open in the same grid.
            Format::Sheet | Format::Data => theme::palette().sheet,
            Format::Markdown
            | Format::Html
            | Format::Docx
            | Format::Pptx
            | Format::Epub
            | Format::Ipynb
            | Format::Doc => theme::palette().doc,
            Format::Text => theme::palette().code,
            Format::Archive => theme::palette().archive,
            Format::Binary => theme::palette().other,
        }
    }

    /// Does Sucher have a viewer that opens this format?
    pub fn opens(&self) -> bool {
        matches!(
            self,
            Format::Markdown
                | Format::Html
                | Format::Text
                | Format::Sheet
                | Format::Data
                | Format::Image
                | Format::Svg
                | Format::Pdf
                | Format::Video
                | Format::Docx
                | Format::Pptx
                | Format::Epub
                | Format::Ipynb
                | Format::Keynote
                | Format::Archive
                | Format::Binary
        )
    }
}

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

    /// Classify a file by extension only (as the directory list does).
    fn by_ext(ext: &str) -> Format {
        classify(ext, false, None)
    }

    #[test]
    fn directories_win_over_any_extension() {
        assert_eq!(classify("rs", true, None), Format::Directory);
        assert_eq!(classify("", true, None), Format::Directory);
    }

    #[test]
    fn tabular_text_is_a_sheet() {
        // ADR-0001 divergence: browser said "Spreadsheet", Enter opened Markdown.
        assert_eq!(by_ext("csv"), Format::Sheet);
        assert_eq!(by_ext("tsv"), Format::Sheet);
        assert_eq!(by_ext("xlsx"), Format::Sheet);
    }

    #[test]
    fn svg_is_its_own_format() {
        // Now rasterisable (resvg) *and* shown as source — its own viewer.
        assert_eq!(by_ext("svg"), Format::Svg);
        assert!(by_ext("svg").opens());
    }

    #[test]
    fn office_binaries_are_doc_not_markdown() {
        // ADR-0001 divergence: read_to_string on binary → Markdown garbage.
        assert_eq!(by_ext("doc"), Format::Doc);
        assert_eq!(by_ext("rtf"), Format::Doc);
        assert_eq!(by_ext("ppt"), Format::Doc);
    }

    #[test]
    fn pptx_and_keynote_have_their_own_viewers() {
        // pptx → markdown conversion; key → embedded-preview image.
        assert_eq!(by_ext("pptx"), Format::Pptx);
        assert_eq!(by_ext("key"), Format::Keynote);
        assert!(by_ext("pptx").opens());
        assert!(by_ext("key").opens());
    }

    #[test]
    fn epub_is_its_own_format() {
        // ADR 0009: .epub is a zip of XHTML reduced to markdown, like docx/pptx.
        assert_eq!(by_ext("epub"), Format::Epub);
        assert!(by_ext("epub").opens());
    }

    #[test]
    fn ipynb_is_its_own_format() {
        // A Jupyter notebook is a JSON document of cells reduced to markdown.
        assert_eq!(by_ext("ipynb"), Format::Ipynb);
        assert!(by_ext("ipynb").opens());
    }

    #[cfg(feature = "data")]
    #[test]
    fn data_files_are_their_own_format() {
        // ADR 0016: DuckDB-backed grid — Parquet, JSONL, SQLite, DuckDB.
        for e in [
            "parquet", "pq", "jsonl", "ndjson", "sqlite", "sqlite3", "db", "db3", "duckdb", "ddb",
        ] {
            assert_eq!(by_ext(e), Format::Data, "{e} should be Data");
        }
        assert!(by_ext("parquet").opens());
        // A `.json` file is usually one document, not a table — it stays Text.
        assert_eq!(by_ext("json"), Format::Text);
    }

    #[test]
    fn source_code_is_text_not_markdown() {
        // ADR-0001 divergence: any code fell through to Markdown, mangled.
        assert_eq!(by_ext("rs"), Format::Text);
        assert_eq!(by_ext("py"), Format::Text);
        assert_eq!(by_ext("json"), Format::Text);
    }

    #[test]
    fn html_is_its_own_format() {
        // ADR 0008: .html reduces to markdown, it no longer opens as Text source.
        assert_eq!(by_ext("html"), Format::Html);
        assert_eq!(by_ext("htm"), Format::Html);
        assert_eq!(by_ext("xhtml"), Format::Html);
        assert!(by_ext("html").opens());
    }

    #[test]
    fn known_media_and_doc_extensions() {
        assert_eq!(by_ext("md"), Format::Markdown);
        assert_eq!(by_ext("docx"), Format::Docx);
        assert_eq!(by_ext("png"), Format::Image);
        assert_eq!(by_ext("pdf"), Format::Pdf);
        assert_eq!(by_ext("mp4"), Format::Video);
        assert_eq!(by_ext("mp3"), Format::Audio);
        assert_eq!(by_ext("zip"), Format::Archive);
    }

    #[test]
    fn unknown_extension_without_head_is_binary() {
        // The directory list passes no head: unknown ext → Binary (by extension).
        assert_eq!(by_ext("wat"), Format::Binary);
        assert_eq!(by_ext(""), Format::Binary);
    }

    #[test]
    fn unknown_extension_with_textual_head_is_text() {
        let head = b"hello, this is plain text\n";
        assert_eq!(classify("", false, Some(head)), Format::Text);
        assert_eq!(classify("wat", false, Some(head)), Format::Text);
    }

    #[test]
    fn unknown_extension_with_nul_head_is_binary() {
        let head = b"\x89PNG\x00\x01\x02binary";
        assert_eq!(classify("", false, Some(head)), Format::Binary);
        assert_eq!(classify("wat", false, Some(head)), Format::Binary);
    }

    #[test]
    fn known_extension_ignores_head() {
        // A `.rs` stays Text even with binary bytes; extension wins.
        assert_eq!(classify("rs", false, Some(b"\x00\x01")), Format::Text);
    }

    #[test]
    fn looks_textual_boundary_split_char() {
        // "é" is 0xC3 0xA9; drop the trailing byte to simulate a read that split
        // a multi-byte char at the head boundary. Still textual.
        let mut head = "text ends with é".as_bytes().to_vec();
        head.pop(); // remove 0xA9, leaving a lone 0xC3 lead byte
        assert!(looks_textual(&head));
    }

    #[test]
    fn looks_textual_rejects_nul_and_empty() {
        assert!(!looks_textual(b"has a \x00 nul"));
        assert!(!looks_textual(b""));
        assert!(looks_textual(b"plain ascii"));
    }

    #[test]
    fn opens_matches_the_viewable_set() {
        for f in [
            Format::Markdown,
            Format::Html,
            Format::Text,
            Format::Sheet,
            Format::Image,
            Format::Svg,
            Format::Pdf,
            Format::Video,
            Format::Docx,
            Format::Pptx,
            Format::Epub,
            Format::Ipynb,
            Format::Keynote,
            Format::Archive,
            Format::Binary,
        ] {
            assert!(f.opens(), "{f:?} should open");
        }
        for f in [Format::Directory, Format::Doc, Format::Audio] {
            assert!(!f.opens(), "{f:?} should not open");
        }
    }
}