summaryrefslogtreecommitdiffstats
path: root/src/util/tar.rs
blob: 5e64bb252e8737307b428891c6a551470d05c569 (plain)
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
use std::{
	ffi::CString,
	fs::DirBuilder,
	io::{self, Read, Result, Write},
	os::unix::ffi::OsStrExt,
	path::Path,
};
use walkdir::WalkDir;

pub fn pack<W: Write, P: AsRef<Path>, E: AsRef<Path>, I: Iterator<Item = E>>(
	archive: W,
	source: P,
	entries: I,
) -> Result<W> {
	let mut ar = tar::Builder::new(archive);
	ar.mode(tar::HeaderMode::Deterministic);
	ar.follow_symlinks(false);

	for entry in entries {
		let entry_path = source.as_ref().join(entry);
		if !entry_path.exists() {
			continue;
		}
		for dir_entry_result in WalkDir::new(entry_path).sort_by_file_name() {
			let dir_entry = dir_entry_result?;
			let path = dir_entry.path();
			let name = path
				.strip_prefix(&source)
				.expect("tar: failed to strip path prefix");
			ar.append_path_with_name(path, name)?;
		}
	}

	ar.into_inner()
}

pub fn unpack_filter<R: Read, P: AsRef<Path>, F>(archive: R, dest: P, filter: F) -> Result<()>
where
	for<'a> F: Fn(&tar::Entry<'a, R>) -> bool,
{
	let dest_path = dest.as_ref();

	DirBuilder::new().recursive(true).create(dest_path)?;

	let mut ar = tar::Archive::new(archive);
	ar.set_preserve_permissions(true);
	ar.set_preserve_mtime(true);
	ar.set_unpack_xattrs(true);

	for entry_r in ar.entries()? {
		let mut entry = entry_r?;
		if !filter(&entry) {
			continue;
		}
		if entry.unpack_in(dest_path)? {
			let header = entry.header();
			let uid = header.uid()? as libc::uid_t;
			let gid = header.gid()? as libc::gid_t;

			let path = CString::new(dest_path.join(entry.path()?).as_os_str().as_bytes())
				.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
			if unsafe { libc::lchown(path.as_ptr(), uid, gid) } < 0 {
				return Err(io::Error::last_os_error());
			}
		}
	}

	Ok(())
}

pub fn unpack<R: Read, P: AsRef<Path>>(archive: R, dest: P) -> Result<()> {
	unpack_filter(archive, dest, |_| true)
}