docterm 0.2.0

A TUI-first documentation browser for Dash/Zeal docsets, optimized for the terminal.
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
use std::{io::Read as _, path::Path};

use flate2::read::GzDecoder;
use quick_xml::Reader;
use quick_xml::escape::unescape;
use quick_xml::events::Event;
use tar::Archive;

use crate::error::FetchError;

/// Metadata extracted from a docset's `Info.plist`.
#[derive(Debug, Clone)]
pub struct PlistInfo {
    /// `CFBundleIdentifier` — machine-readable docset identifier.
    pub identifier: String,
    /// `CFBundleName` — human-readable display name.
    pub name: String,
    /// `dashIndexFilePath` — entry-point HTML path relative to `Documents/`.
    pub index_file: String,
}

/// Read all entries from a Dash `docSet.dsidx` SQLite file.
///
/// Returns `(name, type, path)` triples.  Returns `Err` if the file cannot
/// be opened or queried; the caller typically falls back to an empty list.
pub fn read_dsidx_entries(
    dsidx_path: &Path,
) -> Result<Vec<(String, String, String)>, rusqlite::Error> {
    let conn = rusqlite::Connection::open(dsidx_path)?;
    let mut stmt = conn.prepare("SELECT name, type, path FROM searchIndex")?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
        ))
    })?;
    rows.collect()
}

/// Parse an `Info.plist` XML document and return the fields relevant to docterm.
///
/// The plist format is a flat `<dict>` of alternating `<key>` / value tags.
/// Only `<string>` values are needed; boolean and integer tags are ignored.
fn parse_plist(xml: &str) -> Result<PlistInfo, FetchError> {
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);

    let mut current_tag: Vec<u8> = Vec::new();
    let mut current_key = String::new();
    let mut identifier = String::new();
    let mut name = String::new();
    let mut index_file = String::new();

    loop {
        match reader.read_event()? {
            Event::Start(e) => {
                current_tag = e.name().as_ref().to_vec();
            }
            Event::Text(e) => {
                let decoded = e.decode().map_err(quick_xml::Error::from)?;
                let text = unescape(&decoded)
                    .map_err(quick_xml::Error::from)?
                    .into_owned();
                match current_tag.as_slice() {
                    b"key" => current_key = text,
                    b"string" => match current_key.as_str() {
                        "CFBundleIdentifier" => identifier = text,
                        "CFBundleName" => name = text,
                        "dashIndexFilePath" => index_file = text,
                        _ => {}
                    },
                    _ => {}
                }
            }
            // Self-closing tags like <true/> and <false/> reset the current tag.
            Event::End(_) | Event::Empty(_) => current_tag.clear(),
            Event::Eof => break,
            _ => {}
        }
    }

    if identifier.is_empty() || name.is_empty() {
        return Err(FetchError::PlistParse(
            "missing required fields (CFBundleIdentifier or CFBundleName)".into(),
        ));
    }

    Ok(PlistInfo {
        identifier,
        name,
        index_file,
    })
}

/// Strip the archive prefix up to and including `Documents/`, returning the
/// path of a doc file relative to the docset's `Documents/` root.
///
/// Example: `Rust.docset/Contents/Resources/Documents/book/ch01.html`
///       →  `book/ch01.html`
fn doc_relative_path(full_path: &str) -> &str {
    const MARKER: &str = "Documents/";
    full_path
        .find(MARKER)
        .map(|i| &full_path[i + MARKER.len()..])
        .unwrap_or(full_path)
}

/// Reject archive entries whose paths are absolute or contain `..` segments.
///
/// The current pipeline keeps HTML bytes in memory only, so a traversing path
/// cannot escape onto disk today.  This check is defense-in-depth so a future
/// change that writes archive contents to disk cannot be tricked by a hostile
/// docset archive.
fn is_safe_archive_path(path: &str) -> bool {
    if path.is_empty() || path.starts_with('/') || path.starts_with('\\') {
        return false;
    }
    // Reject Windows drive letters like `C:\...`.
    if path.len() >= 2 && path.as_bytes()[1] == b':' {
        return false;
    }
    !path.split(['/', '\\']).any(|segment| segment == "..")
}

/// Open a `.tgz` docset archive, parse its `Info.plist`, and invoke `on_html`
/// for every HTML file found under `Contents/Resources/Documents/`.
///
/// `on_html(relative_path, raw_bytes)` — `relative_path` is relative to the
/// `Documents/` directory (e.g. `"book/ch01.html"`).
///
/// Also extracts the `docSet.dsidx` Dash search-index database (if present)
/// and returns its raw bytes as the second element of the result tuple.  The
/// caller is responsible for persisting the bytes to disk before opening them
/// with a SQLite driver.
///
/// This performs synchronous I/O; call it inside `tokio::task::spawn_blocking`
/// when used from an async context.
pub fn extract_docset<F>(
    path: &Path,
    mut on_html: F,
) -> Result<(PlistInfo, Option<Vec<u8>>), FetchError>
where
    F: FnMut(&str, &[u8]),
{
    let file = std::fs::File::open(path)?;
    let gz = GzDecoder::new(file);
    let mut archive = Archive::new(gz);

    let mut plist: Option<PlistInfo> = None;
    let mut dsidx: Option<Vec<u8>> = None;

    for entry in archive.entries()? {
        let mut entry = entry?;
        // Resolve the path to an owned String before we move into the entry.
        let path_str = entry.path()?.to_string_lossy().into_owned();

        // Defense-in-depth: skip entries with absolute or traversing paths.
        // See `is_safe_archive_path`.
        if !is_safe_archive_path(&path_str) {
            tracing::warn!(path = %path_str, "skipping unsafe archive entry");
            continue;
        }

        if path_str.ends_with("Contents/Info.plist") {
            let mut buf = Vec::new();
            entry.read_to_end(&mut buf)?;
            plist = Some(parse_plist(&String::from_utf8_lossy(&buf))?);
        } else if path_str.ends_with(".dsidx") {
            let mut buf = Vec::new();
            entry.read_to_end(&mut buf)?;
            dsidx = Some(buf);
        } else if path_str.contains("Documents/")
            && (path_str.ends_with(".html") || path_str.ends_with(".htm"))
        {
            let rel = doc_relative_path(&path_str).to_owned();
            let mut buf = Vec::new();
            entry.read_to_end(&mut buf)?;
            on_html(&rel, &buf);
        }
    }

    let info =
        plist.ok_or_else(|| FetchError::PlistParse("Info.plist not found in archive".into()))?;
    Ok((info, dsidx))
}

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

    const SAMPLE_PLIST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>rust</string>
<key>CFBundleName</key>
<string>Rust</string>
<key>dashIndexFilePath</key>
<string>doc.rust-lang.org/1.94.0/book/ch00-00-introduction.html</string>
<key>DocSetPlatformFamily</key>
<string>rust</string>
<key>isDashDocset</key>
<true/>
<key>isJavaScriptEnabled</key>
<true/>
</dict>
</plist>"#;

    // ── parse_plist ───────────────────────────────────────────────────────────

    #[test]
    fn plist_identifier() {
        let info = parse_plist(SAMPLE_PLIST).unwrap();
        assert_eq!(info.identifier, "rust");
    }

    #[test]
    fn plist_name() {
        let info = parse_plist(SAMPLE_PLIST).unwrap();
        assert_eq!(info.name, "Rust");
    }

    #[test]
    fn plist_index_file() {
        let info = parse_plist(SAMPLE_PLIST).unwrap();
        assert_eq!(
            info.index_file,
            "doc.rust-lang.org/1.94.0/book/ch00-00-introduction.html"
        );
    }

    #[test]
    fn plist_missing_identifier_returns_error() {
        let xml = r#"<plist><dict>
            <key>CFBundleName</key><string>Rust</string>
        </dict></plist>"#;
        assert!(parse_plist(xml).is_err());
    }

    #[test]
    fn plist_missing_name_returns_error() {
        let xml = r#"<plist><dict>
            <key>CFBundleIdentifier</key><string>rust</string>
        </dict></plist>"#;
        assert!(parse_plist(xml).is_err());
    }

    #[test]
    fn plist_empty_index_file_is_allowed() {
        let xml = r#"<plist><dict>
            <key>CFBundleIdentifier</key><string>rust</string>
            <key>CFBundleName</key><string>Rust</string>
        </dict></plist>"#;
        let info = parse_plist(xml).unwrap();
        assert!(info.index_file.is_empty());
    }

    // ── doc_relative_path ─────────────────────────────────────────────────────

    #[test]
    fn relative_path_strips_prefix() {
        let full = "Rust.docset/Contents/Resources/Documents/book/ch01.html";
        assert_eq!(doc_relative_path(full), "book/ch01.html");
    }

    #[test]
    fn relative_path_top_level_file() {
        let full = "Rust.docset/Contents/Resources/Documents/index.html";
        assert_eq!(doc_relative_path(full), "index.html");
    }

    #[test]
    fn relative_path_no_marker_returns_full() {
        let full = "some/other/path/file.html";
        assert_eq!(doc_relative_path(full), full);
    }

    // ── is_safe_archive_path ──────────────────────────────────────────────────

    #[test]
    fn safe_path_allows_normal_docset_entries() {
        assert!(is_safe_archive_path(
            "Rust.docset/Contents/Resources/Documents/book/ch01.html"
        ));
        assert!(is_safe_archive_path("Rust.docset/Contents/Info.plist"));
        assert!(is_safe_archive_path("a/b/c"));
    }

    #[test]
    fn safe_path_rejects_absolute_unix() {
        assert!(!is_safe_archive_path("/etc/passwd"));
    }

    #[test]
    fn safe_path_rejects_absolute_windows_backslash() {
        assert!(!is_safe_archive_path("\\Windows\\system32"));
    }

    #[test]
    fn safe_path_rejects_windows_drive_letter() {
        assert!(!is_safe_archive_path("C:/Windows/system32"));
        assert!(!is_safe_archive_path("D:\\evil.exe"));
    }

    #[test]
    fn safe_path_rejects_parent_dir_segments() {
        assert!(!is_safe_archive_path("../etc/passwd"));
        assert!(!is_safe_archive_path("foo/../../etc/passwd"));
        assert!(!is_safe_archive_path("foo\\..\\bar"));
        assert!(!is_safe_archive_path(".."));
    }

    #[test]
    fn safe_path_rejects_empty() {
        assert!(!is_safe_archive_path(""));
    }

    #[test]
    fn safe_path_allows_dot_segments() {
        // `./foo` is normalised to `foo`; not a traversal risk on its own.
        assert!(is_safe_archive_path("./foo/bar"));
    }

    // ── extract_docset ────────────────────────────────────────────────────────

    fn make_tgz(files: &[(&str, &[u8])]) -> Vec<u8> {
        use flate2::{Compression, write::GzEncoder};

        let buf = Vec::new();
        let gz = GzEncoder::new(buf, Compression::default());
        let mut ar = tar::Builder::new(gz);

        for (path, data) in files {
            let mut header = tar::Header::new_gnu();
            header.set_size(data.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            ar.append_data(&mut header, path, *data).unwrap();
        }

        let gz = ar.into_inner().unwrap();
        gz.finish().unwrap()
    }

    #[test]
    fn extract_docset_parses_plist_and_html() {
        use std::io::Write as _;

        let tgz = make_tgz(&[
            ("Rust.docset/Contents/Info.plist", SAMPLE_PLIST.as_bytes()),
            (
                "Rust.docset/Contents/Resources/Documents/index.html",
                b"<html><body><main><h1>Hello</h1></main></body></html>",
            ),
            (
                "Rust.docset/Contents/Resources/Documents/book/ch01.html",
                b"<html><body><p>Chapter 1</p></body></html>",
            ),
        ]);

        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(&tgz).unwrap();

        let mut collected: Vec<(String, Vec<u8>)> = Vec::new();
        let (info, dsidx) = extract_docset(tmp.path(), |rel, bytes| {
            collected.push((rel.to_owned(), bytes.to_owned()));
        })
        .unwrap();

        assert_eq!(info.identifier, "rust");
        assert!(dsidx.is_none(), "no dsidx in this archive");
        assert_eq!(info.name, "Rust");
        assert_eq!(collected.len(), 2);

        let paths: Vec<&str> = collected.iter().map(|(p, _)| p.as_str()).collect();
        assert!(paths.contains(&"index.html"));
        assert!(paths.contains(&"book/ch01.html"));
    }

    #[test]
    fn extract_docset_skips_non_html_files() {
        use std::io::Write as _;

        let tgz = make_tgz(&[
            ("Rust.docset/Contents/Info.plist", SAMPLE_PLIST.as_bytes()),
            (
                "Rust.docset/Contents/Resources/Documents/style.css",
                b"body {}",
            ),
            (
                "Rust.docset/Contents/Resources/Documents/index.html",
                b"<html/>",
            ),
        ]);

        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(&tgz).unwrap();

        let mut count = 0usize;
        extract_docset(tmp.path(), |_, _| count += 1).unwrap();
        assert_eq!(count, 1, "only the HTML file should trigger the callback");
    }

    #[test]
    fn extract_docset_captures_dsidx_bytes() {
        use std::io::Write as _;

        let dummy_dsidx = b"SQLite format 3\x00fakedata";
        let tgz = make_tgz(&[
            ("Rust.docset/Contents/Info.plist", SAMPLE_PLIST.as_bytes()),
            ("Rust.docset/Contents/Resources/docSet.dsidx", dummy_dsidx),
        ]);

        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(&tgz).unwrap();

        let (_info, dsidx) = extract_docset(tmp.path(), |_, _| {}).unwrap();
        assert!(dsidx.is_some(), "dsidx bytes must be captured");
        assert_eq!(dsidx.unwrap(), dummy_dsidx);
    }

    // NOTE: end-to-end coverage of `is_safe_archive_path` inside
    // `extract_docset` isn't possible with the safe `tar::Builder` API — it
    // itself refuses to serialise entries whose paths contain `..`.  The
    // pure-function unit tests above (`safe_path_rejects_*`) cover the
    // predicate, and the wiring in `extract_docset` is a two-line `continue`.

    #[test]
    fn extract_docset_missing_plist_returns_error() {
        use std::io::Write as _;

        let tgz = make_tgz(&[(
            "Rust.docset/Contents/Resources/Documents/index.html",
            b"<html/>",
        )]);

        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(&tgz).unwrap();

        assert!(extract_docset(tmp.path(), |_, _| {}).is_err());
    }

    // ── read_dsidx_entries ────────────────────────────────────────────────────

    fn make_dsidx(path: &Path) {
        let conn = rusqlite::Connection::open(path).unwrap();
        conn.execute_batch(
            "CREATE TABLE searchIndex (
                id   INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                type TEXT NOT NULL,
                path TEXT NOT NULL
            );
            INSERT INTO searchIndex (name, type, path) VALUES
                ('Vec',      'Struct',   'std/vec/struct.Vec.html'),
                ('Vec::new', 'Method',   'std/vec/struct.Vec.html#method.new'),
                ('spawn',    'Function', 'tokio/fn.spawn.html');",
        )
        .unwrap();
    }

    #[test]
    fn read_dsidx_returns_all_entries() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("docSet.dsidx");
        make_dsidx(&path);
        let entries = read_dsidx_entries(&path).unwrap();
        assert_eq!(entries.len(), 3);
    }

    #[test]
    fn read_dsidx_entry_fields() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("docSet.dsidx");
        make_dsidx(&path);
        let entries = read_dsidx_entries(&path).unwrap();
        let vec_entry = entries.iter().find(|(n, _, _)| n == "Vec").unwrap();
        assert_eq!(vec_entry.1, "Struct");
        assert_eq!(vec_entry.2, "std/vec/struct.Vec.html");
    }

    #[test]
    fn read_dsidx_missing_file_returns_err() {
        let result = read_dsidx_entries(std::path::Path::new("/nonexistent/docSet.dsidx"));
        assert!(result.is_err());
    }
}