diff --git a/NEX_AGENT_DELIVERABLE.md b/NEX_AGENT_DELIVERABLE.md new file mode 100644 index 0000000..0fbc7d7 --- /dev/null +++ b/NEX_AGENT_DELIVERABLE.md @@ -0,0 +1,7 @@ +# Deliverable for issue #19 + +GitHub issue with bounty label — auto-submit via PR (fork + branch + PR to upstream) + +## Code + +See `github-19.rs`. diff --git a/github-19.rs b/github-19.rs new file mode 100644 index 0000000..414588e --- /dev/null +++ b/github-19.rs @@ -0,0 +1,56 @@ +use std::path::{Path, PathBuf}; + +pub fn strip_prefix>(path: P, prefix: P) -> Option { + let path = path.as_ref(); + let prefix = prefix.as_ref(); + + if path.starts_with(prefix) { + Some(path.strip_prefix(prefix).unwrap().to_path_buf()) + } else { + None + } +} + +pub fn remap(path: P, prefix: P, mapper: F) -> Option +where + P: AsRef, + F: FnOnce(&Path) -> PathBuf, +{ + let path = path.as_ref(); + let prefix = prefix.as_ref(); + + if path.starts_with(prefix) { + let stripped = path.strip_prefix(prefix).unwrap(); + Some(mapper(stripped)) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + #[test] + fn test_strip_prefix() { + assert_eq!( + strip_prefix("/home/user/file.txt", "/home/user"), + Some(Path::new("file.txt").to_path_buf()) + ); + assert_eq!(strip_prefix("/home/user/file.txt", "/wrong"), None); + } + + #[test] + fn test_remap() { + let result = remap( + "/home/user/file.txt", + "/home/user", + |p| Path::new("mapped").join(p) + ); + assert_eq!(result, Some(Path::new("mapped").join("file.txt").to_path_buf())); + + let result = remap("/home/user/file.txt", "/wrong", |_| PathBuf::new()); + assert_eq!(result, None); + } +} \ No newline at end of file