Debian Codegraph @

rust/hg-core/src/utils/files.rs

raw
1 // files.rs
2 //
3 // Copyright 2019
4 // Raphaël Gomès <[email protected]>,
5 // Yuya Nishihara <[email protected]>
6 //
7 // This software may be used and distributed according to the terms of the
8 // GNU General Public License version 2 or any later version.
9
10 //! Functions for fiddling with files.
11
12 use std::borrow::Cow;
13 use std::borrow::ToOwned;
14 use std::ffi::OsStr;
15 use std::ffi::OsString;
16 use std::io;
17 use std::iter::FusedIterator;
18 use std::ops::Deref;
19 use std::os::unix::fs::PermissionsExt;
20 use std::path::Path;
21 use std::path::PathBuf;
22 use std::time::SystemTime;
23
24 use lazy_static::lazy_static;
25 use same_file::is_same_file;
26
27 use super::strings::replace_slice;
28 use crate::utils::hg_path::path_to_hg_path_buf;
29 use crate::utils::hg_path::HgPath;
30 use crate::utils::hg_path::HgPathBuf;
31 use crate::utils::hg_path::HgPathError;
32 use crate::utils::hg_path::HgPathErrorKind;
33 use crate::utils::path_auditor::PathAuditor;
34
35 pub fn get_os_str_from_bytes(bytes: &[u8]) -> &OsStr {
36 let os_str;
37 #[cfg(unix)]
38 {
39 use std::os::unix::ffi::OsStrExt;
40 os_str = std::ffi::OsStr::from_bytes(bytes);
41 }
42 // TODO Handle other platforms
43 // TODO: convert from WTF8 to Windows MBCS (ANSI encoding).
44 // Perhaps, the return type would have to be Result<PathBuf>.
45 os_str
46 }
47
48 pub fn get_path_from_bytes(bytes: &[u8]) -> &Path {
49 Path::new(get_os_str_from_bytes(bytes))
50 }
51
52 // TODO: need to convert from WTF8 to MBCS bytes on Windows.
53 // that's why Vec<u8> is returned.
54 #[cfg(unix)]
55 pub fn get_bytes_from_path(path: impl AsRef<Path>) -> Vec<u8> {
56 get_bytes_from_os_str(path.as_ref())
57 }
58
59 #[cfg(unix)]
60 pub fn get_bytes_from_os_str(str: impl AsRef<OsStr>) -> Vec<u8> {
61 use std::os::unix::ffi::OsStrExt;
62 str.as_ref().as_bytes().to_vec()
63 }
64
65 #[cfg(unix)]
66 pub fn get_bytes_from_os_string(str: OsString) -> Vec<u8> {
67 use std::os::unix::ffi::OsStringExt;
68 str.into_vec()
69 }
70
71 /// An iterator over repository path yielding itself and its ancestors.
72 #[derive(Copy, Clone, Debug)]
73 pub struct Ancestors<'a> {
74 next: Option<&'a HgPath>,
75 }
76
77 impl<'a> Iterator for Ancestors<'a> {
78 type Item = &'a HgPath;
79
80 fn next(&mut self) -> Option<Self::Item> {
81 let next = self.next;
82 self.next = match self.next {
83 Some(s) if s.is_empty() => None,
84 Some(s) => {
85 let p = s.bytes().rposition(|c| *c == b'/').unwrap_or(0);
86 Some(HgPath::new(&s.as_bytes()[..p]))
87 }
88 None => None,
89 };
90 next
91 }
92 }
93
94 impl FusedIterator for Ancestors<'_> {}
95
96 /// An iterator over repository path yielding itself and its ancestors.
97 #[derive(Copy, Clone, Debug)]
98 pub(crate) struct AncestorsWithBase<'a> {
99 next: Option<(&'a HgPath, &'a HgPath)>,
100 }
101
102 impl<'a> Iterator for AncestorsWithBase<'a> {
103 type Item = (&'a HgPath, &'a HgPath);
104
105 fn next(&mut self) -> Option<Self::Item> {
106 let next = self.next;
107 self.next = match self.next {
108 Some((s, _)) if s.is_empty() => None,
109 Some((s, _)) => Some(s.split_filename()),
110 None => None,
111 };
112 next
113 }
114 }
115
116 impl FusedIterator for AncestorsWithBase<'_> {}
117
118 /// Returns an iterator yielding ancestor directories of the given repository
119 /// path.
120 ///
121 /// The path is separated by '/', and must not start with '/'.
122 ///
123 /// The path itself isn't included unless it is b"" (meaning the root
124 /// directory.)
125 pub fn find_dirs(path: &HgPath) -> Ancestors {
126 let mut dirs = Ancestors { next: Some(path) };
127 if !path.is_empty() {
128 dirs.next(); // skip itself
129 }
130 dirs
131 }
132
133 /// Returns an iterator yielding ancestor directories of the given repository
134 /// path from (but excluding) the root.
135 ///
136 /// The path is separated by '/', and must not start with '/'.
137 ///
138 /// The path itself isn't included.
139 pub fn find_dirs_recursive_no_root<'a>(
140 path: &'a HgPath,
141 ) -> std::iter::FromFn<impl FnMut() -> Option<&'a HgPath>> {
142 let mut positions =
143 path.bytes().enumerate().filter(|&(_, &c)| c == b'/').map(|(i, _)| i);
144 std::iter::from_fn(move || {
145 let p = positions.next().unwrap_or(path.len());
146 if p == path.len() {
147 None
148 } else {
149 Some(HgPath::new(&path.as_bytes()[..p]))
150 }
151 })
152 }
153
154 pub fn dir_ancestors(path: &HgPath) -> Ancestors {
155 Ancestors { next: Some(path) }
156 }
157
158 /// Returns an iterator yielding ancestor directories of the given repository
159 /// path.
160 ///
161 /// The path is separated by '/', and must not start with '/'.
162 ///
163 /// The path itself isn't included unless it is b"" (meaning the root
164 /// directory.)
165 pub(crate) fn find_dirs_with_base(path: &HgPath) -> AncestorsWithBase {
166 let mut dirs = AncestorsWithBase { next: Some((path, HgPath::new(b""))) };
167 if !path.is_empty() {
168 dirs.next(); // skip itself
169 }
170 dirs
171 }
172
173 /// TODO more than ASCII?
174 pub fn normalize_case(path: &HgPath) -> HgPathBuf {
175 #[cfg(windows)] // NTFS compares via upper()
176 return path.to_ascii_uppercase();
177 #[cfg(unix)]
178 path.to_ascii_lowercase()
179 }
180
181 lazy_static! {
182 static ref IGNORED_CHARS: Vec<Vec<u8>> = {
183 [
184 0x200c, 0x200d, 0x200e, 0x200f, 0x202a, 0x202b, 0x202c, 0x202d,
185 0x202e, 0x206a, 0x206b, 0x206c, 0x206d, 0x206e, 0x206f, 0xfeff,
186 ]
187 .iter()
188 .map(|code| {
189 std::char::from_u32(*code)
190 .unwrap()
191 .encode_utf8(&mut [0; 3])
192 .bytes()
193 .collect()
194 })
195 .collect()
196 };
197 }
198
199 fn hfs_ignore_clean(bytes: &[u8]) -> Vec<u8> {
200 let mut buf = bytes.to_owned();
201 let needs_escaping = bytes.iter().any(|b| *b == b'\xe2' || *b == b'\xef');
202 if needs_escaping {
203 for forbidden in IGNORED_CHARS.iter() {
204 buf = replace_slice(&buf, forbidden, &[]);
205 }
206 buf
207 } else {
208 buf
209 }
210 }
211
212 pub fn lower_clean(bytes: &[u8]) -> Vec<u8> {
213 hfs_ignore_clean(&bytes.to_ascii_lowercase())
214 }
215
216 /// Returns the canonical path of `name`, given `cwd` and `root`
217 pub fn canonical_path(
218 root: impl AsRef<Path>,
219 cwd: impl AsRef<Path>,
220 name: impl AsRef<Path>,
221 ) -> Result<PathBuf, HgPathError> {
222 // TODO add missing normalization for other platforms
223 let root = root.as_ref();
224 let cwd = cwd.as_ref();
225 let name = name.as_ref();
226
227 let name = if !name.is_absolute() {
228 root.join(cwd).join(name)
229 } else {
230 name.to_owned()
231 };
232 let auditor = PathAuditor::new(root);
233 if name != root && name.starts_with(root) {
234 let name = name.strip_prefix(root).unwrap();
235 auditor.audit_path(path_to_hg_path_buf(name)?)?;
236 Ok(name.to_owned())
237 } else if name == root {
238 Ok("".into())
239 } else {
240 // Determine whether `name' is in the hierarchy at or beneath `root',
241 // by iterating name=name.parent() until it returns `None` (can't
242 // check name == '/', because that doesn't work on windows).
243 let mut name = name.deref();
244 let original_name = name.to_owned();
245 loop {
246 let same = is_same_file(name, root).unwrap_or(false);
247 if same {
248 if name == original_name {
249 // `name` was actually the same as root (maybe a symlink)
250 return Ok("".into());
251 }
252 // `name` is a symlink to root, so `original_name` is under
253 // root
254 let rel_path = original_name.strip_prefix(name).unwrap();
255 auditor.audit_path(path_to_hg_path_buf(rel_path)?)?;
256 return Ok(rel_path.to_owned());
257 }
258 name = match name.parent() {
259 None => break,
260 Some(p) => p,
261 };
262 }
263 // TODO hint to the user about using --cwd
264 // Bubble up the responsibility to Python for now
265 Err(HgPathErrorKind::NotUnderRoot {
266 path: original_name,
267 root: root.to_owned(),
268 }
269 .into())
270 }
271 }
272
273 /// Returns the representation of the path relative to the current working
274 /// directory for display purposes.
275 ///
276 /// `cwd` is a `HgPath`, so it is considered relative to the root directory
277 /// of the repository.
278 ///
279 /// # Examples
280 ///
281 /// ```
282 /// use hg::utils::hg_path::HgPath;
283 /// use hg::utils::files::relativize_path;
284 /// use std::borrow::Cow;
285 ///
286 /// let file = HgPath::new(b"nested/file");
287 /// let cwd = HgPath::new(b"");
288 /// assert_eq!(relativize_path(file, cwd), Cow::Borrowed(b"nested/file"));
289 ///
290 /// let cwd = HgPath::new(b"nested");
291 /// assert_eq!(relativize_path(file, cwd), Cow::Borrowed(b"file"));
292 ///
293 /// let cwd = HgPath::new(b"other");
294 /// assert_eq!(relativize_path(file, cwd), Cow::Borrowed(b"../nested/file"));
295 /// ```
296 pub fn relativize_path(path: &HgPath, cwd: impl AsRef<HgPath>) -> Cow<[u8]> {
297 if cwd.as_ref().is_empty() {
298 Cow::Borrowed(path.as_bytes())
299 } else {
300 // This is not all accurate as to how large `res` will actually be, but
301 // profiling `rhg files` on a large-ish repo shows it’s better than
302 // starting from a zero-capacity `Vec` and letting `extend` reallocate
303 // repeatedly.
304 let guesstimate = path.as_bytes().len();
305
306 let mut res: Vec<u8> = Vec::with_capacity(guesstimate);
307 let mut path_iter = path.as_bytes().split(|b| *b == b'/').peekable();
308 let mut cwd_iter =
309 cwd.as_ref().as_bytes().split(|b| *b == b'/').peekable();
310 loop {
311 match (path_iter.peek(), cwd_iter.peek()) {
312 (Some(a), Some(b)) if a == b => (),
313 _ => break,
314 }
315 path_iter.next();
316 cwd_iter.next();
317 }
318 let mut need_sep = false;
319 for _ in cwd_iter {
320 if need_sep {
321 res.extend(b"/")
322 } else {
323 need_sep = true
324 };
325 res.extend(b"..");
326 }
327 for c in path_iter {
328 if need_sep {
329 res.extend(b"/")
330 } else {
331 need_sep = true
332 };
333 res.extend(c);
334 }
335 Cow::Owned(res)
336 }
337 }
338
339 /// Return the `mtime` of a temporary file newly-created in the `.hg` directory
340 /// of the give repository.
341 ///
342 /// This is similar to `SystemTime::now()`, with the result truncated to the
343 /// same time resolution as other files’ modification times. Using `.hg`
344 /// instead of the system’s default temporary directory (such as `/tmp`) makes
345 /// it more likely the temporary file is in the same disk partition as contents
346 /// of the working directory, which can matter since different filesystems may
347 /// store timestamps with different resolutions.
348 ///
349 /// This may fail, typically if we lack write permissions. In that case we
350 /// should continue the `status()` algoritm anyway and consider the current
351 /// date/time to be unknown.
352 pub fn filesystem_now(repo_root: &Path) -> Result<SystemTime, io::Error> {
353 tempfile::Builder::new()
354 .permissions(std::fs::Permissions::from_mode(0o666))
355 .tempfile_in(repo_root.join(".hg"))?
356 .into_file()
357 .metadata()?
358 .modified()
359 }
360
361 /// Returns true if file content is considered to be binary (not text).
362 pub fn is_binary(content: &[u8]) -> bool {
363 // Matches binary() in utils/stringutil.py.
364 !content.is_empty() && memchr::memchr(b'\0', content).is_some()
365 }
366
367 #[cfg(test)]
368 mod tests {
369 use pretty_assertions::assert_eq;
370
371 use super::*;
372
373 #[test]
374 fn find_dirs_some() {
375 let mut dirs = super::find_dirs(HgPath::new(b"foo/bar/baz"));
376 assert_eq!(dirs.next(), Some(HgPath::new(b"foo/bar")));
377 assert_eq!(dirs.next(), Some(HgPath::new(b"foo")));
378 assert_eq!(dirs.next(), Some(HgPath::new(b"")));
379 assert_eq!(dirs.next(), None);
380 assert_eq!(dirs.next(), None);
381 }
382 #[test]
383 fn find_dirs_recursive_no_root_some() {
384 let mut dirs =
385 super::find_dirs_recursive_no_root(HgPath::new(b"foo/bar/baz"));
386 assert_eq!(dirs.next(), Some(HgPath::new(b"foo")));
387 assert_eq!(dirs.next(), Some(HgPath::new(b"foo/bar")));
388 assert_eq!(dirs.next(), None);
389 assert_eq!(dirs.next(), None);
390 }
391
392 #[test]
393 fn find_dirs_recursive_no_root_empty() {
394 let mut dirs = super::find_dirs_recursive_no_root(HgPath::new(b""));
395 assert_eq!(dirs.next(), None);
396 assert_eq!(dirs.next(), None);
397 }
398
399 #[test]
400 fn find_dirs_empty() {
401 // looks weird, but mercurial.pathutil.finddirs(b"") yields b""
402 let mut dirs = super::find_dirs(HgPath::new(b""));
403 assert_eq!(dirs.next(), Some(HgPath::new(b"")));
404 assert_eq!(dirs.next(), None);
405 assert_eq!(dirs.next(), None);
406 }
407
408 #[test]
409 fn test_find_dirs_with_base_some() {
410 let mut dirs = super::find_dirs_with_base(HgPath::new(b"foo/bar/baz"));
411 assert_eq!(
412 dirs.next(),
413 Some((HgPath::new(b"foo/bar"), HgPath::new(b"baz")))
414 );
415 assert_eq!(
416 dirs.next(),
417 Some((HgPath::new(b"foo"), HgPath::new(b"bar")))
418 );
419 assert_eq!(dirs.next(), Some((HgPath::new(b""), HgPath::new(b"foo"))));
420 assert_eq!(dirs.next(), None);
421 assert_eq!(dirs.next(), None);
422 }
423
424 #[test]
425 fn test_find_dirs_with_base_empty() {
426 let mut dirs = super::find_dirs_with_base(HgPath::new(b""));
427 assert_eq!(dirs.next(), Some((HgPath::new(b""), HgPath::new(b""))));
428 assert_eq!(dirs.next(), None);
429 assert_eq!(dirs.next(), None);
430 }
431
432 #[test]
433 fn test_canonical_path() {
434 let root = Path::new("/repo");
435 let cwd = Path::new("/dir");
436 let name = Path::new("filename");
437 assert_eq!(
438 canonical_path(root, cwd, name),
439 Err(HgPathErrorKind::NotUnderRoot {
440 path: PathBuf::from("/dir/filename"),
441 root: root.to_path_buf()
442 }
443 .into())
444 );
445
446 let root = Path::new("/repo");
447 let cwd = Path::new("/");
448 let name = Path::new("filename");
449 assert_eq!(
450 canonical_path(root, cwd, name),
451 Err(HgPathErrorKind::NotUnderRoot {
452 path: PathBuf::from("/filename"),
453 root: root.to_path_buf()
454 }
455 .into())
456 );
457
458 let root = Path::new("/repo");
459 let cwd = Path::new("/");
460 let name = Path::new("repo/filename");
461 assert_eq!(
462 canonical_path(root, cwd, name),
463 Ok(PathBuf::from("filename"))
464 );
465
466 let root = Path::new("/repo");
467 let cwd = Path::new("/repo");
468 let name = Path::new("filename");
469 assert_eq!(
470 canonical_path(root, cwd, name),
471 Ok(PathBuf::from("filename"))
472 );
473
474 let root = Path::new("/repo");
475 let cwd = Path::new("/repo/subdir");
476 let name = Path::new("filename");
477 assert_eq!(
478 canonical_path(root, cwd, name),
479 Ok(PathBuf::from("subdir/filename"))
480 );
481 }
482
483 #[test]
484 fn test_canonical_path_not_rooted() {
485 use std::fs::create_dir;
486
487 use tempfile::tempdir;
488
489 let base_dir = tempdir().unwrap();
490 let base_dir_path = base_dir.path();
491 let beneath_repo = base_dir_path.join("a");
492 let root = base_dir_path.join("a/b");
493 let out_of_repo = base_dir_path.join("c");
494 let under_repo_symlink = out_of_repo.join("d");
495
496 create_dir(&beneath_repo).unwrap();
497 create_dir(&root).unwrap();
498
499 // TODO make portable
500 std::os::unix::fs::symlink(&root, &out_of_repo).unwrap();
501
502 assert_eq!(
503 canonical_path(&root, Path::new(""), out_of_repo),
504 Ok(PathBuf::from(""))
505 );
506 assert_eq!(
507 canonical_path(&root, Path::new(""), &beneath_repo),
508 Err(HgPathErrorKind::NotUnderRoot {
509 path: beneath_repo,
510 root: root.to_owned()
511 }
512 .into())
513 );
514 assert_eq!(
515 canonical_path(&root, Path::new(""), under_repo_symlink),
516 Ok(PathBuf::from("d"))
517 );
518 }
519 }