agent_chain_core/api/
path.rs1use std::path::{Path, PathBuf};
4
5pub fn get_relative_path<P: AsRef<Path>, B: AsRef<Path>>(
28 file: P,
29 relative_to: B,
30) -> Option<String> {
31 let file = file.as_ref();
32 let base = relative_to.as_ref();
33
34 file.strip_prefix(base)
35 .ok()
36 .map(|p| p.to_string_lossy().into_owned())
37}
38
39pub fn as_import_path<P: AsRef<Path>, B: AsRef<Path>>(
65 file: P,
66 suffix: Option<&str>,
67 relative_to: B,
68) -> Option<String> {
69 let file = file.as_ref();
70 let relative_path = get_relative_path(file, relative_to)?;
71
72 let path = PathBuf::from(&relative_path);
73
74 let without_extension = if path.extension().is_some() {
76 path.with_extension("")
77 } else {
78 path
79 };
80
81 let import_path = without_extension
83 .to_string_lossy()
84 .replace([std::path::MAIN_SEPARATOR, '/', '\\'], "::");
85
86 if let Some(suffix) = suffix {
87 Some(format!("{}::{}", import_path, suffix))
88 } else {
89 Some(import_path)
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96 use std::path::Path;
97
98 #[test]
99 fn test_get_relative_path() {
100 let base = Path::new("/home/user/project");
101 let file = Path::new("/home/user/project/src/main.rs");
102 let relative = get_relative_path(file, base);
103 assert_eq!(relative, Some("src/main.rs".to_string()));
104 }
105
106 #[test]
107 fn test_get_relative_path_same_dir() {
108 let base = Path::new("/home/user/project");
109 let file = Path::new("/home/user/project/main.rs");
110 let relative = get_relative_path(file, base);
111 assert_eq!(relative, Some("main.rs".to_string()));
112 }
113
114 #[test]
115 fn test_get_relative_path_not_relative() {
116 let base = Path::new("/home/user/project");
117 let file = Path::new("/other/path/main.rs");
118 let relative = get_relative_path(file, base);
119 assert_eq!(relative, None);
120 }
121
122 #[test]
123 fn test_as_import_path() {
124 let base = Path::new("/home/user/project/src");
125 let file = Path::new("/home/user/project/src/api/path.rs");
126 let import = as_import_path(file, None, base);
127 assert_eq!(import, Some("api::path".to_string()));
128 }
129
130 #[test]
131 fn test_as_import_path_with_suffix() {
132 let base = Path::new("/home/user/project/src");
133 let file = Path::new("/home/user/project/src/api/path.rs");
134 let import = as_import_path(file, Some("MyStruct"), base);
135 assert_eq!(import, Some("api::path::MyStruct".to_string()));
136 }
137
138 #[test]
139 fn test_as_import_path_directory() {
140 let base = Path::new("/home/user/project/src");
141 let file = Path::new("/home/user/project/src/api");
142 let import = as_import_path(file, None, base);
143 assert_eq!(import, Some("api".to_string()));
144 }
145}