onpath 0.2.0

Get your tools on the PATH — cross-shell, cross-platform, zero fuss
Documentation
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
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};

/// Timeout in seconds for acquiring an RC file lock.
#[cfg(unix)]
const LOCK_TIMEOUT_SECS: u64 = 10;

/// RAII guard for an advisory file lock on Unix.
///
/// Uses `flock(2)` to serialize concurrent read-modify-write operations
/// on RC files. The lock is automatically released when dropped.
#[cfg(unix)]
pub(crate) struct RcFileLock {
    file: fs::File,
}

#[cfg(unix)]
impl RcFileLock {
    /// Acquire an exclusive lock on the given RC file.
    ///
    /// Creates a `.onpath.lock` lockfile next to the target file.
    /// Blocks up to [`LOCK_TIMEOUT_SECS`] seconds before returning an error.
    pub fn acquire(rc_path: &Path) -> Result<Self> {
        use std::os::unix::io::AsRawFd;
        use std::time::{Duration, Instant};

        let lock_path = lock_path_for(rc_path);

        // Ensure parent directory exists
        if let Some(parent) = lock_path.parent() {
            fs::create_dir_all(parent).map_err(|source| Error::DirCreate {
                path: parent.to_owned(),
                source,
            })?;
        }

        let file = fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .map_err(|source| Error::LockFailed {
                path: lock_path.clone(),
                source,
            })?;

        let timeout = Duration::from_secs(LOCK_TIMEOUT_SECS);
        let start = Instant::now();
        let fd = file.as_raw_fd();

        loop {
            // SAFETY: flock is a standard POSIX syscall. fd is a valid file descriptor
            // from an open File. LOCK_EX|LOCK_NB requests a non-blocking exclusive lock.
            #[allow(unsafe_code)]
            let result = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };

            if result == 0 {
                return Ok(Self { file });
            }

            let err = std::io::Error::last_os_error();
            if err.kind() != std::io::ErrorKind::WouldBlock {
                return Err(Error::LockFailed {
                    path: lock_path,
                    source: err,
                });
            }

            if start.elapsed() >= timeout {
                return Err(Error::LockTimeout { path: lock_path });
            }

            std::thread::sleep(Duration::from_millis(50));
        }
    }
}

#[cfg(unix)]
impl Drop for RcFileLock {
    fn drop(&mut self) {
        use std::os::unix::io::AsRawFd;

        // SAFETY: fd is a valid file descriptor from our open File.
        // LOCK_UN releases the advisory lock.
        #[allow(unsafe_code)]
        unsafe {
            libc::flock(self.file.as_raw_fd(), libc::LOCK_UN);
        }
    }
}

/// Returns the lockfile path for a given RC file.
#[cfg(unix)]
fn lock_path_for(rc_path: &Path) -> PathBuf {
    let mut lock_name = rc_path
        .file_name()
        .map(std::ffi::OsStr::to_os_string)
        .unwrap_or_default();
    lock_name.push(".onpath.lock");
    rc_path.with_file_name(lock_name)
}

/// Opening marker for a source block in an RC file.
fn open_marker(tool_name: &str) -> String {
    format!("# >>> onpath:{tool_name} >>>")
}

/// Closing marker for a source block in an RC file.
fn close_marker(tool_name: &str) -> String {
    format!("# <<< onpath:{tool_name} <<<")
}

/// Check if an RC file already contains the onpath block for the given tool.
pub fn has_source_block(rc_content: &str, tool_name: &str) -> bool {
    rc_content.contains(&open_marker(tool_name))
}

/// Build the full block to insert into an RC file.
pub fn build_source_block(tool_name: &str, source_line: &str) -> String {
    format!(
        "{}\n{}\n{}\n",
        open_marker(tool_name),
        source_line,
        close_marker(tool_name),
    )
}

/// Insert a source block into an RC file's content. Returns `None` if already present.
pub fn insert_source_block(rc_content: &str, tool_name: &str, source_line: &str) -> Option<String> {
    if has_source_block(rc_content, tool_name) {
        return None;
    }

    let block = build_source_block(tool_name, source_line);

    // Ensure the file ends with a newline before appending
    let mut result = rc_content.to_owned();
    if !result.is_empty() && !result.ends_with('\n') {
        result.push('\n');
    }
    result.push_str(&block);
    Some(result)
}

/// Remove the source block for the given tool from RC file content. Returns `None` if not found.
pub fn remove_source_block(rc_content: &str, tool_name: &str) -> Option<String> {
    let open = open_marker(tool_name);
    let close = close_marker(tool_name);

    let start = rc_content.find(&open)?;
    let close_pos = rc_content[start..].find(&close)?;
    let end = start + close_pos + close.len();

    // Also remove the trailing newline after the close marker
    let end = if rc_content.as_bytes().get(end) == Some(&b'\n') {
        end + 1
    } else {
        end
    };

    let mut result = String::with_capacity(rc_content.len());
    result.push_str(&rc_content[..start]);
    result.push_str(&rc_content[end..]);

    // Remove trailing empty lines that may be left behind
    while result.ends_with("\n\n") {
        result.pop();
    }

    Some(result)
}

/// Create a backup of a file. Returns the backup path.
///
/// If a backup already exists, it is preserved (not overwritten).
/// This ensures the original pre-modification state is always recoverable,
/// even after multiple `add()` calls.
pub fn backup_file(path: &Path) -> Result<PathBuf> {
    let backup_path = path.with_extension("onpath.bak");
    if backup_path.exists() {
        // Preserve the existing backup (original state is more valuable)
        return Ok(backup_path);
    }
    fs::copy(path, &backup_path).map_err(|source| Error::BackupFailed {
        path: path.to_owned(),
        source,
    })?;
    Ok(backup_path)
}

/// Read a file, returning an empty string if it doesn't exist.
pub fn read_file_or_empty(path: &Path) -> Result<String> {
    match fs::read_to_string(path) {
        Ok(content) => Ok(content),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(source) => Err(Error::FileRead {
            path: path.to_owned(),
            source,
        }),
    }
}

/// Write content to a file, creating parent directories if needed.
pub fn write_file(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| Error::DirCreate {
            path: parent.to_owned(),
            source,
        })?;
    }
    fs::write(path, content).map_err(|source| Error::FileWrite {
        path: path.to_owned(),
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn has_source_block_detects_existing() {
        let content = "# existing\n# >>> onpath:myapp >>>\n. /path/env\n# <<< onpath:myapp <<<\n";
        assert!(has_source_block(content, "myapp"));
        assert!(!has_source_block(content, "other"));
    }

    #[test]
    fn build_source_block_format() {
        let block = build_source_block("myapp", ". \"/home/user/.myapp/env\"");
        assert_eq!(
            block,
            "# >>> onpath:myapp >>>\n. \"/home/user/.myapp/env\"\n# <<< onpath:myapp <<<\n"
        );
    }

    #[test]
    fn insert_source_block_appends() {
        let content = "# existing config\n";
        let result = insert_source_block(content, "myapp", ". /path/env");
        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.starts_with("# existing config\n"));
        assert!(result.contains("# >>> onpath:myapp >>>"));
        assert!(result.contains(". /path/env"));
        assert!(result.contains("# <<< onpath:myapp <<<"));
    }

    #[test]
    fn insert_source_block_idempotent() {
        let content = "# >>> onpath:myapp >>>\n. /path/env\n# <<< onpath:myapp <<<\n";
        let result = insert_source_block(content, "myapp", ". /path/env");
        assert!(result.is_none());
    }

    #[test]
    fn insert_adds_newline_if_missing() {
        let content = "# existing config";
        let result = insert_source_block(content, "myapp", ". /path/env").unwrap();
        assert!(result.starts_with("# existing config\n"));
    }

    #[test]
    fn insert_handles_empty_file() {
        let result = insert_source_block("", "myapp", ". /path/env").unwrap();
        assert!(result.starts_with("# >>> onpath:myapp >>>"));
    }

    #[test]
    fn remove_source_block_removes_cleanly() {
        let content =
            "before\n# >>> onpath:myapp >>>\n. /path/env\n# <<< onpath:myapp <<<\nafter\n";
        let result = remove_source_block(content, "myapp").unwrap();
        assert_eq!(result, "before\nafter\n");
    }

    #[test]
    fn remove_source_block_returns_none_when_missing() {
        let content = "just normal config\n";
        assert!(remove_source_block(content, "myapp").is_none());
    }

    #[test]
    fn remove_source_block_handles_end_of_file() {
        let content = "before\n# >>> onpath:myapp >>>\n. /path/env\n# <<< onpath:myapp <<<\n";
        let result = remove_source_block(content, "myapp").unwrap();
        assert_eq!(result, "before\n");
    }

    #[test]
    fn multiple_tools_dont_interfere() {
        let content = "";
        let content = insert_source_block(content, "tool_a", ". /a/env").unwrap();
        let content = insert_source_block(&content, "tool_b", ". /b/env").unwrap();

        assert!(has_source_block(&content, "tool_a"));
        assert!(has_source_block(&content, "tool_b"));

        let content = remove_source_block(&content, "tool_a").unwrap();
        assert!(!has_source_block(&content, "tool_a"));
        assert!(has_source_block(&content, "tool_b"));
    }

    #[test]
    fn backup_and_read_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.rc");
        std::fs::write(&path, "content").unwrap();

        let backup_path = backup_file(&path).unwrap();
        assert!(backup_path.exists());
        assert_eq!(std::fs::read_to_string(&backup_path).unwrap(), "content");
    }

    #[test]
    fn read_file_or_empty_returns_empty_for_missing() {
        let result = read_file_or_empty(Path::new("/nonexistent/path")).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn remove_source_block_crlf() {
        let content = "before\r\n# >>> onpath:myapp >>>\r\n. /path/env\r\n# <<< onpath:myapp <<<\r\nafter\r\n";
        let result = remove_source_block(content, "myapp").unwrap();
        assert!(!result.contains("onpath:myapp"));
        assert!(result.contains("before"));
        assert!(result.contains("after"));
    }

    #[test]
    fn insert_into_file_with_bom() {
        let bom = "\u{FEFF}";
        let content = format!("{bom}# existing config\n");
        let result = insert_source_block(&content, "myapp", ". /path/env").unwrap();
        assert!(result.starts_with(bom));
        assert!(result.contains("# >>> onpath:myapp >>>"));
    }

    #[test]
    fn insert_into_file_without_trailing_newline() {
        let content = "# config without newline";
        let result = insert_source_block(content, "myapp", ". /path/env").unwrap();
        // Should add newline before marker block
        assert!(result.contains("# config without newline\n# >>> onpath:myapp >>>"));
    }

    #[test]
    fn crlf_insert_remove_roundtrip() {
        let original = "# my config\r\nexport FOO=bar\r\n";
        let inserted = insert_source_block(original, "myapp", ". /path/env").unwrap();

        assert!(inserted.contains("# >>> onpath:myapp >>>"));
        assert!(inserted.starts_with("# my config\r\n"));

        let removed = remove_source_block(&inserted, "myapp").unwrap();
        assert!(!removed.contains("onpath:myapp"));
        assert!(removed.contains("FOO=bar"));
    }

    #[test]
    fn bom_insert_remove_roundtrip() {
        let bom = "\u{FEFF}";
        let original = format!("{bom}# config\nexport BAR=baz\n");

        let inserted = insert_source_block(&original, "myapp", ". /path/env").unwrap();
        assert!(inserted.starts_with(bom));
        assert!(inserted.contains("# >>> onpath:myapp >>>"));

        let removed = remove_source_block(&inserted, "myapp").unwrap();
        assert!(removed.starts_with(bom));
        assert!(!removed.contains("onpath:myapp"));
        assert!(removed.contains("BAR=baz"));
    }

    #[test]
    fn backup_preserves_existing_backup() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.rc");
        fs::write(&path, "original content").unwrap();

        // Create first backup
        let backup_path = backup_file(&path).unwrap();
        assert_eq!(
            fs::read_to_string(&backup_path).unwrap(),
            "original content"
        );

        // Modify the file
        fs::write(&path, "modified content").unwrap();

        // Second backup should NOT overwrite — original is preserved
        let backup_path2 = backup_file(&path).unwrap();
        assert_eq!(backup_path, backup_path2);
        assert_eq!(
            fs::read_to_string(&backup_path).unwrap(),
            "original content",
            "backup should preserve original, not overwrite with modified"
        );
    }

    #[cfg(unix)]
    #[test]
    fn backup_follows_symlinks() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("actual.rc");
        let link = dir.path().join("link.rc");
        fs::write(&target, "symlinked content").unwrap();
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let backup_path = backup_file(&link).unwrap();
        assert!(backup_path.exists());
        // Backup contains the content from the symlink target
        assert_eq!(
            fs::read_to_string(&backup_path).unwrap(),
            "symlinked content"
        );
        // Original symlink is still intact
        assert!(link.is_symlink());
    }

    #[test]
    fn write_file_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let deep_path = dir.path().join("a").join("b").join("c").join("test.rc");
        write_file(&deep_path, "test content").unwrap();
        assert_eq!(std::fs::read_to_string(&deep_path).unwrap(), "test content");
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Insert then remove a source block — the content should be restored.
        #[test]
        fn rc_insert_remove_roundtrip(
            content in "[a-zA-Z0-9 \n#=]{0,500}",
            tool in "[a-z]{3,10}",
            source_line in r#"[a-zA-Z0-9/."\- ]{5,80}"#,
        ) {
            let inserted = insert_source_block(&content, &tool, &source_line);
            // If insertion happened (wasn't already present), removal should restore
            if let Some(new_content) = inserted {
                let removed = remove_source_block(&new_content, &tool);
                prop_assert!(removed.is_some(), "remove should find what insert added");
                let restored = removed.unwrap();
                // The restored content should equal the original (modulo trailing whitespace normalization)
                prop_assert_eq!(restored.trim_end(), content.trim_end());
            }
        }
    }
}