diff options
| author | sigoden <sigoden@gmail.com> | 2024-06-27 07:51:30 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-06-27 07:51:30 +0800 |
| commit | 1ced451c2723c36b7e0cb70e6c0755cdbad457c3 (patch) | |
| tree | ea994b6bf4a6ba0f209129419a54e04679c88562 /src/utils/mod.rs | |
| parent | f60df039979b8642aa82fec9e6ce56acb3a80f50 (diff) | |
| download | aichat-1ced451c2723c36b7e0cb70e6c0755cdbad457c3.tar.gz | |
refactor: agent rag use `documents` field other than `embeddings` dir (#658)
Diffstat (limited to 'src/utils/mod.rs')
| -rw-r--r-- | src/utils/mod.rs | 53 |
1 files changed, 52 insertions, 1 deletions
diff --git a/src/utils/mod.rs b/src/utils/mod.rs index f8bfcc6..7d1d07a 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -17,7 +17,10 @@ pub use self::spinner::{create_spinner, Spinner}; use fancy_regex::Regex; use is_terminal::IsTerminal; use lazy_static::lazy_static; -use std::env; +use std::{ + env, + path::{self, Path, PathBuf}, +}; lazy_static! { pub static ref CODE_BLOCK_RE: Regex = Regex::new(r"(?ms)```\w*(.*)```").unwrap(); @@ -151,6 +154,32 @@ pub fn dimmed_text(input: &str) -> String { nu_ansi_term::Style::new().dimmed().paint(input).to_string() } +pub fn safe_join_path<T1: AsRef<Path>, T2: AsRef<Path>>( + base_path: T1, + sub_path: T2, +) -> Option<PathBuf> { + let base_path = base_path.as_ref(); + let sub_path = sub_path.as_ref(); + if sub_path.is_absolute() { + return None; + } + + let mut joined_path = PathBuf::from(base_path); + + for component in sub_path.components() { + if path::Component::ParentDir == component { + return None; + } + joined_path.push(component); + } + + if joined_path.starts_with(base_path) { + Some(joined_path) + } else { + None + } +} + #[cfg(test)] mod tests { use super::*; @@ -161,4 +190,26 @@ mod tests { assert!(fuzzy_match("openai:gpt-4-turbo", "oai4")); assert!(!fuzzy_match("openai:gpt-4-turbo", "4gpt")); } + + #[test] + #[cfg(not(target_os = "windows"))] + fn test_safe_join_path() { + assert_eq!( + safe_join_path("/home/user/dir1", "files/file1"), + Some(PathBuf::from("/home/user/dir1/files/file1")) + ); + assert!(safe_join_path("/home/user/dir1", "/files/file1").is_none()); + assert!(safe_join_path("/home/user/dir1", "../file1").is_none()); + } + + #[test] + #[cfg(target_os = "windows")] + fn test_safe_join_path() { + assert_eq!( + safe_join_path("C:\\Users\\user\\dir1", "files/file1"), + Some(PathBuf::from("C:\\Users\\user\\dir1\\files\\file1")) + ); + assert!(safe_join_path("C:\\Users\\user\\dir1", "/files/file1").is_none()); + assert!(safe_join_path("C:\\Users\\user\\dir1", "../file1").is_none()); + } } |
