zip_extensions/utilities/
file_utils.rs1use std::fs::File;
2use std::io;
3use std::io::{Error, ErrorKind, Write};
4use std::path::{Component, PathBuf};
5
6pub fn file_write_all_bytes(path: PathBuf, bytes: &[u8], overwrite: bool) -> io::Result<usize> {
8 if path.exists() && !overwrite {
9 return Err(Error::new(
10 ErrorKind::AlreadyExists,
11 "The specified file already exists.",
12 ));
13 }
14 let mut file = File::create(path)?;
15 file.set_len(0)?;
16 file.write(bytes)
17}
18
19pub(crate) fn make_relative_path(root: &PathBuf, current: &PathBuf) -> PathBuf {
21 let mut result = PathBuf::new();
22 let root_components = root.components().collect::<Vec<Component>>();
23 let current_components = current.components().collect::<Vec<_>>();
24 for i in 0..current_components.len() {
25 let current_path_component: Component = current_components[i];
26 if i < root_components.len() {
27 let other: Component = root_components[i];
28 if other != current_path_component {
29 break;
30 }
31 } else {
32 result.push(current_path_component)
33 }
34 }
35 result
36}
37
38pub(crate) fn path_as_string(path: &std::path::Path) -> String {
40 let mut path_str = String::new();
41 for component in path.components() {
42 if let Component::Normal(os_str) = component {
43 if !path_str.is_empty() {
44 path_str.push('/');
45 }
46 path_str.push_str(&*os_str.to_string_lossy());
47 }
48 }
49 path_str
50}