doiget-cli 0.8.12

doiget CLI binary
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
//! End-to-end tests for `doiget info` and `doiget list-recent`.
//!
//! Strategy: seed a `FsStore` rooted at a per-test `tempfile::TempDir`,
//! then invoke the freshly-built `doiget` binary as a subprocess with
//! `DOIGET_STORE_ROOT` pointing at that tempdir. This guarantees no test
//! ever touches the real `~/papers/`, and because env mutation happens
//! ONLY on the child process (via `assert_cmd::Command::env`), the tests
//! are safe to run in parallel without `serial_test` coordination.
//!
//! The two assertions per subcommand:
//!
//! 1. Exit status is success.
//! 2. Stdout contains an expected substring (paper title for `info`,
//!    safekey + title for `list-recent`).
//!
//! No assertions are made about the exact byte-for-byte stdout layout;
//! that lets the underlying serializer evolve (e.g. toml-rs upgrades)
//! without breaking these tests.

// Tests are panic-on-failure by design; relax the workspace-wide lints
// that ban `expect`/`unwrap`/`panic` in production code.
#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]

use std::collections::BTreeMap;

use assert_cmd::Command;
use camino::Utf8PathBuf;
use chrono::TimeZone;
use predicates::prelude::*;
use tempfile::TempDir;

use doiget_core::store::{DoigetExtension, FsStore, Metadata, Store};
use doiget_core::{Doi, Safekey, SCHEMA_VERSION};

/// Convert a `TempDir`'s path to a `Utf8PathBuf` so it can drive
/// `FsStore::new` (which is camino-only). Panics if the temp path is not
/// UTF-8 — on every platform we test, the system temp dir is ASCII.
fn utf8_path(dir: &TempDir) -> Utf8PathBuf {
    Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).expect("temp dir path must be UTF-8")
}

/// Build a small `Metadata` fixture with the given DOI suffix, title, and
/// fetched-at year. All other fields are constant.
fn fixture(doi_suffix: &str, title: &str, year: i32, fetched_year: i32) -> (Safekey, Metadata) {
    let doi = format!("10.1234/{doi_suffix}");
    let ref_ = doiget_core::Ref::Doi(Doi::parse(&doi).expect("valid DOI"));
    let safekey = ref_.safekey();
    let m = Metadata {
        schema_version: SCHEMA_VERSION.to_string(),
        title: title.to_string(),
        authors: vec!["Alice Researcher".to_string()],
        year: Some(year),
        doi: Some(Doi::parse(&doi).expect("valid DOI")),
        arxiv_id: None,
        arxiv_categories: vec![],
        abstract_: None,
        venue: Some("Phys. Rev. X".to_string()),
        volume: None,
        issue: None,
        pages: None,
        publisher: None,
        issn: None,
        isbn: None,
        type_: Some("journal-article".to_string()),
        keywords: vec![],
        url: None,
        pdf_path: None,
        doiget: Some(DoigetExtension {
            fetched_at: chrono::Utc
                .with_ymd_and_hms(fetched_year, 5, 6, 12, 0, 0)
                .single()
                .expect("valid timestamp"),
            source: "unpaywall".to_string(),
            license: "CC-BY-4.0".to_string(),
            oa_status: None,
            size_bytes: 1234,
            mcp_call_id: None,
            tags: Vec::new(),
            collections: Vec::new(),
            annotation: None,
        }),
        other: BTreeMap::new(),
    };
    (safekey, m)
}

/// Seed a temp store with two distinct entries and return the (TempDir
/// guard, store-root) pair. The guard MUST be kept alive for the duration
/// of the test — dropping it deletes the tempdir.
fn seeded_store() -> (TempDir, Utf8PathBuf) {
    let dir = TempDir::new().expect("tempdir");
    let root = utf8_path(&dir).join("papers");
    let store = FsStore::new(root.clone()).expect("FsStore::new");

    let (k1, m1) = fixture("alpha", "First Quantum Result", 2024, 2024);
    let (k2, m2) = fixture("beta", "Second Quantum Result", 2026, 2026);
    store.write(&k1, &m1, None).expect("seed entry 1");
    store.write(&k2, &m2, None).expect("seed entry 2");

    (dir, root)
}

/// Configure a `doiget` subprocess to use `root` as its store. Sets
/// `DOIGET_STORE_ROOT` (the primary resolution hook) and clears
/// `HOME` / `USERPROFILE` to belt-and-suspenders against any fallback
/// codepath leaking the developer's real home directory into the test.
fn doiget(root: &Utf8PathBuf) -> Command {
    let mut cmd = Command::cargo_bin("doiget").expect("locate doiget binary");
    cmd.env("DOIGET_STORE_ROOT", root.as_str())
        .env("HOME", root.as_str())
        .env("USERPROFILE", root.as_str())
        // #203: opt into human stdout — assert_cmd's captured stdout is
        // non-TTY, which defaults to Quiet after #203 honoring.
        .env("DOIGET_MODE", "human");
    cmd
}

#[test]
fn info_prints_metadata_for_stored_entry() {
    let (_dir_guard, root) = seeded_store();

    doiget(&root)
        .args(["info", "10.1234/alpha"])
        .assert()
        .success()
        .stdout(predicate::str::contains("First Quantum Result"));
}

#[test]
fn info_fails_for_missing_entry() {
    let (_dir_guard, root) = seeded_store();

    doiget(&root)
        .args(["info", "10.9999/missing"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no entry for"));
}

#[test]
fn list_recent_prints_seeded_entries_in_recency_order() {
    let (_dir_guard, root) = seeded_store();

    let assert = doiget(&root).args(["list-recent"]).assert().success();

    let stdout = String::from_utf8(assert.get_output().stdout.clone())
        .expect("doiget list-recent stdout was not UTF-8");

    // Header line.
    assert!(
        stdout.starts_with("safekey\tyear\ttitle\tfetched_at"),
        "expected header line, got:\n{stdout}"
    );
    // Both seeded titles appear.
    assert!(
        stdout.contains("First Quantum Result"),
        "missing seeded title 'First Quantum Result' in stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("Second Quantum Result"),
        "missing seeded title 'Second Quantum Result' in stdout:\n{stdout}"
    );

    // Recency order: 2026 entry must appear before 2024 entry.
    let pos_2026 = stdout
        .find("Second Quantum Result")
        .expect("2026 entry present");
    let pos_2024 = stdout
        .find("First Quantum Result")
        .expect("2024 entry present");
    assert!(
        pos_2026 < pos_2024,
        "expected 2026 entry before 2024 entry; stdout:\n{stdout}"
    );

    // Safekeys derived from `Ref::safekey()` for the seeded DOIs.
    assert!(
        stdout.contains("doi_10.1234_alpha"),
        "safekey 'doi_10.1234_alpha' missing from stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("doi_10.1234_beta"),
        "safekey 'doi_10.1234_beta' missing from stdout:\n{stdout}"
    );
}

#[test]
fn list_recent_with_explicit_limit_truncates() {
    let (_dir_guard, root) = seeded_store();

    let assert = doiget(&root).args(["list-recent", "1"]).assert().success();

    let stdout = String::from_utf8(assert.get_output().stdout.clone())
        .expect("doiget list-recent stdout was not UTF-8");

    // Header + exactly 1 data row → 2 newline-terminated lines total.
    let line_count = stdout.lines().count();
    assert_eq!(
        line_count, 2,
        "with --limit=1 expected header + 1 row, got {line_count} lines:\n{stdout}"
    );

    // The single row must be the most-recent entry (2026).
    assert!(
        stdout.contains("Second Quantum Result"),
        "expected most-recent (2026) entry in 1-row output:\n{stdout}"
    );
    assert!(
        !stdout.contains("First Quantum Result"),
        "did not expect older (2024) entry with --limit=1; stdout:\n{stdout}"
    );
}

#[test]
fn list_recent_on_empty_store_prints_only_header() {
    // Empty store: no .metadata files at all. We still expect a successful
    // exit and a header-only stdout, so callers can pipe `| tail -n +2`
    // without a special-case for emptiness.
    let dir = TempDir::new().expect("tempdir");
    let root = utf8_path(&dir).join("papers");
    // FsStore::new creates the dirs; no entries are seeded.
    FsStore::new(root.clone()).expect("FsStore::new");

    let assert = doiget(&root).args(["list-recent"]).assert().success();

    let stdout = String::from_utf8(assert.get_output().stdout.clone())
        .expect("doiget list-recent stdout was not UTF-8");
    assert_eq!(
        stdout, "safekey\tyear\ttitle\tfetched_at\tpdf\n",
        "empty store should produce header-only stdout, got:\n{stdout}"
    );
}

// ---- #481: the inventory must distinguish a stub from a paper ----------

/// Seed one entry with a stored PDF and one metadata-only entry
/// (`size_bytes = 0`), which is exactly what a blocked content leg leaves
/// behind.
fn store_with_one_stub() -> (TempDir, Utf8PathBuf) {
    let dir = TempDir::new().expect("tempdir");
    let root = utf8_path(&dir).join("papers");
    let store = FsStore::new(root.clone()).expect("FsStore::new");

    let (k1, m1) = fixture("gotpdf", "A Paper We Actually Have", 2024, 2024);
    store.write(&k1, &m1, None).expect("seed fetched entry");

    let (k2, mut m2) = fixture("nopdf", "A Paper We Only Know About", 2023, 2023);
    if let Some(d) = m2.doiget.as_mut() {
        // What `fetch` writes when the content leg was blocked: the record
        // is real, the bytes are not.
        d.size_bytes = 0;
    }
    store
        .write(&k2, &m2, None)
        .expect("seed metadata-only entry");

    (dir, root)
}

/// #481. Two entries, one with a PDF and one without, must not render
/// alike. Before the `pdf` column they did -- and `list-recent` is the only
/// command that answers "what do I have?" without being told the ref, so it
/// was the one place the distinction was unrecoverable.
#[test]
fn list_recent_distinguishes_a_metadata_only_entry_from_a_fetched_one() {
    let (_guard, root) = store_with_one_stub();
    let assert = doiget(&root).args(["list-recent"]).assert().success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf-8");

    let have = stdout
        .lines()
        .find(|l| l.contains("A Paper We Actually Have"))
        .unwrap_or_else(|| panic!("missing fetched row in:\n{stdout}"));
    let stub = stdout
        .lines()
        .find(|l| l.contains("A Paper We Only Know About"))
        .unwrap_or_else(|| panic!("missing metadata-only row in:\n{stdout}"));

    assert!(
        have.ends_with("1.2 kB"),
        "a stored PDF must show its size; got:\n{have}"
    );
    assert!(
        stub.ends_with('-'),
        "a metadata-only entry must be visibly different; got:\n{stub}"
    );
}

/// The column answers "which are stubs?" one row at a time. `--missing-pdf`
/// answers it for a fifty-ref batch, which is the case that produced the
/// report.
#[test]
fn list_recent_missing_pdf_lists_only_the_stubs() {
    let (_guard, root) = store_with_one_stub();
    let assert = doiget(&root)
        .args(["list-recent", "--missing-pdf"])
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf-8");

    assert!(
        stdout.contains("A Paper We Only Know About"),
        "the stub must be listed; got:\n{stdout}"
    );
    assert!(
        !stdout.contains("A Paper We Actually Have"),
        "a fetched paper is not missing its PDF; got:\n{stdout}"
    );
}

/// The JSON surface carries it too, and carries `has_pdf` beside
/// `size_bytes` so a consumer does not have to know that `0` and `null`
/// both mean "no PDF" while meaning different things about the entry.
#[test]
fn list_recent_json_carries_size_bytes_and_has_pdf() {
    let (_guard, root) = store_with_one_stub();
    let assert = doiget(&root)
        .args(["--mode", "json", "list-recent"])
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf-8");
    let v: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let entries = v["entries"].as_array().expect("entries array");

    let stub = entries
        .iter()
        .find(|e| e["title"].as_str() == Some("A Paper We Only Know About"))
        .unwrap_or_else(|| panic!("stub missing from {stdout}"));
    assert_eq!(stub["size_bytes"], serde_json::json!(0));
    assert_eq!(stub["has_pdf"], serde_json::json!(false));

    let have = entries
        .iter()
        .find(|e| e["title"].as_str() == Some("A Paper We Actually Have"))
        .unwrap_or_else(|| panic!("fetched entry missing from {stdout}"));
    assert_eq!(have["has_pdf"], serde_json::json!(true));
}

// ---- #204 JSON-mode coverage --------------------------------------------

#[test]
fn info_json_emits_metadata_object() {
    let (_dir_guard, root) = seeded_store();

    let out = doiget(&root)
        // The #203 helper sets DOIGET_MODE=human; override per-test for
        // the JSON case (env_clear is too invasive — we still need
        // DOIGET_STORE_ROOT / HOME for the resolver).
        .env("DOIGET_MODE", "json")
        .args(["info", "10.1234/alpha"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8(out).expect("info JSON stdout utf-8");
    let v: serde_json::Value = serde_json::from_str(&s).expect("info JSON parses");
    // #212: info --mode json emits {ok, ref, safekey, metadata} envelope.
    assert_eq!(v["ok"], true, "envelope ok");
    assert!(v["safekey"].is_string(), "safekey present");
    assert_eq!(v["metadata"]["title"], "First Quantum Result");
}

#[test]
fn list_recent_json_emits_array_of_entries() {
    let (_dir_guard, root) = seeded_store();

    let out = doiget(&root)
        .env("DOIGET_MODE", "json")
        .args(["list-recent"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8(out).expect("list-recent JSON stdout utf-8");
    let v: serde_json::Value = serde_json::from_str(&s).expect("list-recent JSON parses");
    // #212: list-recent --mode json emits {ok, count, entries} envelope.
    assert_eq!(v["ok"], true, "envelope ok");
    let arr = v["entries"].as_array().expect("entries is an array");
    assert_eq!(arr.len(), 2, "seeded store has 2 entries");
    assert_eq!(v["count"], 2, "count matches entries length");
    // EntryInfo schema (#204): {safekey, title, year, fetched_at}.
    for entry in arr {
        assert!(entry["safekey"].is_string(), "safekey is a string");
        assert!(entry["title"].is_string(), "title is a string");
    }
}

// ---- #301 / ADR-0017 Amendment 2: artifact-class honors only EXPLICIT Quiet

/// `doiget` rooted at `root` WITHOUT forcing `DOIGET_MODE`, so the
/// resolver sees a non-TTY captured stdout (assert_cmd pipes it) and
/// falls through to the *implicit* Quiet branch. Pre-#301 this silenced
/// `info` / `list-recent`; post-#301 they are artifact-class and emit.
/// `DOIGET_MODE` is explicitly removed in case the parent environment
/// has it set.
fn doiget_implicit(root: &Utf8PathBuf) -> Command {
    let mut cmd = Command::cargo_bin("doiget").expect("locate doiget binary");
    cmd.env("DOIGET_STORE_ROOT", root.as_str())
        .env("HOME", root.as_str())
        .env("USERPROFILE", root.as_str())
        .env_remove("DOIGET_MODE");
    cmd
}

#[test]
fn info_emits_under_implicit_non_tty_quiet() {
    // The #301 repro: agent / pipe / ssh caller (non-TTY, no flag, no
    // DOIGET_MODE). `info` MUST still print its metadata.
    let (_dir_guard, root) = seeded_store();
    doiget_implicit(&root)
        .args(["info", "10.1234/alpha"])
        .assert()
        .success()
        .stdout(predicate::str::contains("First Quantum Result"));
}

#[test]
fn list_recent_emits_under_implicit_non_tty_quiet() {
    let (_dir_guard, root) = seeded_store();
    doiget_implicit(&root)
        .args(["list-recent"])
        .assert()
        .success()
        .stdout(predicate::str::contains("First Quantum Result"));
}

#[test]
fn info_explicit_quiet_flag_suppresses_stdout() {
    // Explicit `--quiet` still silences (the entry exists → exit 0); the
    // not-found contract is unaffected.
    let (_dir_guard, root) = seeded_store();
    doiget_implicit(&root)
        .args(["--quiet", "info", "10.1234/alpha"])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());
}

#[test]
fn list_recent_explicit_quiet_flag_suppresses_stdout() {
    let (_dir_guard, root) = seeded_store();
    doiget_implicit(&root)
        .args(["-q", "list-recent"])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());
}

#[test]
fn info_explicit_quiet_env_suppresses_stdout() {
    // `DOIGET_MODE=quiet` is an explicit Quiet signal → suppress.
    let (_dir_guard, root) = seeded_store();
    doiget_implicit(&root)
        .env("DOIGET_MODE", "quiet")
        .args(["info", "10.1234/alpha"])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());
}