返回 CodeWhale
lib.rs
根目录 / crates / paths / src / lib.rs
1 //! Canonical user-scoped runtime path resolution for Codewhale.
2 //!
3 //! This leaf crate owns environment, platform-home and daemon endpoint layout. File
4 //! migration and per-subsystem fallback remain with the crate that owns those
5 //! files.
6 #![deny(missing_docs)]
7
8 use std::ffi::OsString;
9 use std::fmt;
10 use std::path::{Path, PathBuf};
11
12 pub mod daemon_socket;
13
14 #[cfg(unix)]
15 #[doc(hidden)]
16 pub fn resolve_root_owned_ancestors(directory: &Path) -> PathBuf {
17 use std::os::unix::fs::MetadataExt as _;
18
19 let mut resolved = PathBuf::new();
20 for component in directory.components() {
21 resolved.push(component);
22 if let Ok(metadata) = std::fs::symlink_metadata(&resolved)
23 && metadata.file_type().is_symlink()
24 {
25 if metadata.uid() != 0 {
26 return directory.to_path_buf();
27 }
28 if let Ok(real) = resolved.canonicalize() {
29 resolved = real;
30 }
31 }
32 }
33 resolved
34 }
35
36 /// Canonical Codewhale app directory name under the user home.
37 pub const CODEWHALE_APP_DIR: &str = ".codewhale";
38
39 /// Legacy DeepSeek-branded directory retained for compatibility reads.
40 pub const LEGACY_APP_DIR: &str = ".deepseek";
41
42 /// An environment-provided runtime path was not safe to use as a global path.
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub struct PathOverrideError {
45 variable: &'static str,
46 path: PathBuf,
47 kind: PathOverrideErrorKind,
48 }
49
50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
51 enum PathOverrideErrorKind {
52 Relative,
53 HomeUnavailable,
54 }
55
56 impl fmt::Display for PathOverrideError {
57 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self.kind {
59 PathOverrideErrorKind::Relative => write!(
60 formatter,
61 "{} must be an absolute path, got {}",
62 self.variable,
63 self.path.display()
64 ),
65 PathOverrideErrorKind::HomeUnavailable => write!(
66 formatter,
67 "{} uses '~', but the user home directory could not be resolved: {}",
68 self.variable,
69 self.path.display()
70 ),
71 }
72 }
73 }
74
75 impl std::error::Error for PathOverrideError {}
76
77 /// Return the explicit Codewhale home override, if one is configured.
78 ///
79 /// Unicode values are trimmed so whitespace-only values are treated as unset,
80 /// matching the existing config and secret-store contract. Non-Unicode path
81 /// values are preserved on platforms that support them instead of silently
82 /// dropping an otherwise valid filesystem path. A leading `~` is expanded;
83 /// every other relative value is rejected.
84 pub fn codewhale_home_override() -> Result<Option<PathBuf>, PathOverrideError> {
85 absolute_path_env("CODEWHALE_HOME")
86 }
87
88 /// Whether `CODEWHALE_HOME` establishes an explicit isolation boundary.
89 #[must_use]
90 pub fn codewhale_home_is_explicit() -> bool {
91 path_env("CODEWHALE_HOME").is_some()
92 }
93
94 /// Resolve the user's platform home, preferring `HOME` before `USERPROFILE`.
95 ///
96 /// The explicit environment order makes CLI, state, config, and secret paths
97 /// deterministic in hermetic shells. On Windows, `HOMEDRIVE` plus `HOMEPATH`
98 /// remains a compatibility fallback before the platform resolver. The platform
99 /// resolver remains last for ordinary desktop launches without those variables.
100 ///
101 /// Only an absolute candidate is a home. A relative `HOME` (`HOME=.`,
102 /// `HOME=build`) would otherwise resolve against the process's working
103 /// directory and move config, state, and secrets into whatever repository the
104 /// process runs in. [`codewhale_home`] names that case as an error.
105 #[must_use]
106 pub fn user_home() -> Option<PathBuf> {
107 // An explicit invalid home is an error, not permission to fall back to
108 // the ambient Windows profile and escape a caller's isolation boundary.
109 if let Some(home) = path_env("HOME") {
110 return home.is_absolute().then_some(home);
111 }
112 path_env("USERPROFILE")
113 .filter(|path| path.is_absolute())
114 .or_else(windows_home_from_environment)
115 .or_else(dirs::home_dir)
116 .filter(|path| path.is_absolute())
117 }
118
119 #[cfg(windows)]
120 fn windows_home_from_environment() -> Option<PathBuf> {
121 let mut path = path_env("HOMEDRIVE")?;
122 path.push(path_env("HOMEPATH")?);
123 (!path.as_os_str().is_empty()).then_some(path)
124 }
125
126 #[cfg(not(windows))]
127 fn windows_home_from_environment() -> Option<PathBuf> {
128 None
129 }
130
131 /// Resolve the canonical Codewhale runtime home.
132 ///
133 /// A valid explicit `CODEWHALE_HOME` is returned after `~` expansion. Otherwise
134 /// this is `<user home>/.codewhale`.
135 pub fn codewhale_home() -> Result<Option<PathBuf>, PathOverrideError> {
136 if let Some(home) = codewhale_home_override()? {
137 return Ok(Some(home));
138 }
139 if let Some(home) = user_home() {
140 return Ok(Some(home.join(CODEWHALE_APP_DIR)));
141 }
142 // No absolute home anywhere: when that is because `HOME` is relative, say
143 // so rather than reporting a missing home.
144 match path_env("HOME").filter(|path| !path.is_absolute()) {
145 Some(path) => Err(PathOverrideError {
146 variable: "HOME",
147 path,
148 kind: PathOverrideErrorKind::Relative,
149 }),
150 None => Ok(None),
151 }
152 }
153
154 /// Return the explicit config-file override, preferring the Codewhale name.
155 ///
156 /// `~` is expanded through the canonical user-home resolver before the path is
157 /// validated. All other relative paths are rejected so a process working in a
158 /// repository can never turn a global config override into a repo-local file.
159 pub fn config_path_override() -> Result<Option<PathBuf>, PathOverrideError> {
160 if let Some(path) = absolute_path_env("CODEWHALE_CONFIG_PATH")? {
161 return Ok(Some(path));
162 }
163 absolute_path_env("DEEPSEEK_CONFIG_PATH")
164 }
165
166 /// Read an optional path environment variable and require a global path.
167 ///
168 /// Empty and whitespace-only values are treated as unset. A leading `~` path
169 /// is expanded first; any path still relative after expansion is rejected.
170 pub fn absolute_path_env(variable: &'static str) -> Result<Option<PathBuf>, PathOverrideError> {
171 path_env(variable)
172 .map(|path| validate_absolute_path(variable, path))
173 .transpose()
174 }
175
176 /// Expand a leading `~` and reject a path that is not absolute.
177 pub fn validate_absolute_path(
178 variable: &'static str,
179 path: PathBuf,
180 ) -> Result<PathBuf, PathOverrideError> {
181 let original = path.clone();
182 let path = match path.to_str() {
183 Some("~") => user_home().ok_or_else(|| PathOverrideError {
184 variable,
185 path: original.clone(),
186 kind: PathOverrideErrorKind::HomeUnavailable,
187 })?,
188 Some(value)
189 if value
190 .strip_prefix('~')
191 .is_some_and(|suffix| suffix.starts_with('/') || suffix.starts_with('\\')) =>
192 {
193 let mut home = user_home().ok_or_else(|| PathOverrideError {
194 variable,
195 path: original.clone(),
196 kind: PathOverrideErrorKind::HomeUnavailable,
197 })?;
198 let suffix = value[1..].trim_start_matches(['/', '\\']);
199 if !suffix.is_empty() {
200 home.push(suffix);
201 }
202 home
203 }
204 _ => path,
205 };
206
207 if path.is_absolute() {
208 Ok(path)
209 } else {
210 Err(PathOverrideError {
211 variable,
212 path: original,
213 kind: PathOverrideErrorKind::Relative,
214 })
215 }
216 }
217
218 /// Resolve the ambient legacy DeepSeek home used for compatibility reads.
219 ///
220 /// This never follows `CODEWHALE_HOME`: callers must suppress legacy fallback
221 /// whenever [`codewhale_home_is_explicit`] is true.
222 #[must_use]
223 pub fn legacy_deepseek_home() -> Option<PathBuf> {
224 user_home().map(|home| home.join(LEGACY_APP_DIR))
225 }
226
227 fn path_env(name: &str) -> Option<PathBuf> {
228 std::env::var_os(name).and_then(normalize_path_value)
229 }
230
231 fn normalize_path_value(value: OsString) -> Option<PathBuf> {
232 if value.is_empty() {
233 return None;
234 }
235 match value.to_str() {
236 Some(value) => {
237 let value = value.trim();
238 (!value.is_empty()).then(|| PathBuf::from(value))
239 }
240 None => Some(PathBuf::from(value)),
241 }
242 }
243
244 /// Strip a trailing `.worktrees/<name>` segment so all worktrees of the same
245 /// checkout share a `project_hash`. If the path doesn't look like a worktree
246 /// it's returned unchanged.
247 #[must_use]
248 pub fn strip_worktree_suffix(path: &Path) -> PathBuf {
249 let mut components: Vec<_> = path.components().collect();
250 if components.len() >= 2
251 && let Some(parent) = components.get(components.len() - 2)
252 && parent.as_os_str() == ".worktrees"
253 {
254 components.truncate(components.len() - 2);
255 let mut p = PathBuf::new();
256 for c in components {
257 p.push(c.as_os_str());
258 }
259 return p;
260 }
261 path.to_path_buf()
262 }
263
264 /// Hex-encoded deterministic FNV-1a digest. This is only a directory tag, not
265 /// a security boundary, but it must remain stable across process launches.
266 ///
267 /// Lives here, below both `codewhale-snapshot` and `codewhale-runtime`, because
268 /// each derives its own on-disk layout from the same project/worktree split.
269 /// Two copies would be two things to keep in step.
270 #[must_use]
271 pub fn stable_hex(path: &Path) -> String {
272 let mut hash = 0xcbf2_9ce4_8422_2325u64;
273 for byte in path.to_string_lossy().as_bytes() {
274 hash ^= u64::from(*byte);
275 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
276 }
277 format!("{hash:016x}")
278 }
279
280 #[cfg(test)]
281 mod tests {
282 use super::*;
283
284 #[test]
285 fn unicode_path_values_are_trimmed_and_whitespace_is_unset() {
286 assert_eq!(
287 normalize_path_value(OsString::from(" /tmp/codewhale ")),
288 Some(PathBuf::from("/tmp/codewhale"))
289 );
290 assert_eq!(normalize_path_value(OsString::from(" \t\n ")), None);
291 assert_eq!(normalize_path_value(OsString::new()), None);
292 }
293
294 #[test]
295 fn relative_global_overrides_are_rejected_with_the_variable_name() {
296 let error = validate_absolute_path(
297 "CODEWHALE_CONFIG_PATH",
298 PathBuf::from(".codewhale/config.toml"),
299 )
300 .expect_err("relative global config path must fail closed");
301 let message = error.to_string();
302 assert!(message.contains("CODEWHALE_CONFIG_PATH"), "{message}");
303 assert!(message.contains(".codewhale/config.toml"), "{message}");
304 assert!(message.contains("absolute"), "{message}");
305 }
306
307 #[test]
308 fn absolute_global_overrides_are_preserved() {
309 let path = if cfg!(windows) {
310 PathBuf::from(r"C:\codewhale\config.toml")
311 } else {
312 PathBuf::from("/tmp/codewhale/config.toml")
313 };
314 assert_eq!(
315 validate_absolute_path("CODEWHALE_CONFIG_PATH", path.clone()),
316 Ok(path)
317 );
318 }
319
320 #[cfg(unix)]
321 #[test]
322 fn unix_non_unicode_path_values_are_preserved() {
323 use std::os::unix::ffi::OsStringExt;
324
325 let value = OsString::from_vec(b"codewhale-\xff-home".to_vec());
326 assert_eq!(
327 normalize_path_value(value.clone()),
328 Some(PathBuf::from(value))
329 );
330 }
331
332 #[cfg(windows)]
333 #[test]
334 fn windows_non_unicode_path_values_are_preserved() {
335 use std::os::windows::ffi::OsStringExt;
336
337 let value = OsString::from_wide(&[b'C' as u16, b':' as u16, b'\\' as u16, 0xd800]);
338 assert_eq!(
339 normalize_path_value(value.clone()),
340 Some(PathBuf::from(value))
341 );
342 }
343 }
344
344 lines RUST