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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::path::PathBuf;
#[cfg(not(windows))]
use std::path::Path;
#[cfg(not(windows))]
use crate::rc;
#[cfg(not(windows))]
use crate::shell::{self, Shell, ShellKind};
use crate::config::Position;
use crate::context::SystemContext;
use crate::error::Error;
use crate::error::Result;
use crate::report::{Action, Report};
/// Builder for configuring and executing PATH management operations.
///
/// Required arguments (`dir` and `tool_name`) are provided in the constructor.
/// Optional settings can be chained before calling [`add`](Self::add) or [`remove`](Self::remove).
///
/// # Example
///
/// ```no_run
/// use onpath::{PathManager, Position};
///
/// let report = PathManager::new("/home/user/.myapp/bin", "myapp")
/// .position(Position::Append)
/// .dry_run(true)
/// .add()?;
/// # Ok::<(), onpath::Error>(())
/// ```
#[must_use]
pub struct PathManager {
dir: PathBuf,
#[cfg(not(windows))]
tool_name: String,
env_dir: Option<PathBuf>,
position: Position,
dry_run: bool,
backup: bool,
allow_relative: bool,
context: Option<SystemContext>,
}
impl PathManager {
/// Create a new `PathManager` for the given directory and tool name.
///
/// - `dir`: The directory to add to or remove from PATH (e.g., `~/.myapp/bin`)
/// - `tool_name`: Unique name for markers and env file naming (e.g., `"myapp"`)
///
/// The env script directory defaults to `dir`'s parent. Override with [`.env_dir()`](Self::env_dir).
#[allow(clippy::needless_pass_by_value)]
pub fn new(dir: impl Into<PathBuf>, tool_name: impl Into<String>) -> Self {
#[cfg(windows)]
let _ = tool_name;
Self {
dir: dir.into(),
#[cfg(not(windows))]
tool_name: tool_name.into(),
env_dir: None,
position: Position::Prepend,
dry_run: false,
backup: true,
allow_relative: false,
context: None,
}
}
/// Override the directory where env scripts are written.
///
/// By default, env scripts are written to `dir.parent()`. Use this if your
/// env scripts should go somewhere else (e.g., `~/.myapp/` when `dir` is `~/.myapp/bin`).
pub fn env_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.env_dir = Some(dir.into());
self
}
/// Whether to prepend or append to PATH. Default: Prepend.
pub fn position(mut self, position: Position) -> Self {
self.position = position;
self
}
/// If true, report what would happen without writing anything.
pub fn dry_run(mut self, dry_run: bool) -> Self {
self.dry_run = dry_run;
self
}
/// If true, backup RC files before modifying. Default: true.
pub fn backup(mut self, backup: bool) -> Self {
self.backup = backup;
self
}
/// Use a custom system context (for testing).
pub fn context(mut self, ctx: SystemContext) -> Self {
self.context = Some(ctx);
self
}
/// If true, allow relative directory paths (default: false).
///
/// Relative paths in PATH resolve relative to the current working directory,
/// which is a security risk ([CWE-427](https://cwe.mitre.org/data/definitions/427.html)).
/// Only enable this if you understand the implications.
pub fn allow_relative(mut self, allow: bool) -> Self {
self.allow_relative = allow;
self
}
/// Validate inputs before performing any operations.
fn validate(&self) -> Result<()> {
// Validate tool_name (Unix only — Windows doesn't use it)
#[cfg(not(windows))]
Self::validate_tool_name(&self.tool_name)?;
// Validate dir is absolute (unless allow_relative is set)
if !self.allow_relative && !self.dir.is_absolute() {
return Err(Error::RelativePath {
dir: self.dir.clone(),
});
}
// Validate dir is valid UTF-8 (shell scripts require text)
if self.dir.to_str().is_none() {
return Err(Error::NonUtf8Path {
dir: self.dir.clone(),
});
}
// Validate dir doesn't contain shell-dangerous characters (Unix only)
#[cfg(not(windows))]
Self::validate_path_safety(&self.dir)?;
Ok(())
}
/// Validate that `tool_name` contains only safe characters.
#[cfg(not(windows))]
fn validate_tool_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::InvalidToolName {
name: name.to_owned(),
reason: "tool name must not be empty".to_owned(),
});
}
if !name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.')
{
return Err(Error::InvalidToolName {
name: name.to_owned(),
reason: "tool name must contain only alphanumeric characters, hyphens, underscores, or dots".to_owned(),
});
}
Ok(())
}
/// Validate that a path doesn't contain characters that would be dangerous
/// when embedded in shell scripts (double quotes, backticks, dollar signs, backslashes).
#[cfg(not(windows))]
fn validate_path_safety(dir: &std::path::Path) -> Result<()> {
if let Some(s) = dir.to_str() {
if s.contains('"') || s.contains('`') || s.contains('$') || s.contains('\\') {
return Err(Error::UnsafePath {
dir: dir.to_owned(),
});
}
}
Ok(())
}
/// Resolve the `env_dir`, falling back to `dir.parent()`.
#[cfg(not(windows))]
fn resolve_env_dir(&self) -> Result<PathBuf> {
match &self.env_dir {
Some(d) => Ok(d.clone()),
None => {
self.dir
.parent()
.map(Path::to_owned)
.ok_or_else(|| Error::EnvDirNotResolvable {
dir: self.dir.clone(),
})
}
}
}
/// Add the directory to PATH across all detected shells.
///
/// # Errors
///
/// Returns [`Error::HomeDirNotFound`] if the home directory cannot be determined,
/// [`Error::EnvDirNotResolvable`] if `dir` has no parent and no env dir was set,
/// [`Error::NoShellsDetected`] if no shells are found on Unix, or
/// [`Error::FileWrite`] / [`Error::DirCreate`] on I/O failures.
/// On Windows, returns `Error::Registry` for registry access failures.
pub fn add(&self) -> Result<Report> {
self.validate()?;
trace_info!(dir = %self.dir.display(), dry_run = self.dry_run, "adding directory to PATH");
let mut report = Report::new(self.dry_run);
self.add_platform(&mut report)?;
Ok(report)
}
/// Remove the directory from PATH across all detected shells.
///
/// # Errors
///
/// Returns [`Error::HomeDirNotFound`] if the home directory cannot be determined,
/// [`Error::EnvDirNotResolvable`] if `dir` has no parent and no env dir was set,
/// or [`Error::FileWrite`] / [`Error::FileRead`] on I/O failures.
/// On Windows, returns `Error::Registry` for registry access failures.
pub fn remove(&self) -> Result<Report> {
self.validate()?;
trace_info!(dir = %self.dir.display(), dry_run = self.dry_run, "removing directory from PATH");
let mut report = Report::new(self.dry_run);
self.remove_platform(&mut report)?;
Ok(report)
}
#[cfg(windows)]
fn add_platform(&self, report: &mut Report) -> Result<()> {
let action = if self.dry_run {
Action::RegistryModified {
old_value: "(dry run)".to_owned(),
new_value: "(dry run)".to_owned(),
}
} else {
crate::windows::add_to_path(&self.dir, self.position)?
};
report.push(action);
Ok(())
}
#[cfg(not(windows))]
fn add_platform(&self, report: &mut Report) -> Result<()> {
let env_dir = self.resolve_env_dir()?;
let ctx = match &self.context {
Some(ctx) => ctx.clone(),
None => SystemContext::detect()?,
};
self.add_unix(&self.dir, &self.tool_name, &env_dir, &ctx, report)
}
#[cfg(windows)]
fn remove_platform(&self, report: &mut Report) -> Result<()> {
let action = if self.dry_run {
Action::RegistryEntryRemoved {
old_value: "(dry run)".to_owned(),
new_value: "(dry run)".to_owned(),
}
} else {
crate::windows::remove_from_path(&self.dir)?
};
report.push(action);
Ok(())
}
#[cfg(not(windows))]
fn remove_platform(&self, report: &mut Report) -> Result<()> {
let env_dir = self.resolve_env_dir()?;
let ctx = match &self.context {
Some(ctx) => ctx.clone(),
None => SystemContext::detect()?,
};
self.remove_unix(&self.tool_name, &env_dir, &ctx, report)
}
#[cfg(not(windows))]
fn add_unix(
&self,
dir: &Path,
tool_name: &str,
env_dir: &Path,
ctx: &SystemContext,
report: &mut Report,
) -> Result<()> {
let shells = shell::detect_shells(ctx);
trace_debug!(count = shells.len(), "detected shells");
if shells.is_empty() {
return Err(Error::NoShellsDetected);
}
for shell in &shells {
trace_debug!(shell = %shell.kind(), "processing shell");
// Special case: Fish uses conf.d, so env script goes there directly
let env_script_path = if shell.kind() == ShellKind::Fish {
crate::shell::fish::conf_d_path(ctx, tool_name)
} else {
env_dir.join(format!("env{}", shell.env_extension()))
};
// Step 1: Write the env script
let env_content = shell.env_script(dir, self.position);
if env_script_path.exists() {
let existing = rc::read_file_or_empty(&env_script_path)?;
if existing == env_content {
report.push(Action::EnvScriptAlreadyExists {
shell: shell.kind(),
path: env_script_path.clone(),
});
} else if !self.dry_run {
rc::write_file(&env_script_path, &env_content)?;
report.push(Action::EnvScriptWritten {
shell: shell.kind(),
path: env_script_path.clone(),
});
}
} else {
if !self.dry_run {
rc::write_file(&env_script_path, &env_content)?;
}
report.push(Action::EnvScriptWritten {
shell: shell.kind(),
path: env_script_path.clone(),
});
}
// Step 2: Add source line to RC files
// Fish conf.d files are auto-loaded, so no source line needed
if shell.kind() == ShellKind::Fish {
continue;
}
let source_line = shell.source_line(&env_script_path);
let rc_files = writable_rc_files(shell.as_ref(), ctx);
if rc_files.is_empty() {
report.push(Action::ShellSkipped {
shell: shell.kind(),
reason: "no RC files found".to_owned(),
});
continue;
}
for rc_file in rc_files {
// Acquire advisory lock to prevent concurrent RC file corruption
let _lock = if self.dry_run {
None
} else {
Some(rc::RcFileLock::acquire(&rc_file)?)
};
let content = rc::read_file_or_empty(&rc_file)?;
match rc::insert_source_block(&content, tool_name, &source_line) {
Some(new_content) => {
if !self.dry_run {
if self.backup && rc_file.exists() {
let backup_path = rc::backup_file(&rc_file)?;
report.push(Action::BackupCreated {
original: rc_file.clone(),
backup: backup_path,
});
}
rc::write_file(&rc_file, &new_content)?;
}
report.push(Action::SourceLineAdded {
shell: shell.kind(),
rc_file,
});
}
None => {
report.push(Action::SourceLineAlreadyPresent {
shell: shell.kind(),
rc_file,
});
}
}
}
}
Ok(())
}
#[cfg(not(windows))]
fn remove_unix(
&self,
tool_name: &str,
env_dir: &Path,
ctx: &SystemContext,
report: &mut Report,
) -> Result<()> {
let shells = shell::detect_shells(ctx);
for shell in &shells {
// Remove env script
let env_script_path = if shell.kind() == ShellKind::Fish {
crate::shell::fish::conf_d_path(ctx, tool_name)
} else {
env_dir.join(format!("env{}", shell.env_extension()))
};
let existed = env_script_path.exists();
if existed && !self.dry_run {
std::fs::remove_file(&env_script_path).map_err(|source| Error::FileWrite {
path: env_script_path.clone(),
source,
})?;
}
if existed || self.dry_run {
report.push(Action::EnvScriptRemoved {
shell: shell.kind(),
path: env_script_path,
});
}
// Remove source lines from RC files (Fish doesn't have source lines)
if shell.kind() == ShellKind::Fish {
continue;
}
let rc_files = writable_rc_files(shell.as_ref(), ctx);
for rc_file in rc_files {
// Acquire advisory lock to prevent concurrent RC file corruption
let _lock = if self.dry_run {
None
} else {
Some(rc::RcFileLock::acquire(&rc_file)?)
};
let content = rc::read_file_or_empty(&rc_file)?;
if let Some(new_content) = rc::remove_source_block(&content, tool_name) {
if !self.dry_run {
if self.backup {
let backup_path = rc::backup_file(&rc_file)?;
report.push(Action::BackupCreated {
original: rc_file.clone(),
backup: backup_path,
});
}
rc::write_file(&rc_file, &new_content)?;
}
report.push(Action::SourceLineRemoved {
shell: shell.kind(),
rc_file,
});
}
}
}
Ok(())
}
}
/// Returns RC files that should actually be modified for a shell.
/// Only returns files that already exist (from `rc_candidates`).
#[cfg(not(windows))]
fn writable_rc_files(shell: &dyn Shell, ctx: &SystemContext) -> Vec<PathBuf> {
let candidates = shell.rc_candidates(ctx);
let existing: Vec<PathBuf> = candidates.into_iter().filter(|p| p.is_file()).collect();
if existing.is_empty() {
// If no RC files exist but this could be the user's shell,
// return the primary RC file so it gets created.
let primary = shell.primary_rc(ctx);
// Only suggest creating if the parent directory exists
if primary.parent().is_some_and(std::path::Path::exists) {
return vec![primary];
}
}
existing
}