| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Paths of the repository, which are bytes, and the file system names they |
| 5 | //! become. |
| 6 | |
| 7 | use std::borrow::Cow; |
| 8 | use std::ffi::OsStr; |
| 9 | use std::path::{Component, Path, PathBuf}; |
| 10 | |
| 11 | use crate::error::Error; |
| 12 | |
| 13 | /// How many bytes of a path messages show. |
| 14 | const SHOWN_BYTES: usize = 256; |
| 15 | |
| 16 | /// A path for messages: lossy UTF-8, cut short if it is long. |
| 17 | pub(crate) fn show(path: &[u8]) -> Cow<'_, str> { |
| 18 | if path.len() <= SHOWN_BYTES { |
| 19 | return String::from_utf8_lossy(path); |
| 20 | } |
| 21 | let mut shown = String::from_utf8_lossy(&path[..SHOWN_BYTES]).into_owned(); |
| 22 | shown.push('…'); |
| 23 | Cow::Owned(shown) |
| 24 | } |
| 25 | |
| 26 | /// `dir/name`, or `name` when `dir` is the root (empty). |
| 27 | pub(crate) fn join(dir: &[u8], name: &[u8]) -> Vec<u8> { |
| 28 | let mut path = Vec::with_capacity(dir.len() + 1 + name.len()); |
| 29 | if !dir.is_empty() { |
| 30 | path.extend_from_slice(dir); |
| 31 | path.push(b'/'); |
| 32 | } |
| 33 | path.extend_from_slice(name); |
| 34 | path |
| 35 | } |
| 36 | |
| 37 | /// The directory part and the last name of a path; the directory of a path |
| 38 | /// with one name is the root, empty. |
| 39 | pub(crate) fn split_last(path: &[u8]) -> (&[u8], &[u8]) { |
| 40 | match path.iter().rposition(|byte| *byte == b'/') { |
| 41 | Some(slash) => (&path[..slash], &path[slash + 1..]), |
| 42 | None => (&[], path), |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /// The names of a path. |
| 47 | pub(crate) fn names(path: &[u8]) -> impl Iterator<Item = &[u8]> { |
| 48 | path.split(|byte| *byte == b'/') |
| 49 | .filter(|name| !name.is_empty()) |
| 50 | } |
| 51 | |
| 52 | /// Every proper prefix of `path` that names a directory, shortest first: |
| 53 | /// `a`, `a/b` for `a/b/c`. |
| 54 | pub(crate) fn ancestors(path: &[u8]) -> impl Iterator<Item = &[u8]> { |
| 55 | path.iter() |
| 56 | .enumerate() |
| 57 | .filter(|(_, byte)| **byte == b'/') |
| 58 | .map(|(at, _)| &path[..at]) |
| 59 | } |
| 60 | |
| 61 | /// Whether `path` is `prefix` or lies below it. The empty prefix is the |
| 62 | /// root, which holds everything. |
| 63 | pub(crate) fn is_within(path: &[u8], prefix: &[u8]) -> bool { |
| 64 | prefix.is_empty() |
| 65 | || path == prefix |
| 66 | || (path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/') |
| 67 | } |
| 68 | |
| 69 | /// The file system name for one name of a repository path, if this platform |
| 70 | /// can represent it at all. |
| 71 | pub(crate) fn os_name(name: &[u8]) -> Option<&OsStr> { |
| 72 | #[cfg(unix)] |
| 73 | { |
| 74 | use std::os::unix::ffi::OsStrExt; |
| 75 | Some(OsStr::from_bytes(name)) |
| 76 | } |
| 77 | #[cfg(not(unix))] |
| 78 | { |
| 79 | std::str::from_utf8(name).ok().map(OsStr::new) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// The repository bytes of a file system name, if it has any. |
| 84 | pub(crate) fn name_bytes(name: &OsStr) -> Option<&[u8]> { |
| 85 | #[cfg(unix)] |
| 86 | { |
| 87 | use std::os::unix::ffi::OsStrExt; |
| 88 | Some(name.as_bytes()) |
| 89 | } |
| 90 | #[cfg(not(unix))] |
| 91 | { |
| 92 | name.to_str().map(str::as_bytes) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Why this platform cannot hold `name` as a file name, if it cannot. |
| 97 | /// |
| 98 | /// The store accepts names that some systems cannot write: Apple file |
| 99 | /// systems store names as UTF-8 and Windows forbids a set of characters and |
| 100 | /// device names. Such a name is refused before anything is written. |
| 101 | pub(crate) fn platform_problem(name: &[u8]) -> Option<&'static str> { |
| 102 | if os_name(name).is_none() { |
| 103 | return Some("the name is not valid UTF-8, which this platform needs"); |
| 104 | } |
| 105 | if cfg!(target_vendor = "apple") && std::str::from_utf8(name).is_err() { |
| 106 | return Some("the name is not valid UTF-8, which this file system needs"); |
| 107 | } |
| 108 | if cfg!(windows) { |
| 109 | if name |
| 110 | .iter() |
| 111 | .any(|byte| *byte < 0x20 || br#"<>:"\|?*"#.contains(byte)) |
| 112 | { |
| 113 | return Some("the name holds a character Windows does not allow"); |
| 114 | } |
| 115 | if matches!(name.last(), Some(b'.' | b' ')) { |
| 116 | return Some("Windows drops a final dot or space"); |
| 117 | } |
| 118 | let stem = name.split(|byte| *byte == b'.').next().unwrap_or(name); |
| 119 | let stem = stem.to_ascii_uppercase(); |
| 120 | let device = matches!(stem.as_slice(), b"CON" | b"PRN" | b"AUX" | b"NUL") |
| 121 | || (stem.len() == 4 |
| 122 | && (stem.starts_with(b"COM") || stem.starts_with(b"LPT")) |
| 123 | && stem[3].is_ascii_digit()); |
| 124 | if device { |
| 125 | return Some("the name is a Windows device name"); |
| 126 | } |
| 127 | } |
| 128 | None |
| 129 | } |
| 130 | |
| 131 | /// Resolves a path given on the command line, relative to `cwd`, into a |
| 132 | /// path of the workspace whose root is `root`. Both must be absolute and |
| 133 | /// free of symlinks. `.` and `..` are resolved by name, without looking at |
| 134 | /// the file system. The workspace root itself is the empty path. |
| 135 | pub fn workspace_path(root: &Path, cwd: &Path, given: &Path) -> Result<Vec<u8>, Error> { |
| 136 | let joined = cwd.join(given); |
| 137 | let mut normal = PathBuf::new(); |
| 138 | for component in joined.components() { |
| 139 | match component { |
| 140 | Component::CurDir => {} |
| 141 | Component::ParentDir => { |
| 142 | normal.pop(); |
| 143 | } |
| 144 | other => normal.push(other.as_os_str()), |
| 145 | } |
| 146 | } |
| 147 | let relative = normal |
| 148 | .strip_prefix(root) |
| 149 | .map_err(|_| Error::OutsideWorkspace(given.to_path_buf()))?; |
| 150 | let mut bytes = Vec::new(); |
| 151 | for component in relative.components() { |
| 152 | let name = name_bytes(component.as_os_str()) |
| 153 | .ok_or_else(|| Error::OutsideWorkspace(given.to_path_buf()))?; |
| 154 | if !bytes.is_empty() { |
| 155 | bytes.push(b'/'); |
| 156 | } |
| 157 | bytes.extend_from_slice(name); |
| 158 | } |
| 159 | Ok(bytes) |
| 160 | } |
| 161 | |
| 162 | #[cfg(test)] |
| 163 | mod tests { |
| 164 | use super::*; |
| 165 | |
| 166 | #[test] |
| 167 | fn helpers() { |
| 168 | assert_eq!(join(b"", b"a"), b"a"); |
| 169 | assert_eq!(join(b"a/b", b"c"), b"a/b/c"); |
| 170 | assert_eq!(split_last(b"a/b/c"), (&b"a/b"[..], &b"c"[..])); |
| 171 | assert_eq!(split_last(b"c"), (&b""[..], &b"c"[..])); |
| 172 | assert_eq!(ancestors(b"a/b/c").collect::<Vec<_>>(), [&b"a"[..], b"a/b"]); |
| 173 | assert_eq!(ancestors(b"c").count(), 0); |
| 174 | assert_eq!(names(b"a/b").collect::<Vec<_>>(), [&b"a"[..], b"b"]); |
| 175 | assert!(is_within(b"a/b", b"a")); |
| 176 | assert!(is_within(b"a", b"a")); |
| 177 | assert!(is_within(b"anything", b"")); |
| 178 | assert!(!is_within(b"ab", b"a")); |
| 179 | assert!(!is_within(b"a", b"a/b")); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn command_line_paths() { |
| 184 | let root = Path::new("/w/ws"); |
| 185 | let cwd = Path::new("/w/ws/src"); |
| 186 | assert_eq!( |
| 187 | workspace_path(root, cwd, Path::new("a.rs")).unwrap(), |
| 188 | b"src/a.rs" |
| 189 | ); |
| 190 | assert_eq!(workspace_path(root, cwd, Path::new("../b")).unwrap(), b"b"); |
| 191 | assert_eq!( |
| 192 | workspace_path(root, cwd, Path::new("./x/../y")).unwrap(), |
| 193 | b"src/y" |
| 194 | ); |
| 195 | assert_eq!(workspace_path(root, cwd, Path::new("..")).unwrap(), b""); |
| 196 | assert_eq!( |
| 197 | workspace_path(root, cwd, Path::new("/w/ws/c")).unwrap(), |
| 198 | b"c" |
| 199 | ); |
| 200 | assert!(matches!( |
| 201 | workspace_path(root, cwd, Path::new("../../other")), |
| 202 | Err(Error::OutsideWorkspace(_)) |
| 203 | )); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn platform_names() { |
| 208 | assert_eq!(platform_problem(b"README.md"), None); |
| 209 | if cfg!(target_vendor = "apple") { |
| 210 | assert!(platform_problem(b"\xff").is_some()); |
| 211 | } |
| 212 | } |
| 213 | } |