-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.rs
More file actions
164 lines (142 loc) · 5.18 KB
/
Copy pathfs.rs
File metadata and controls
164 lines (142 loc) · 5.18 KB
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
// Copyright (c) 2026 Jan Holthuis <jan.holthuis@rub.de>
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy
// of the MPL was not distributed with this file, You can obtain one at
// http://mozilla.org/MPL/2.0/.
//
// SPDX-License-Identifier: MPL-2.0
//! Filesystem-related utility functions.
use std::collections::BinaryHeap;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::os::unix::{self, fs::PermissionsExt};
use std::path::{Path, PathBuf};
/// An iterator that recursively walks through a directory structure and yields a tuple `(path,
/// dirs, files)` for each directory it visits.
/// This struct is created by [`walk_dir`]. See its documentation for more.
pub struct DirWalk {
/// Queued paths that will be visited next.
queue: BinaryHeap<PathBuf>,
}
impl Iterator for DirWalk {
type Item = io::Result<(PathBuf, Vec<PathBuf>, Vec<PathBuf>)>;
fn next(&mut self) -> Option<Self::Item> {
let queued_path = self.queue.pop();
queued_path.map(move |path| {
log::debug!("Queued path: {}", path.display());
fs::read_dir(&path).and_then(move |entries| {
let mut files = vec![];
let mut dirs = vec![];
for entry in entries {
let entry_path = entry?.path();
if entry_path.is_dir() {
dirs.push(entry_path.clone());
} else {
files.push(entry_path);
}
}
files.sort_unstable();
for dir in dirs.clone() {
self.queue.push(dir);
}
Ok((path, dirs, files))
})
})
}
}
/// Creates an iterator that walks through a directory structure recursively and yields a tuple
/// consisting of the path of current directory and the files and directories in that directory.
pub fn walk_dir(path: PathBuf) -> DirWalk {
let mut queue = BinaryHeap::new();
queue.push(path);
DirWalk { queue }
}
/// Copy the file
pub fn copy_file<S: AsRef<Path>, D: AsRef<Path>>(source: S, destination: D) -> io::Result<()> {
let dest_filename = destination
.as_ref()
.file_name()
.and_then(OsStr::to_str)
.ok_or(io::Error::other("cannot determine destination file name"))?;
let dest_dir = destination
.as_ref()
.parent()
.ok_or(io::Error::other("cannot determine destination directory"))?;
fs::create_dir_all(dest_dir)?;
let mut temp_destination_file = tempfile::Builder::new()
.prefix(format!(".helicon.{dest_filename}").as_str())
.suffix(".tmp")
.tempfile_in(dest_dir)?;
let mut source_file = fs::File::open(&source)?;
let _ = io::copy(&mut source_file, &mut temp_destination_file)?;
// When copying succeeded, persist the temporary file at the actual destination.
let temp_destination = temp_destination_file.into_temp_path();
temp_destination.persist(&destination)?;
log::info!(
"Copied file {} to {}",
source.as_ref().display(),
destination.as_ref().display()
);
Ok(())
}
/// Move the file.
pub fn move_file<S: AsRef<Path>, D: AsRef<Path>>(source: S, destination: D) -> crate::Result<()> {
// First, try renaming.
if let Ok(()) = fs::rename(&source, &destination) {
log::info!(
"Renamed file {} to {}",
source.as_ref().display(),
destination.as_ref().display()
);
return Ok(());
}
// If that didn't work, try to copy the source file to a temporary file on the destination
// filesystem and persist the temporary file under the actual destination path if this
// succeeds.
copy_file(&source, destination)?;
// Then remove the source file.
fs::remove_file(&source)?;
log::info!("Removed file {}", source.as_ref().display());
Ok(())
}
/// Set file/directory owner and permissions.
#[cfg(unix)]
pub fn set_file_permissions<S: AsRef<Path>>(
source: S,
uid: Option<u32>,
gid: Option<u32>,
mode: Option<u32>,
) -> crate::Result<()> {
let path = source.as_ref();
unix::fs::chown(path, uid, gid)?;
match (uid, gid) {
(Some(owner), Some(group)) => {
log::info!(
"Changed owner/group for {} to {owner}:{group}.",
path.display()
);
}
(Some(owner), None) => {
log::info!("Changed owner for {} to {owner}.", path.display());
}
(None, Some(group)) => {
log::info!("Changed group for {} to {group}.", path.display());
}
_ => (),
}
if let Some(new_mode) = mode {
let metadata = fs::metadata(path)?;
let permissions = metadata.permissions();
let old_mode = permissions.mode();
if permissions.mode() != new_mode {
let permissions = fs::Permissions::from_mode(new_mode);
fs::set_permissions(path, permissions)?; // ← Works on paths (files & directories)
log::info!(
"Permission for {} changed from {old_mode:o} to {new_mode:o}.",
path.display()
);
}
}
Ok(())
}