1use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use std::collections::HashMap;
34use std::ops::Range;
35use std::path::PathBuf;
36use uuid::Uuid;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct FileRecord {
45 pub id: Uuid,
47 pub path: PathBuf,
49 pub size_bytes: u64,
51 pub mime_type: String,
53 pub content_hash: String,
55 pub modified_at: DateTime<Utc>,
57 pub indexed_at: Option<DateTime<Utc>>,
59 pub chunk_count: u32,
61 pub status: FileStatus,
63 pub error_message: Option<String>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "lowercase")]
70pub enum FileStatus {
71 Pending,
73 Indexing,
75 Indexed,
77 Error,
79 Deleted,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Chunk {
90 pub id: Uuid,
92 pub file_id: Uuid,
94 pub file_path: PathBuf,
96 pub content: String,
98 pub content_type: ContentType,
100 pub mime_type: Option<String>,
102 pub chunk_index: u32,
104 pub byte_range: Range<u64>,
106 pub line_range: Option<Range<u32>>,
108 pub parent_chunk_id: Option<Uuid>,
110 pub depth: u8,
112 pub embedding: Option<Vec<f32>>,
114 pub dir_path: String,
116 pub dir_depth: u16,
118 pub path_components: String,
120 pub metadata: ChunkMetadata,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
129pub struct DirectoryScope {
130 pub dir_path: String,
132 pub dir_depth: u16,
134 pub path_components: String,
136}
137
138impl DirectoryScope {
139 #[must_use]
141 pub fn from_paths(file_path: &std::path::Path, root: Option<&std::path::Path>) -> Self {
142 let rel = root
143 .and_then(|r| file_path.strip_prefix(r).ok())
144 .unwrap_or(file_path);
145 let parts: Vec<String> = rel
146 .components()
147 .filter_map(|c| match c {
148 std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
149 _ => None,
150 })
151 .collect();
152
153 let dir_parts = parts.get(..parts.len().saturating_sub(1)).unwrap_or(&[]);
154 let dir_path = dir_parts.join("/");
155 let dir_depth = dir_parts.len() as u16;
156 let path_components = parts.join(",");
157
158 Self {
159 dir_path,
160 dir_depth,
161 path_components,
162 }
163 }
164
165 #[must_use]
167 pub fn from_file_path(file_path: &std::path::Path) -> Self {
168 Self::from_paths(file_path, None)
169 }
170
171 #[must_use]
173 pub fn normalize_prefix(scope: &str) -> String {
174 scope.replace('\\', "/").trim_matches('/').to_string()
175 }
176
177 #[must_use]
179 pub fn matches_prefix(&self, scope: &str) -> bool {
180 dir_path_matches_scope(&self.dir_path, scope)
181 }
182
183 #[must_use]
185 pub fn infer_root(file_path: &std::path::Path, dir_path: &str) -> Option<std::path::PathBuf> {
186 let parent = file_path.parent()?;
187 let dir = Self::normalize_prefix(dir_path);
188 if dir.is_empty() {
189 return Some(parent.to_path_buf());
190 }
191 let parent_norm = parent.to_string_lossy().replace('\\', "/");
192 parent_norm
193 .strip_suffix(&dir)
194 .map(|root| std::path::PathBuf::from(root.trim_end_matches('/')))
195 }
196}
197
198#[must_use]
207pub fn dir_path_matches_scope(dir_path: &str, scope: &str) -> bool {
208 let scope = DirectoryScope::normalize_prefix(scope);
209 if scope.is_empty() || scope == "." {
210 return true;
211 }
212 let dir = DirectoryScope::normalize_prefix(dir_path);
213 dir == scope
214 || dir.starts_with(&format!("{scope}/"))
215 || dir.ends_with(&format!("/{scope}"))
216 || dir.contains(&format!("/{scope}/"))
217}
218
219#[derive(Debug, Clone, Serialize, Deserialize)]
221#[serde(tag = "type", rename_all = "snake_case")]
222pub enum ContentType {
223 Text,
225 Code {
227 language: String,
229 symbol: Option<CodeSymbol>,
231 },
232 ImageCaption,
234 PdfPage {
236 page_num: u32,
238 },
239 Markdown,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct CodeSymbol {
246 pub kind: SymbolKind,
248 pub name: String,
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "snake_case")]
255pub enum SymbolKind {
256 Function,
257 Method,
258 Class,
259 Struct,
260 Enum,
261 Module,
262 Constant,
263 Variable,
264 Interface,
265 Trait,
266}
267
268#[derive(Debug, Clone, Default, Serialize, Deserialize)]
270pub struct ChunkMetadata {
271 #[serde(default)]
273 pub media: MediaInfo,
274 pub embedding_model: Option<String>,
276 pub indexed_at: Option<DateTime<Utc>>,
278 pub token_count: Option<usize>,
280 #[serde(flatten)]
282 pub extra: HashMap<String, String>,
283}
284
285#[derive(Debug, Clone)]
291pub struct ExtractedContent {
292 pub text: String,
294 pub elements: Vec<ContentElement>,
296 pub images: Vec<ExtractedImage>,
298 pub metadata: ContentMetadataInfo,
300}
301
302#[derive(Debug, Clone)]
304pub enum ContentElement {
305 Heading {
306 level: u8,
307 text: String,
308 byte_offset: u64,
309 },
310 Paragraph {
311 text: String,
312 byte_offset: u64,
313 },
314 CodeBlock {
315 language: Option<String>,
316 code: String,
317 byte_offset: u64,
318 },
319 List {
320 items: Vec<String>,
321 ordered: bool,
322 byte_offset: u64,
323 },
324 Table {
325 headers: Vec<String>,
326 rows: Vec<Vec<String>>,
327 byte_offset: u64,
328 },
329}
330
331#[derive(Debug, Clone)]
333pub struct ExtractedImage {
334 pub data: Vec<u8>,
336 pub mime_type: String,
338 pub caption: Option<String>,
340 pub page: Option<u32>,
342}
343
344#[derive(Debug, Clone, Default)]
346pub struct ContentMetadataInfo {
347 pub title: Option<String>,
349 pub author: Option<String>,
351 pub language: Option<String>,
353 pub page_count: Option<u32>,
355 pub created_at: Option<DateTime<Utc>>,
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize)]
365pub struct ChunkConfig {
366 pub target_size: usize,
368 pub max_size: usize,
370 pub overlap: usize,
372 pub hierarchical: bool,
374 pub max_depth: u8,
376}
377
378impl Default for ChunkConfig {
379 fn default() -> Self {
380 Self {
381 target_size: 512,
382 max_size: 1024,
383 overlap: 64,
384 hierarchical: true,
385 max_depth: 2,
386 }
387 }
388}
389
390#[derive(Debug, Clone)]
392pub struct ChunkOutput {
393 pub content: String,
395 pub byte_range: Range<u64>,
397 pub line_range: Option<Range<u32>>,
399 pub parent_index: Option<usize>,
401 pub depth: u8,
403 pub metadata: ChunkOutputMetadata,
405}
406
407#[derive(Debug, Clone, Default)]
409pub struct ChunkOutputMetadata {
410 pub symbol_type: Option<String>,
412 pub symbol_name: Option<String>,
414 pub language: Option<String>,
416}
417
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
424#[serde(rename_all = "lowercase")]
425pub enum Modality {
426 Text,
427 Image,
428 Audio,
429}
430
431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
434#[serde(default)]
435pub struct MediaInfo {
436 pub modality: String,
437 pub start_ms: Option<u64>,
438 pub end_ms: Option<u64>,
439}
440
441impl Default for MediaInfo {
442 fn default() -> Self {
443 Self {
444 modality: "text".into(),
445 start_ms: None,
446 end_ms: None,
447 }
448 }
449}
450
451impl MediaInfo {
452 pub fn validate(&self) -> std::result::Result<(), String> {
453 if !matches!(self.modality.as_str(), "text" | "image" | "audio" | "video") {
454 return Err("Unsupported source modality".into());
455 }
456 match (self.start_ms, self.end_ms) {
457 (None, None) => Ok(()),
458 (Some(start), Some(end)) if end >= start => Ok(()),
459 _ => Err("Media range requires start_ms <= end_ms, or both null".into()),
460 }
461 }
462
463 pub fn from_metadata(metadata: &HashMap<String, String>) -> std::result::Result<Self, String> {
464 let time = |key: &str| {
465 metadata
466 .get(key)
467 .map(|v| v.parse::<u64>().map_err(|_| format!("Invalid {key}")))
468 .transpose()
469 };
470 let media = Self {
471 modality: metadata
472 .get("modality")
473 .cloned()
474 .unwrap_or_else(|| "text".into()),
475 start_ms: time("start_ms")?,
476 end_ms: time("end_ms")?,
477 };
478 media.validate()?;
479 Ok(media)
480 }
481
482 pub fn write_metadata(&self, metadata: &mut HashMap<String, String>) {
483 metadata.remove("start_ms");
484 metadata.remove("end_ms");
485 metadata.insert("modality".into(), self.modality.clone());
486 if let (Some(start), Some(end)) = (self.start_ms, self.end_ms) {
487 metadata.insert("start_ms".into(), start.to_string());
488 metadata.insert("end_ms".into(), end.to_string());
489 }
490 }
491}
492
493#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct EmbeddingConfig {
496 pub normalize: bool,
498 pub instruction: Option<String>,
500 pub batch_size: usize,
502}
503
504impl Default for EmbeddingConfig {
505 fn default() -> Self {
506 Self {
507 normalize: true,
508 instruction: None,
509 batch_size: 32,
510 }
511 }
512}
513
514#[derive(Debug, Clone)]
516pub struct EmbeddingOutput {
517 pub embedding: Vec<f32>,
519 pub token_count: usize,
521}
522
523#[derive(Debug, Clone)]
529pub struct SearchQuery {
530 pub embedding: Vec<f32>,
532 pub text: Option<String>,
534 pub limit: usize,
536 pub filters: Vec<SearchFilter>,
538 pub metric: DistanceMetric,
540 pub scope_prefix: Option<String>,
545}
546
547#[derive(Debug, Clone)]
549pub enum SearchFilter {
550 PathPrefix(String),
552 PathGlob(String),
554 MimeType(String),
556 Language(String),
558 ModifiedAfter(DateTime<Utc>),
560 ModifiedBefore(DateTime<Utc>),
562 MinDepth(u8),
564 MaxDepth(u8),
566}
567
568#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
570#[serde(rename_all = "lowercase")]
571pub enum DistanceMetric {
572 #[default]
573 Cosine,
574 L2,
575 Dot,
576}
577
578#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct SearchResult {
581 #[serde(default, flatten)]
583 pub media: MediaInfo,
584 pub chunk_id: Uuid,
586 pub file_path: PathBuf,
588 pub content: String,
590 pub score: f32,
592 pub byte_range: Range<u64>,
594 pub line_range: Option<Range<u32>>,
596 pub metadata: HashMap<String, String>,
598}
599
600#[derive(Debug, Clone, Serialize, Deserialize)]
602pub struct StoreStats {
603 pub total_chunks: u64,
605 pub total_files: u64,
607 pub index_size_bytes: u64,
609 pub last_updated: Option<DateTime<Utc>>,
611 #[serde(default)]
615 pub index_revision: u64,
616}
617
618#[derive(Debug, Clone, Default, Serialize, Deserialize)]
624pub struct IndexStats {
625 pub total_files: u64,
627 pub indexed_files: u64,
629 pub pending_files: u64,
631 pub error_files: u64,
633 pub total_chunks: u64,
635 pub last_update: Option<DateTime<Utc>>,
637}
638
639#[derive(Debug, Clone)]
645pub enum FileEvent {
646 Created(PathBuf),
647 Modified(PathBuf),
648 Deleted(PathBuf),
649 Renamed { from: PathBuf, to: PathBuf },
650}
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655
656 #[test]
659 fn test_file_record_serialization() {
660 let record = FileRecord {
661 id: Uuid::new_v4(),
662 path: PathBuf::from("/test/file.txt"),
663 size_bytes: 1024,
664 mime_type: "text/plain".to_string(),
665 content_hash: "abc123".to_string(),
666 modified_at: Utc::now(),
667 indexed_at: Some(Utc::now()),
668 chunk_count: 5,
669 status: FileStatus::Indexed,
670 error_message: None,
671 };
672
673 let json = serde_json::to_string(&record).unwrap();
674 let deserialized: FileRecord = serde_json::from_str(&json).unwrap();
675
676 assert_eq!(record.id, deserialized.id);
677 assert_eq!(record.path, deserialized.path);
678 assert_eq!(record.size_bytes, deserialized.size_bytes);
679 assert_eq!(record.status, deserialized.status);
680 }
681
682 #[test]
683 fn test_file_status_serialization() {
684 assert_eq!(
685 serde_json::to_string(&FileStatus::Pending).unwrap(),
686 "\"pending\""
687 );
688 assert_eq!(
689 serde_json::to_string(&FileStatus::Indexed).unwrap(),
690 "\"indexed\""
691 );
692 assert_eq!(
693 serde_json::to_string(&FileStatus::Error).unwrap(),
694 "\"error\""
695 );
696 }
697
698 #[test]
699 fn test_file_status_equality() {
700 assert_eq!(FileStatus::Pending, FileStatus::Pending);
701 assert_ne!(FileStatus::Pending, FileStatus::Indexed);
702 }
703
704 #[test]
707 fn test_chunk_serialization() {
708 let chunk = Chunk {
709 id: Uuid::new_v4(),
710 file_id: Uuid::new_v4(),
711 file_path: PathBuf::from("/test/file.rs"),
712 content: "fn main() {}".to_string(),
713 content_type: ContentType::Code {
714 language: "rust".to_string(),
715 symbol: Some(CodeSymbol {
716 kind: SymbolKind::Function,
717 name: "main".to_string(),
718 }),
719 },
720 mime_type: Some("text/x-rust".to_string()),
721 chunk_index: 0,
722 byte_range: 0..12,
723 line_range: Some(0..1),
724 parent_chunk_id: None,
725 depth: 0,
726 embedding: None,
727 dir_path: "test".to_string(),
728 dir_depth: 1,
729 path_components: "test,file.rs".to_string(),
730 metadata: ChunkMetadata::default(),
731 };
732
733 let json = serde_json::to_string(&chunk).unwrap();
734 let deserialized: Chunk = serde_json::from_str(&json).unwrap();
735
736 assert_eq!(chunk.id, deserialized.id);
737 assert_eq!(chunk.content, deserialized.content);
738 }
739
740 #[test]
741 fn test_content_type_text() {
742 let ct = ContentType::Text;
743 let json = serde_json::to_string(&ct).unwrap();
744 assert!(json.contains("\"type\":\"text\""));
745 }
746
747 #[test]
748 fn test_content_type_code() {
749 let ct = ContentType::Code {
750 language: "python".to_string(),
751 symbol: None,
752 };
753 let json = serde_json::to_string(&ct).unwrap();
754 assert!(json.contains("\"type\":\"code\""));
755 assert!(json.contains("\"language\":\"python\""));
756 }
757
758 #[test]
759 fn test_content_type_pdf_page() {
760 let ct = ContentType::PdfPage { page_num: 5 };
761 let json = serde_json::to_string(&ct).unwrap();
762 assert!(json.contains("\"type\":\"pdf_page\""));
763 assert!(json.contains("\"page_num\":5"));
764 }
765
766 #[test]
767 fn test_content_type_markdown() {
768 let ct = ContentType::Markdown;
769 let json = serde_json::to_string(&ct).unwrap();
770 assert!(json.contains("\"type\":\"markdown\""));
771 }
772
773 #[test]
774 fn test_symbol_kind_serialization() {
775 assert_eq!(
776 serde_json::to_string(&SymbolKind::Function).unwrap(),
777 "\"function\""
778 );
779 assert_eq!(
780 serde_json::to_string(&SymbolKind::Struct).unwrap(),
781 "\"struct\""
782 );
783 assert_eq!(
784 serde_json::to_string(&SymbolKind::Trait).unwrap(),
785 "\"trait\""
786 );
787 }
788
789 #[test]
792 fn test_chunk_config_default() {
793 let config = ChunkConfig::default();
794 assert_eq!(config.target_size, 512);
795 assert_eq!(config.max_size, 1024);
796 assert_eq!(config.overlap, 64);
797 assert!(config.hierarchical);
798 assert_eq!(config.max_depth, 2);
799 }
800
801 #[test]
802 fn test_chunk_config_serialization() {
803 let config = ChunkConfig::default();
804 let json = serde_json::to_string(&config).unwrap();
805 let deserialized: ChunkConfig = serde_json::from_str(&json).unwrap();
806
807 assert_eq!(config.target_size, deserialized.target_size);
808 assert_eq!(config.max_size, deserialized.max_size);
809 }
810
811 #[test]
814 fn test_embedding_config_default() {
815 let config = EmbeddingConfig::default();
816 assert!(config.normalize);
817 assert!(config.instruction.is_none());
818 assert_eq!(config.batch_size, 32);
819 }
820
821 #[test]
822 fn test_embedding_config_serialization() {
823 let config = EmbeddingConfig {
824 normalize: false,
825 instruction: Some("Search: ".to_string()),
826 batch_size: 16,
827 };
828 let json = serde_json::to_string(&config).unwrap();
829 let deserialized: EmbeddingConfig = serde_json::from_str(&json).unwrap();
830
831 assert_eq!(config.normalize, deserialized.normalize);
832 assert_eq!(config.instruction, deserialized.instruction);
833 assert_eq!(config.batch_size, deserialized.batch_size);
834 }
835
836 #[test]
839 fn test_modality_serialization() {
840 assert_eq!(serde_json::to_string(&Modality::Text).unwrap(), "\"text\"");
841 assert_eq!(
842 serde_json::to_string(&Modality::Image).unwrap(),
843 "\"image\""
844 );
845 assert_eq!(
846 serde_json::to_string(&Modality::Audio).unwrap(),
847 "\"audio\""
848 );
849 }
850
851 #[test]
852 fn test_modality_equality() {
853 assert_eq!(Modality::Text, Modality::Text);
854 assert_ne!(Modality::Text, Modality::Image);
855 }
856
857 #[test]
860 fn test_distance_metric_default() {
861 let metric = DistanceMetric::default();
862 assert_eq!(metric, DistanceMetric::Cosine);
863 }
864
865 #[test]
866 fn test_distance_metric_serialization() {
867 assert_eq!(
868 serde_json::to_string(&DistanceMetric::Cosine).unwrap(),
869 "\"cosine\""
870 );
871 assert_eq!(
872 serde_json::to_string(&DistanceMetric::L2).unwrap(),
873 "\"l2\""
874 );
875 assert_eq!(
876 serde_json::to_string(&DistanceMetric::Dot).unwrap(),
877 "\"dot\""
878 );
879 }
880
881 #[test]
884 fn test_search_result_serialization() {
885 let result = SearchResult {
886 media: Default::default(),
887 chunk_id: Uuid::new_v4(),
888 file_path: PathBuf::from("/test/file.txt"),
889 content: "Test content".to_string(),
890 score: 0.95,
891 byte_range: 0..12,
892 line_range: Some(0..1),
893 metadata: HashMap::new(),
894 };
895
896 let json = serde_json::to_string(&result).unwrap();
897 let deserialized: SearchResult = serde_json::from_str(&json).unwrap();
898
899 assert_eq!(result.chunk_id, deserialized.chunk_id);
900 assert_eq!(result.score, deserialized.score);
901 assert_eq!(result.content, deserialized.content);
902 }
903
904 #[test]
907 fn test_store_stats_serialization() {
908 let stats = StoreStats {
909 total_chunks: 100,
910 total_files: 10,
911 index_size_bytes: 1024 * 1024,
912 last_updated: Some(Utc::now()),
913 index_revision: 4,
914 };
915
916 let json = serde_json::to_string(&stats).unwrap();
917 let deserialized: StoreStats = serde_json::from_str(&json).unwrap();
918
919 assert_eq!(stats.total_chunks, deserialized.total_chunks);
920 assert_eq!(stats.total_files, deserialized.total_files);
921 assert_eq!(stats.index_revision, deserialized.index_revision);
922 }
923
924 #[test]
925 fn old_store_stats_json_defaults_revision() {
926 let deserialized: StoreStats = serde_json::from_str(
927 r#"{"total_chunks":1,"total_files":1,"index_size_bytes":0,"last_updated":null}"#,
928 )
929 .unwrap();
930 assert_eq!(deserialized.index_revision, 0);
931 }
932
933 #[test]
936 fn test_index_stats_default() {
937 let stats = IndexStats::default();
938 assert_eq!(stats.total_files, 0);
939 assert_eq!(stats.indexed_files, 0);
940 assert_eq!(stats.pending_files, 0);
941 assert_eq!(stats.error_files, 0);
942 assert_eq!(stats.total_chunks, 0);
943 assert!(stats.last_update.is_none());
944 }
945
946 #[test]
947 fn test_index_stats_serialization() {
948 let stats = IndexStats {
949 total_files: 50,
950 indexed_files: 45,
951 pending_files: 3,
952 error_files: 2,
953 total_chunks: 500,
954 last_update: Some(Utc::now()),
955 };
956
957 let json = serde_json::to_string(&stats).unwrap();
958 let deserialized: IndexStats = serde_json::from_str(&json).unwrap();
959
960 assert_eq!(stats.total_files, deserialized.total_files);
961 assert_eq!(stats.indexed_files, deserialized.indexed_files);
962 }
963
964 #[test]
967 fn test_chunk_metadata_default() {
968 let meta = ChunkMetadata::default();
969 assert!(meta.embedding_model.is_none());
970 assert!(meta.indexed_at.is_none());
971 assert!(meta.token_count.is_none());
972 assert!(meta.extra.is_empty());
973 }
974
975 #[test]
978 fn test_chunk_output_metadata_default() {
979 let meta = ChunkOutputMetadata::default();
980 assert!(meta.symbol_type.is_none());
981 assert!(meta.symbol_name.is_none());
982 assert!(meta.language.is_none());
983 }
984
985 #[test]
988 fn test_content_metadata_info_default() {
989 let meta = ContentMetadataInfo::default();
990 assert!(meta.title.is_none());
991 assert!(meta.author.is_none());
992 assert!(meta.language.is_none());
993 assert!(meta.page_count.is_none());
994 assert!(meta.created_at.is_none());
995 }
996
997 #[test]
1000 fn test_directory_scope_is_relative_to_root() {
1001 let root = PathBuf::from("/project");
1002 let file = PathBuf::from("/project/src/auth/login.rs");
1003 let scope = DirectoryScope::from_paths(&file, Some(&root));
1004
1005 assert_eq!(scope.dir_path, "src/auth");
1006 assert_eq!(scope.dir_depth, 2);
1007 assert_eq!(scope.path_components, "src,auth,login.rs");
1008 }
1009
1010 #[test]
1011 fn test_directory_scope_index_root_file() {
1012 let root = PathBuf::from("/project");
1013 let file = PathBuf::from("/project/README.md");
1014 let scope = DirectoryScope::from_paths(&file, Some(&root));
1015
1016 assert_eq!(scope.dir_path, "");
1017 assert_eq!(scope.dir_depth, 0);
1018 assert_eq!(scope.path_components, "README.md");
1019 }
1020
1021 #[test]
1022 fn test_directory_scope_without_root_strips_only_prefix_components() {
1023 let file = PathBuf::from("/test/file.rs");
1024 let scope = DirectoryScope::from_file_path(&file);
1025 assert_eq!(scope.dir_path, "test");
1026 assert_eq!(scope.path_components, "test,file.rs");
1027 }
1028
1029 #[test]
1030 fn test_dir_path_matches_scope_exact_and_subdirectory() {
1031 assert!(dir_path_matches_scope("src/auth", "src/auth"));
1032 assert!(dir_path_matches_scope("src/auth/oauth", "src/auth"));
1033 assert!(dir_path_matches_scope("src/auth", "src/auth/"));
1034 assert!(!dir_path_matches_scope("src/other", "src/auth"));
1035 assert!(!dir_path_matches_scope("src/auth-backup", "src/auth"));
1036 assert!(dir_path_matches_scope("src", ""));
1037 assert!(dir_path_matches_scope("src", "."));
1038 }
1039
1040 #[test]
1041 fn test_dir_path_matches_scope_migrated_absolute_suffix() {
1042 assert!(dir_path_matches_scope("project/src/auth", "src/auth"));
1044 assert!(dir_path_matches_scope("project/src/auth/oauth", "src/auth"));
1045 assert!(dir_path_matches_scope("project/src", "src"));
1046 assert!(dir_path_matches_scope("project/src/auth", "src"));
1047 assert!(!dir_path_matches_scope("project/src-backup", "src"));
1048 assert!(!dir_path_matches_scope("project/other", "src/auth"));
1049 assert!(!dir_path_matches_scope("project/author/notes", "auth"));
1050 }
1051
1052 #[test]
1055 fn test_file_event_created() {
1056 let event = FileEvent::Created(PathBuf::from("/test/new.txt"));
1057 match event {
1058 FileEvent::Created(path) => assert_eq!(path, PathBuf::from("/test/new.txt")),
1059 _ => panic!("Expected Created event"),
1060 }
1061 }
1062
1063 #[test]
1064 fn test_file_event_modified() {
1065 let event = FileEvent::Modified(PathBuf::from("/test/changed.txt"));
1066 match event {
1067 FileEvent::Modified(path) => assert_eq!(path, PathBuf::from("/test/changed.txt")),
1068 _ => panic!("Expected Modified event"),
1069 }
1070 }
1071
1072 #[test]
1073 fn test_file_event_deleted() {
1074 let event = FileEvent::Deleted(PathBuf::from("/test/removed.txt"));
1075 match event {
1076 FileEvent::Deleted(path) => assert_eq!(path, PathBuf::from("/test/removed.txt")),
1077 _ => panic!("Expected Deleted event"),
1078 }
1079 }
1080
1081 #[test]
1082 fn test_file_event_renamed() {
1083 let event = FileEvent::Renamed {
1084 from: PathBuf::from("/test/old.txt"),
1085 to: PathBuf::from("/test/new.txt"),
1086 };
1087 match event {
1088 FileEvent::Renamed { from, to } => {
1089 assert_eq!(from, PathBuf::from("/test/old.txt"));
1090 assert_eq!(to, PathBuf::from("/test/new.txt"));
1091 }
1092 _ => panic!("Expected Renamed event"),
1093 }
1094 }
1095}
1096
1097#[cfg(test)]
1098mod media_tests {
1099 use super::*;
1100 #[test]
1101 fn legacy_media_defaults_and_ranges_are_validated() {
1102 assert_eq!(
1103 serde_json::from_str::<MediaInfo>("{}").unwrap(),
1104 MediaInfo::default()
1105 );
1106 let mut metadata = HashMap::from([
1107 ("modality".into(), "audio".into()),
1108 ("start_ms".into(), "10".into()),
1109 ("end_ms".into(), "20".into()),
1110 ]);
1111 let media = MediaInfo::from_metadata(&metadata).unwrap();
1112 assert_eq!(media.start_ms, Some(10));
1113 metadata.insert("end_ms".into(), "9".into());
1114 assert!(MediaInfo::from_metadata(&metadata).is_err());
1115 metadata.remove("end_ms");
1116 assert!(MediaInfo::from_metadata(&metadata).is_err());
1117 MediaInfo::default().write_metadata(&mut metadata);
1118 assert_eq!(
1119 MediaInfo::from_metadata(&metadata).unwrap(),
1120 MediaInfo::default()
1121 );
1122 }
1123}