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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! What:
//! Classify the worktree an invocation targets for worktree-enforcing policies.
//! Why:
//! Linked-worktree safeguards discipline a person's repositories,
//! not the
//! disposable clones a tool keeps in its own cache.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! // classifyEffectiveTarget(identity, allowedDirs) === 'linked-worktree'
//! ```
/// Import getenv-style lookup and the resolved repository identity.
use super::child_environment::environment_value;
use super::worktree_identity::WorktreeIdentity;
/// What:
/// `OsString` is owned operating-system text of raw OS bytes (sibling `String`
/// must be UTF-8).
/// Why:
/// Cache directories come from environment values that need not be UTF-8.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// // process.env values, but byte-preserving.
/// ```
use std::ffi::OsString;
/// `Path`/`PathBuf` are borrowed/owned filesystem paths of raw OS bytes.
use std::path::{Path, PathBuf};
/// What:
/// The four targets worktree policies distinguish.
/// `#[derive(...)]` generates copying,
/// debug printing and `==`.
/// Why:
/// A bare repository or no repository has no worktree to protect;
/// an
/// allowlisted tool cache is exempt;
/// main versus linked decides enforcement.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type EffectiveTarget = 'outside-worktree' | 'main-worktree' | 'linked-worktree' | 'allowlisted';
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EffectiveTarget {
/// No worktree:
/// outside any repository,
/// or a bare repository.
OutsideWorktree,
/// The repository's main worktree.
MainWorktree,
/// A linked worktree.
LinkedWorktree,
/// A repository under a tool-cache directory exempt from enforcement.
Allowlisted,
}
/// What:
/// Resolve uv's cache directory the way uv does:
/// `UV_CACHE_DIR`,
/// then
/// `XDG_CACHE_HOME/uv`,
/// then `HOME/.cache/uv`;
/// an empty value counts as unset.
/// `Option<&Path>` is "a borrowed home directory or nothing";
/// `Option<PathBuf>` is "an owned path or nothing".
/// Why:
/// uv runs destructive Git inside throwaway clones it owns there.
/// The home
/// directory is injected so tests never read the real one.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function uvCacheDir(environment: [string, string][], home?: string): string | undefined;
/// ```
pub fn uv_cache_dir(environment: &[(OsString, OsString)], home: Option<&Path>) -> Option<PathBuf> {
// `if let Some(x) = ... && cond` runs only when the variable is set and the second
// condition also holds, like `x !== undefined && x !== ""`.
if let Some(explicit) = environment_value(environment, "UV_CACHE_DIR")
&& !explicit.is_empty()
{
// `Some(...)` is the "present" variant.
return Some(PathBuf::from(explicit));
}
if let Some(cache_home) = environment_value(environment, "XDG_CACHE_HOME")
&& !cache_home.is_empty()
{
// `.join` appends one path segment and returns an owned path.
return Some(PathBuf::from(cache_home).join("uv"));
}
// What: `let Some(x) = ... else { return None; };` unwraps the home or exits.
// Why: Without any hint and without a home directory there is no cache to exempt.
//
// In TS you'd write (pseudocode):
// ```ts
// if (home === undefined) return undefined;
// ```
let Some(home_directory) = home else {
// `None` is the "absent" variant.
return None;
};
return Some(home_directory.join(".cache").join("uv"));
}
/// What:
/// The tool-cache directories exempt from worktree enforcement on this machine.
/// `Vec<PathBuf>` is an owned list of owned paths.
/// Why:
/// The set is a property of installed tooling,
/// not of any repository,
/// so it is
/// compiled in rather than configured.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function defaultAllowedWorktreeDirs(environment, home): string[];
/// ```
pub fn default_allowed_worktree_dirs(
environment: &[(OsString, OsString)],
home: Option<&Path>,
) -> Vec<PathBuf> {
// `Vec::<PathBuf>::new()` is an empty owned list; `mut` allows pushing.
let mut directories: Vec<PathBuf> = Vec::<PathBuf>::new();
if let Some(uv) = uv_cache_dir(environment, home) {
directories.push(uv);
}
return directories;
}
/// What:
/// Report whether the canonical `candidate` lies inside any allowed directory.
/// Why:
/// Each allowed directory is resolved through symbolic links first,
/// so a home
/// reached through a link still matches;
/// a directory that does not exist drops
/// out.
/// `Path::starts_with` compares whole segments,
/// so `/a/b` does not contain
/// `/a/bc`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function isAllowedWorktreeDir(candidate: string, allowedDirs: string[]): Promise<boolean>;
/// ```
pub fn is_allowed_worktree_dir(candidate: &Path, allowed_dirs: &[PathBuf]) -> bool {
// `for directory in allowed_dirs` borrows each entry in turn.
for directory in allowed_dirs {
// What: `if let Ok(resolved) = ... && cond` runs only when the directory could be
// resolved and the candidate lies inside it.
// Why: A tool that is not installed has no cache directory to compare with.
//
// In TS you'd write (pseudocode):
// ```ts
// let resolved; try { resolved = await realpath(directory); } catch { continue; }
// ```
if let Ok(resolved) = std::fs::canonicalize(directory)
&& candidate.starts_with(resolved.as_path())
{
return true;
}
}
return false;
}
/// What:
/// Map a repository identity to the target worktree policies act on.
/// Why:
/// Bare and absent repositories have no worktree;
/// a repository whose Git
/// directory sits under an allowed tool cache is exempt before main/linked matters.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// function classifyEffectiveTarget(identity: WorktreeIdentity, allowedDirs: string[]): EffectiveTarget;
/// ```
pub fn classify_effective_target(
identity: &WorktreeIdentity,
allowed_dirs: &[PathBuf],
) -> EffectiveTarget {
// What: `match` on the borrowed identity; `{ git_dir, .. }` binds one field and
// ignores the rest.
// Why: Each shape maps to exactly one target, and the compiler checks none is missed.
//
// In TS you'd write (pseudocode):
// ```ts
// switch (identity.kind) { case 'outside-worktree': return 'outside-worktree'; ... }
// ```
match identity {
WorktreeIdentity::OutsideWorktree | WorktreeIdentity::BareRepository { .. } => {
return EffectiveTarget::OutsideWorktree;
}
WorktreeIdentity::MainWorktree { git_dir, .. } => {
if is_allowed_worktree_dir(git_dir.as_path(), allowed_dirs) {
return EffectiveTarget::Allowlisted;
}
return EffectiveTarget::MainWorktree;
}
WorktreeIdentity::LinkedWorktree { git_dir, .. } => {
if is_allowed_worktree_dir(git_dir.as_path(), allowed_dirs) {
return EffectiveTarget::Allowlisted;
}
return EffectiveTarget::LinkedWorktree;
}
}
}
/// Disposable-directory controls stay out of the release executable.
#[cfg(test)]
#[path = "effective_target_tests.rs"]
mod tests;