hatchzip 0.1.11

Extract huge archives in place: the archive shrinks as your files hatch, so you only need room for the output.
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
//! Folder entries keep their permissions and modified times, set once
//! everything inside them is made.

mod common;

use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use common::*;
use hatchzip_core::session;
use tempfile::TempDir;

fn when() -> SystemTime {
    UNIX_EPOCH + Duration::from_secs(1_000_000_000)
}

fn modified(p: &Path) -> SystemTime {
    fs::metadata(p).unwrap().modified().unwrap()
}

#[cfg(unix)]
fn assert_mode(p: &Path, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    let got = fs::metadata(p).unwrap().permissions().mode() & 0o7777;
    assert_eq!(got, mode, "{}", p.display());
}

#[cfg(not(unix))]
fn assert_mode(_: &Path, _: u32) {}

/// `docs` (0o750) holding `docs/old` (0o700), each with a file inside, all
/// dated `when()`. `extra` is added as a folder entry at the end.
fn tar_with_folders(dir: &Path, extra: Option<(&str, u32)>) -> PathBuf {
    let mut b = tar::Builder::new(Vec::new());
    let folder = |b: &mut tar::Builder<Vec<u8>>, path: &str, mode: u32| {
        let mut h = tar::Header::new_gnu();
        h.set_entry_type(tar::EntryType::Directory);
        h.set_mode(mode);
        h.set_mtime(1_000_000_000);
        h.set_size(0);
        b.append_data(&mut h, path, std::io::empty()).unwrap();
    };
    folder(&mut b, "docs", 0o750);
    folder(&mut b, "docs/old", 0o700);
    for (i, path) in ["docs/a.txt", "docs/old/b.txt"].iter().enumerate() {
        let data = noise(20_000, i as u64);
        let mut h = tar::Header::new_gnu();
        h.set_size(data.len() as u64);
        h.set_mode(0o644);
        h.set_mtime(1_000_000_000);
        b.append_data(&mut h, path, data.as_slice()).unwrap();
    }
    if let Some((path, mode)) = extra {
        folder(&mut b, path, mode);
        let mut h = tar::Header::new_gnu();
        h.set_size(4);
        h.set_mode(0o644);
        b.append_data(&mut h, format!("{path}/c.txt"), &b"data"[..])
            .unwrap();
    }
    let path = dir.join("docs.tar");
    fs::write(&path, b.into_inner().unwrap()).unwrap();
    path
}

fn assert_folders(out: &Path) {
    for (path, mode) in [("docs", 0o750), ("docs/old", 0o700)] {
        assert_eq!(modified(&out.join(path)), when(), "{path}");
        assert_mode(&out.join(path), mode);
    }
}

#[test]
fn tar_folders_keep_their_permissions_and_times() {
    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), None);
    let out = tmp.path().join("out");
    assert_ok(&extract(&archive, &out, &[("HATCHZIP_BATCH_ENTRIES", "1")]));
    assert_folders(&out);
    assert_consumed(&archive);
}

#[test]
fn a_kept_archive_sets_folders_too() {
    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), None);
    let out = tmp.path().join("out");
    let (a, o) = (archive.to_str().unwrap(), out.to_str().unwrap());
    assert_ok(&hatchzip(
        &[
            "extract",
            a,
            "-o",
            o,
            "--keep-archive",
            "--keep-free",
            "0",
            "--yes",
        ],
        &[],
    ));
    assert_folders(&out);
    assert!(archive.exists());
    assert_no_side_files(&archive);
}

/// A folder listed twice takes the mode and time of its last entry.
#[test]
fn a_folder_listed_twice_takes_its_last_entry() {
    let tmp = TempDir::new().unwrap();
    let mut b = tar::Builder::new(Vec::new());
    for (mode, mtime) in [(0o755, 946_684_800), (0o750, 1_000_000_000)] {
        let mut h = tar::Header::new_gnu();
        h.set_entry_type(tar::EntryType::Directory);
        h.set_mode(mode);
        h.set_mtime(mtime);
        h.set_size(0);
        b.append_data(&mut h, "docs", std::io::empty()).unwrap();
        let mut h = tar::Header::new_gnu();
        h.set_size(4);
        h.set_mode(0o644);
        b.append_data(&mut h, format!("docs/{mtime}.txt"), &b"data"[..])
            .unwrap();
    }
    let archive = tmp.path().join("docs.tar");
    fs::write(&archive, b.into_inner().unwrap()).unwrap();
    let out = tmp.path().join("out");

    assert_ok(&extract(&archive, &out, &[]));
    assert_eq!(modified(&out.join("docs")), when());
    assert_mode(&out.join("docs"), 0o750);
}

/// A crash after the last link and before the folders are set leaves the
/// journal, and the resume sets them.
#[test]
fn a_crash_before_the_folders_are_set_resumes() {
    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), None);
    let out = tmp.path().join("out");
    let crashed = extract(&archive, &out, &[("HATCHZIP_CRASH_AT", "before-folders")]);
    assert!(!crashed.status.success(), "should have crashed");
    assert!(side_files(&archive)[0].exists());
    assert!(folders_file(&archive).exists());

    assert_ok(&extract(&archive, &out, &[]));
    assert_folders(&out);
    assert_consumed(&archive);
}

/// A folder that takes no new files is only made read-only once everything
/// inside it is extracted.
#[cfg(unix)]
#[test]
fn a_read_only_folder_still_gets_its_files() {
    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), Some(("locked", 0o500)));
    let out = tmp.path().join("out");
    assert_ok(&extract(&archive, &out, &[]));
    assert_eq!(fs::read(out.join("locked/c.txt")).unwrap(), b"data");
    assert_mode(&out.join("locked"), 0o500);
    assert_folders(&out);

    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(out.join("locked"), fs::Permissions::from_mode(0o700)).unwrap();
}

/// A crash once the folders are set leaves only them to do. The resume makes
/// no link again inside a folder that no longer takes new entries, and opens
/// folders it already set that it can't read or look into.
#[cfg(unix)]
#[test]
fn a_crash_after_the_folders_are_set_resumes() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let mut b = tar::Builder::new(Vec::new());
    let folder = |b: &mut tar::Builder<Vec<u8>>, path: &str, mode: u32| {
        let mut h = tar::Header::new_gnu();
        h.set_entry_type(tar::EntryType::Directory);
        h.set_mode(mode);
        h.set_mtime(1_000_000_000);
        h.set_size(0);
        b.append_data(&mut h, path, std::io::empty()).unwrap();
    };
    let file = |b: &mut tar::Builder<Vec<u8>>, path: &str| {
        let mut h = tar::Header::new_gnu();
        h.set_size(4);
        h.set_mode(0o644);
        b.append_data(&mut h, path, &b"data"[..]).unwrap();
    };
    folder(&mut b, "ro", 0o555);
    file(&mut b, "ro/a.txt");
    let mut h = tar::Header::new_gnu();
    h.set_entry_type(tar::EntryType::Symlink);
    h.set_size(0);
    b.append_link(&mut h, "ro/l", "a.txt").unwrap();
    folder(&mut b, "noread", 0o311);
    file(&mut b, "noread/b.txt");
    folder(&mut b, "nosearch", 0o600);
    folder(&mut b, "nosearch/inner", 0o700);
    file(&mut b, "nosearch/inner/c.txt");
    let archive = tmp.path().join("modes.tar");
    fs::write(&archive, b.into_inner().unwrap()).unwrap();
    let out = tmp.path().join("out");

    let crashed = extract(&archive, &out, &[("HATCHZIP_CRASH_AT", "after-folders")]);
    assert!(!crashed.status.success(), "should have crashed");
    assert!(folders_file(&archive).exists());

    assert_ok(&extract(&archive, &out, &[]));
    for (path, mode) in [("ro", 0o555), ("noread", 0o311), ("nosearch", 0o600)] {
        assert_mode(&out.join(path), mode);
        assert_eq!(modified(&out.join(path)), when(), "{path}");
        fs::set_permissions(out.join(path), fs::Permissions::from_mode(0o700)).unwrap();
    }
    assert_mode(&out.join("nosearch/inner"), 0o700);
    assert_eq!(fs::read_link(out.join("ro/l")).unwrap(), Path::new("a.txt"));
    assert_eq!(fs::read(out.join("nosearch/inner/c.txt")).unwrap(), b"data");
    assert_no_side_files(&archive);
}

/// A folder that was in the output before the extraction may belong to
/// someone else, and is left as it was, like an existing file.
#[cfg(unix)]
#[test]
fn a_folder_already_in_the_output_is_left_as_it_is() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), None);
    let out = tmp.path().join("out");
    fs::create_dir_all(out.join("docs")).unwrap();
    fs::set_permissions(out.join("docs"), fs::Permissions::from_mode(0o775)).unwrap();

    assert_ok(&extract(&archive, &out, &[]));
    assert_mode(&out.join("docs"), 0o775);
    assert_mode(&out.join("docs/old"), 0o700);
    assert_eq!(modified(&out.join("docs/old")), when());
    assert_consumed(&archive);
}

/// The saved folders are checked with the rest of the journal, so a resume
/// with the file gone stops before it frees any more of the archive.
#[test]
fn a_missing_folders_file_stops_the_resume_before_anything_is_freed() {
    let tmp = TempDir::new().unwrap();
    let archive = tar_with_folders(tmp.path(), None);
    let out = tmp.path().join("out");
    let crashed = extract(
        &archive,
        &out,
        &[
            ("HATCHZIP_BATCH_ENTRIES", "1"),
            ("HATCHZIP_CRASH_AT", "after-journal"),
        ],
    );
    assert!(!crashed.status.success(), "should have crashed");
    fs::remove_file(folders_file(&archive)).unwrap();
    let before = snapshot(&archive);

    let resumed = extract(&archive, &out, &[]);
    assert!(!resumed.status.success(), "should have refused");
    let err = String::from_utf8_lossy(&resumed.stderr);
    assert!(err.contains("hatchzip-folders"), "{err}");
    assert!(
        err.contains("Put it back, or run `hatchzip restore` to give the archive back."),
        "{err}"
    );
    assert_unchanged(&before);
}

/// Looking never reads the saved folders, so the app still opens a run with
/// the file gone or damaged, and reaches its restore button.
#[test]
fn a_lost_folders_file_does_not_stop_a_look() {
    for damaged in [false, true] {
        let tmp = TempDir::new().unwrap();
        let archive = tar_with_folders(tmp.path(), None);
        let out = tmp.path().join("out");
        let crashed = extract(
            &archive,
            &out,
            &[
                ("HATCHZIP_BATCH_ENTRIES", "1"),
                ("HATCHZIP_CRASH_AT", "after-journal"),
            ],
        );
        assert!(!crashed.status.success(), "should have crashed");
        if damaged {
            fs::write(folders_file(&archive), b"[]").unwrap();
        } else {
            fs::remove_file(folders_file(&archive)).unwrap();
        }

        let (primary, paths) = session::locate(&archive).unwrap();
        let reads = Default::default();
        let state = session::open(
            &primary,
            &paths,
            session::Output::Default,
            None,
            false,
            None,
            &reads,
        )
        .unwrap();
        assert!(matches!(state, session::State::Resume(..)));
    }
}

/// With every entry out the files are safe, so a lost list only costs the
/// folders' permissions and times: the run finishes and says so.
#[test]
fn a_lost_folders_file_does_not_stop_the_finish() {
    for keep in [false, true] {
        for damaged in [false, true] {
            let tmp = TempDir::new().unwrap();
            let archive = tar_with_folders(tmp.path(), None);
            let out = tmp.path().join("out");
            let (a, o) = (archive.to_str().unwrap(), out.to_str().unwrap());
            let mut args = vec!["extract", a, "-o", o, "--keep-free", "0", "--yes"];
            if keep {
                args.push("--keep-archive");
            }
            let crashed = hatchzip(&args, &[("HATCHZIP_CRASH_AT", "before-folders")]);
            assert!(!crashed.status.success(), "should have crashed");
            if damaged {
                fs::write(folders_file(&archive), b"[]").unwrap();
            } else {
                fs::remove_file(folders_file(&archive)).unwrap();
            }

            let finished = hatchzip(&args, &[]);
            assert_ok(&finished);
            let err = String::from_utf8_lossy(&finished.stderr);
            assert!(err.contains("hatchzip-folders"), "{err}");
            assert!(err.contains("default permissions"), "{err}");
            assert!(out.join("docs/old").is_dir());
            assert_no_side_files(&archive);
            assert_eq!(archive.exists(), keep);
        }
    }
}

/// A run can have both saved folders and names that differ only in case, and
/// its journal, at version 8, still resumes.
#[test]
fn a_run_with_folders_and_names_differing_only_in_case_resumes() {
    let tmp = TempDir::new().unwrap();
    if !session::case_sensitive(tmp.path()) {
        return;
    }
    let archive = tar_with_folders(tmp.path(), Some(("docs/A.TXT", 0o755)));
    let out = tmp.path().join("out");
    let crashed = extract(
        &archive,
        &out,
        &[
            ("HATCHZIP_BATCH_ENTRIES", "1"),
            ("HATCHZIP_CRASH_AT", "after-journal"),
        ],
    );
    assert!(!crashed.status.success(), "should have crashed");
    let journal: serde_json::Value =
        serde_json::from_slice(&fs::read(&side_files(&archive)[0]).unwrap()).unwrap();
    assert_eq!(journal["version"], 8);
    assert_eq!(journal["case_folders"], serde_json::json!(["docs"]));
    assert!(!journal["folders"].is_null());

    assert_ok(&extract(&archive, &out, &[]));
    assert_folders(&out);
    assert_mode(&out.join("docs/A.TXT"), 0o755);
    assert_consumed(&archive);
}

/// A restore never reads the saved folders, so it still gives the archive
/// back, or discards a kept run's progress, with the file gone or damaged.
#[test]
fn a_lost_folders_file_does_not_stop_a_restore() {
    for keep in [false, true] {
        for damaged in [false, true] {
            let tmp = TempDir::new().unwrap();
            let archive = tar_with_folders(tmp.path(), None);
            let out = tmp.path().join("out");
            let (a, o) = (archive.to_str().unwrap(), out.to_str().unwrap());
            let mut args = vec!["extract", a, "-o", o, "--keep-free", "0", "--yes"];
            if keep {
                args.push("--keep-archive");
            }
            let crashed = hatchzip(
                &args,
                &[
                    ("HATCHZIP_BATCH_ENTRIES", "1"),
                    ("HATCHZIP_CRASH_AT", "after-journal"),
                ],
            );
            assert!(!crashed.status.success(), "should have crashed");
            if damaged {
                fs::write(folders_file(&archive), b"[]").unwrap();
            } else {
                fs::remove_file(folders_file(&archive)).unwrap();
            }

            assert_ok(&hatchzip(&["restore", a, "-o", o], &[]));
            assert_no_side_files(&archive);

            let again = tmp.path().join("again");
            assert_ok(&extract(&archive, &again, &[]));
            assert!(again.join("docs/old").is_dir());
        }
    }
}

/// The DOS time of a ZIP folder entry is read the way a file's is, so both
/// end up the same.
#[test]
fn zip_folders_keep_their_permissions_and_times() {
    use std::io::Write;
    use zip::DateTime;
    use zip::write::{SimpleFileOptions, ZipWriter};

    let tmp = TempDir::new().unwrap();
    let time = DateTime::from_date_and_time(2001, 9, 9, 1, 46, 40).unwrap();
    let opts = SimpleFileOptions::default().last_modified_time(time);
    let mut w = ZipWriter::new(std::io::Cursor::new(Vec::new()));
    w.add_directory("docs/", opts.unix_permissions(0o750))
        .unwrap();
    w.start_file("docs/a.txt", opts).unwrap();
    w.write_all(&noise(20_000, 1)).unwrap();
    let archive = tmp.path().join("docs.zip");
    fs::write(&archive, w.finish().unwrap().into_inner()).unwrap();
    let out = tmp.path().join("out");

    assert_ok(&extract(&archive, &out, &[]));
    assert_eq!(
        modified(&out.join("docs")),
        modified(&out.join("docs/a.txt"))
    );
    assert_mode(&out.join("docs"), 0o750);
}

#[test]
fn sevenz_folders_keep_their_permissions_and_times() {
    use sevenz_rust2::{ArchiveEntry, ArchiveWriter, NtTime};

    let tmp = TempDir::new().unwrap();
    let archive = tmp.path().join("docs.7z");
    let mut w = ArchiveWriter::create(&archive).unwrap();
    let mut docs = ArchiveEntry::new_directory("docs");
    docs.has_last_modified_date = true;
    docs.last_modified_date = NtTime::try_from(when()).unwrap();
    // FILE_ATTRIBUTE_DIRECTORY, with the Unix mode in the high bits.
    docs.has_windows_attributes = true;
    docs.windows_attributes = 0x10 | 0x8000 | ((0o040750) << 16);
    w.push_archive_entry::<&[u8]>(docs, None).unwrap();
    let data = noise(20_000, 1);
    w.push_archive_entry(ArchiveEntry::new_file("docs/a.txt"), Some(data.as_slice()))
        .unwrap();
    w.finish().unwrap();
    let out = tmp.path().join("out");

    assert_ok(&extract(&archive, &out, &[]));
    assert_eq!(modified(&out.join("docs")), when());
    assert_mode(&out.join("docs"), 0o750);
}