tarzan 0.2.1

Random-access, seekable .tar.zst archives with an embedded table-of-contents index
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use tempfile::tempdir;

fn fixture_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("testdata/fixtures/tiny-tree")
        .canonicalize()
        .expect("fixture path should exist")
}

fn create_tar_from_fixture(output_tar: &Path) {
    let fixture = fixture_root();
    let mut cmd = Command::new("tar");
    #[cfg(target_os = "macos")]
    cmd.env("COPYFILE_DISABLE", "1");
    let status = cmd
        .arg("-cf")
        .arg(output_tar)
        .arg("-C")
        .arg(&fixture)
        .arg(".")
        .status()
        .expect("failed to run tar command");
    assert!(status.success(), "tar command failed");
}

fn tarzan_bin() -> PathBuf {
    PathBuf::from(std::env::var("CARGO_BIN_EXE_tarzan").expect("missing tarzan test binary"))
}

fn wrap_fixture(temp: &tempfile::TempDir) -> PathBuf {
    let tar_path = temp.path().join("input.tar");
    let archive_path = temp.path().join("archive.tar.zst");
    create_tar_from_fixture(&tar_path);
    let status = Command::new(tarzan_bin())
        .arg("wrap")
        .arg(&tar_path)
        .arg("-f")
        .arg(&archive_path)
        .status()
        .expect("failed to run tarzan wrap");
    assert!(status.success(), "tarzan wrap failed");
    archive_path
}

#[test]
fn list_exits_zero_and_prints_paths() {
    let temp = tempdir().expect("failed to create tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(&archive)
        .output()
        .expect("failed to run tarzan list");

    assert!(
        output.status.success(),
        "tarzan list exited with status {}; stderr: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8(output.stdout).expect("stdout should be UTF-8");
    assert!(!stdout.is_empty(), "list output should not be empty");
    assert!(
        stdout.lines().any(|l| l.contains("README.txt")),
        "expected README.txt in list output; got:\n{stdout}"
    );
}

#[test]
fn list_long_format_shows_extra_columns() {
    let temp = tempdir().expect("failed to create tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-v", "-f"])
        .arg(&archive)
        .output()
        .expect("failed to run tarzan list -v");

    assert!(output.status.success(), "tarzan list -v failed");

    let stdout = String::from_utf8(output.stdout).expect("stdout should be UTF-8");
    // Long format lines contain a year (mtime) and a size field.
    let readme_line = stdout
        .lines()
        .find(|l| l.contains("README.txt"))
        .expect("expected README.txt in list -l output");
    assert!(
        readme_line.contains("19") || readme_line.contains("20"),
        "expected a year in long-format line: {readme_line}"
    );
}

#[test]
fn list_paths_match_tar_tf() {
    let temp = tempdir().expect("failed to create tempdir");
    let archive = wrap_fixture(&temp);
    let tar_path = temp.path().join("input.tar");
    create_tar_from_fixture(&tar_path);

    let tar_output = Command::new("tar")
        .arg("-tf")
        .arg(&tar_path)
        .output()
        .expect("failed to run tar -tf");
    assert!(tar_output.status.success(), "tar -tf failed");
    let tar_paths: std::collections::BTreeSet<String> = String::from_utf8(tar_output.stdout)
        .unwrap()
        .lines()
        .map(str::to_owned)
        .collect();

    let list_output = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(&archive)
        .output()
        .expect("failed to run tarzan list");
    assert!(list_output.status.success(), "tarzan list failed");
    let list_paths: std::collections::BTreeSet<String> = String::from_utf8(list_output.stdout)
        .unwrap()
        .lines()
        .map(str::to_owned)
        .collect();

    assert_eq!(
        list_paths, tar_paths,
        "tarzan list paths should match tar -tf paths"
    );
}

#[test]
fn list_nonexistent_archive_exits_nonzero() {
    let temp = tempdir().expect("failed to create tempdir");
    let status = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(temp.path().join("does_not_exist.tar.zst"))
        .status()
        .expect("failed to run tarzan list");
    assert!(!status.success(), "tarzan list on missing file should fail");
}

#[test]
fn list_verbose_shows_owner_group_column() {
    let temp = tempdir().expect("failed to create tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-v", "-f"])
        .arg(&archive)
        .output()
        .expect("failed to run tarzan list -v");
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    let readme_line = stdout
        .lines()
        .find(|l| l.contains("README.txt"))
        .expect("README.txt line present");
    // Owner column is `uid/gid` (numeric). Any line should match the
    // pattern `digits/digits` between the mode and size columns.
    assert!(
        readme_line.split_whitespace().any(|f| {
            f.split_once('/')
                .is_some_and(|(a, b)| a.parse::<u64>().is_ok() && b.parse::<u64>().is_ok())
        }),
        "expected uid/gid column in: {readme_line}"
    );
}

#[cfg(unix)]
#[test]
fn list_verbose_shows_symlink_target() {
    use std::os::unix::fs::symlink;

    let temp = tempdir().expect("tempdir");
    let src = temp.path().join("src");
    fs::create_dir(&src).unwrap();
    fs::write(src.join("target.txt"), b"hi").unwrap();
    symlink("target.txt", src.join("link.txt")).unwrap();

    let tar_path = temp.path().join("input.tar");
    let mut cmd = Command::new("tar");
    #[cfg(target_os = "macos")]
    cmd.env("COPYFILE_DISABLE", "1");
    let status = cmd
        .arg("-cf")
        .arg(&tar_path)
        .arg("-C")
        .arg(&src)
        .arg(".")
        .status()
        .expect("tar");
    assert!(status.success());

    let archive_path = temp.path().join("a.tar.zst");
    let status = Command::new(tarzan_bin())
        .arg("wrap")
        .arg(&tar_path)
        .arg("-f")
        .arg(&archive_path)
        .status()
        .expect("wrap");
    assert!(status.success());

    let out = Command::new(tarzan_bin())
        .args(["list", "-v", "-f"])
        .arg(&archive_path)
        .output()
        .expect("list -v");
    assert!(out.status.success());
    let stdout = String::from_utf8(out.stdout).unwrap();
    let link_line = stdout
        .lines()
        .find(|l| l.contains("link.txt"))
        .expect("link.txt should be listed");
    assert!(
        link_line.contains("-> target.txt"),
        "expected ` -> target.txt` in: {link_line}"
    );
    // Type char should be `l` for the symlink line.
    assert!(
        link_line.trim_start().starts_with('l'),
        "expected symlink line to start with `l`: {link_line}"
    );
}

#[test]
fn list_json_emits_parseable_array() {
    let temp = tempdir().expect("tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "--json", "-f"])
        .arg(&archive)
        .output()
        .expect("list --json");
    assert!(output.status.success(), "list --json failed");

    let stdout = String::from_utf8(output.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("top-level array");
    assert!(!arr.is_empty(), "expected non-empty member array");

    let has_readme = arr.iter().any(|m| {
        m.get("path")
            .and_then(|p| p.as_str())
            .is_some_and(|s| s.ends_with("README.txt"))
    });
    assert!(has_readme, "expected a README.txt entry in JSON output");

    let first = &arr[0];
    for key in ["path", "type", "size", "mode", "uid", "gid", "mtime"] {
        assert!(
            first.get(key).is_some(),
            "JSON entry missing key `{key}`: {first}"
        );
    }
}

#[test]
fn list_filter_by_directory_prefix() {
    let temp = tempdir().expect("tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(&archive)
        .arg("src/")
        .output()
        .expect("list with filter");
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.lines().all(|l| l.is_empty() || l.contains("src")),
        "every line should match src/ prefix:\n{stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("main.rs")),
        "expected src/main.rs in filtered listing"
    );
    assert!(
        !stdout.lines().any(|l| l.ends_with("README.txt")),
        "README.txt should be filtered out"
    );
}

#[test]
fn list_filter_by_glob_pattern() {
    let temp = tempdir().expect("tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(&archive)
        .arg("*.txt")
        .output()
        .expect("list with glob");
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        stdout.lines().any(|l| l.ends_with("README.txt")),
        "README.txt should match *.txt"
    );
    assert!(
        !stdout.lines().any(|l| l.ends_with("main.rs")),
        "main.rs should NOT match *.txt"
    );
}

#[test]
fn list_json_respects_filter() {
    let temp = tempdir().expect("tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "--json", "-f"])
        .arg(&archive)
        .arg("src/")
        .output()
        .expect("list --json src/");
    assert!(output.status.success());

    let stdout = String::from_utf8(output.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let arr = parsed.as_array().expect("top-level array");
    for entry in arr {
        let path = entry.get("path").unwrap().as_str().unwrap();
        assert!(
            path.contains("src"),
            "JSON entry leaked through filter: {path}"
        );
    }
}

#[test]
fn list_verbose_and_json_are_mutually_exclusive() {
    let temp = tempdir().expect("tempdir");
    let archive = wrap_fixture(&temp);

    let output = Command::new(tarzan_bin())
        .args(["list", "-v", "--json", "-f"])
        .arg(&archive)
        .output()
        .expect("list -v --json");
    assert!(
        !output.status.success(),
        "list -v --json should fail with a conflict error"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("--verbose") && stderr.contains("--json"),
        "expected clap conflict message, got: {stderr}"
    );
}

/// Builds an archive whose plain listing exceeds the OS pipe buffer (~64 KiB).
/// 5 000 entries × ~15 bytes each = ~75 KiB, which guarantees a write block
/// before a `head -1` reader drains the pipe. Only the Unix broken-pipe test
/// uses this; gated to match.
#[cfg(unix)]
fn big_archive(temp: &tempfile::TempDir) -> PathBuf {
    use std::io::Cursor;

    let archive = temp.path().join("big.tar.zst");
    let out = fs::File::create(&archive).expect("create big archive");

    let mut tar_data = Vec::new();
    {
        let mut builder = tar::Builder::new(&mut tar_data);
        for i in 0..5000usize {
            let name = format!("file_{i:04}.txt");
            let content = b"x";
            let mut header = tar::Header::new_gnu();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_uid(0);
            header.set_gid(0);
            header.set_mtime(0);
            header.set_entry_type(tar::EntryType::Regular);
            builder
                .append_data(&mut header, &name, &content[..])
                .expect("append entry");
        }
        builder.into_inner().expect("finish tar");
    }

    tarzan::wrap(Cursor::new(tar_data), out, tarzan::WrapOptions::default())
        .expect("wrap big archive");

    archive
}

/// Closing a pipe after reading one line must not cause a panic.
/// Before the fix this test fails: `tarzan list` panics with "failed printing
/// to stdout: Broken pipe" and exits 101.
#[cfg(unix)]
#[test]
fn list_exits_cleanly_on_broken_pipe() {
    use std::io::{BufRead, BufReader};
    use std::process::Stdio;

    let temp = tempdir().expect("tempdir");
    let archive = big_archive(&temp);

    let mut child = Command::new(tarzan_bin())
        .args(["list", "-f"])
        .arg(&archive)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn tarzan list");

    // Simulate `| head -1`: read one line then close the read end of the pipe.
    {
        let stdout = child.stdout.take().expect("stdout pipe");
        let mut reader = BufReader::new(stdout);
        let mut line = String::new();
        reader.read_line(&mut line).expect("read one line");
    } // read end of pipe dropped here

    // wait_with_output still collects stderr (stdout is already None).
    let output = child.wait_with_output().expect("wait for child");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("panicked"),
        "tarzan list panicked on broken pipe:\n{stderr}"
    );
}

// Ensure wrapping still roundtrips correctly after adding TOC.
#[test]
fn wrap_still_roundtrips_after_toc_added() {
    let temp = tempdir().expect("failed to create tempdir");
    let tar_path = temp.path().join("input.tar");
    create_tar_from_fixture(&tar_path);
    let source_tar = fs::read(&tar_path).expect("failed to read tar");
    let archive = wrap_fixture(&temp);
    let compressed = fs::read(&archive).expect("failed to read archive");
    let roundtrip = zstd::stream::decode_all(std::io::Cursor::new(compressed))
        .expect("zstd should decode archive");
    assert_eq!(roundtrip, source_tar);
}