1use crate::keri::core::errors::CoreError;
2use std::fs::{self, File, OpenOptions};
3use std::io;
4use std::os::unix::fs::PermissionsExt;
5use std::path::{Path, PathBuf};
6use tempfile::Builder;
7
8pub struct BaseFiler {
13 name: String,
15
16 base: String,
18
19 temp: bool,
21
22 head_dir_path: PathBuf,
24
25 path: Option<PathBuf>,
27
28 perm: u32,
30
31 filed: bool,
33
34 extensioned: bool,
36
37 mode: String,
39
40 fext: String,
42
43 file: Option<File>,
45
46 opened: bool,
48
49 defaults: FilerDefaults,
50}
51
52#[allow(dead_code)]
53impl BaseFiler {
54 pub fn name(&self) -> String {
55 self.name.clone()
56 }
57
58 pub fn base(&self) -> String {
59 self.base.clone()
60 }
61
62 pub fn path(&self) -> Option<PathBuf> {
63 self.path.clone()
64 }
65
66 pub fn temp(&self) -> bool {
67 self.temp
68 }
69
70 pub fn filed(&self) -> bool {
71 self.filed
72 }
73
74 pub fn opened(&self) -> bool {
75 self.opened
76 }
77
78 pub(crate) fn set_opened(&mut self, opened: bool) {
79 self.opened = opened;
80 }
81
82 pub fn extensioned(&self) -> bool {
83 self.extensioned
84 }
85
86 pub fn perm(&self) -> u32 {
87 self.perm
88 }
89}
90
91impl Default for BaseFiler {
92 fn default() -> Self {
93 Self {
94 name: String::from("main"),
95 base: String::from(""),
96 temp: false,
97 head_dir_path: PathBuf::from(Self::HEAD_DIR_PATH),
98 path: None,
99 perm: Self::PERM,
100 filed: false,
101 extensioned: false,
102 mode: Self::MODE.to_string(),
103 fext: Self::FEXT.to_string(),
104 file: None,
105 opened: false,
106 defaults: FilerDefaults::default(),
107 }
108 }
109}
110
111pub struct FilerDefaults {
112 pub head_dir_path: &'static str,
113 pub tail_dir_path: &'static str,
114 pub clean_tail_dir_path: &'static str,
115 pub alt_head_dir_path: &'static str,
116 pub alt_tail_dir_path: &'static str,
117 pub alt_clean_tail_dir_path: &'static str,
118 pub temp_head_dir: &'static str,
119 pub temp_prefix: &'static str,
120 pub temp_suffix: &'static str,
121 pub perm: u32,
122 pub mode: &'static str,
123 pub fext: &'static str,
124}
125
126impl Default for FilerDefaults {
127 fn default() -> Self {
128 Self {
129 head_dir_path: <BaseFiler as Filer>::HEAD_DIR_PATH,
130 tail_dir_path: <BaseFiler as Filer>::TAIL_DIR_PATH,
131 clean_tail_dir_path: <BaseFiler as Filer>::CLEAN_TAIL_DIR_PATH,
132 alt_head_dir_path: "~",
133 alt_tail_dir_path: <BaseFiler as Filer>::ALT_TAIL_DIR_PATH,
134 alt_clean_tail_dir_path: <BaseFiler as Filer>::ALT_CLEAN_TAIL_DIR_PATH,
135 temp_head_dir: <BaseFiler as Filer>::TEMP_HEAD_DIR,
136 temp_prefix: <BaseFiler as Filer>::TEMP_PREFIX,
137 temp_suffix: "_test",
138 perm: <BaseFiler as Filer>::PERM,
139 mode: <BaseFiler as Filer>::MODE,
140 fext: <BaseFiler as Filer>::FEXT,
141 }
142 }
143}
144
145#[allow(dead_code)]
146pub trait Filer {
147 fn defaults() -> FilerDefaults {
148 FilerDefaults::default()
149 }
150
151 const HEAD_DIR_PATH: &'static str = "/usr/local/var";
154
155 const TAIL_DIR_PATH: &'static str = "keri";
157
158 const CLEAN_TAIL_DIR_PATH: &'static str = "keri/clean";
160
161 const ALT_TAIL_DIR_PATH: &'static str = ".keri";
163
164 const ALT_CLEAN_TAIL_DIR_PATH: &'static str = ".keri/clean";
166
167 const TEMP_PREFIX: &'static str = "keri_";
169
170 const TEMP_HEAD_DIR: &'static str = "/tmp";
172
173 const PERM: u32 = 0o1700;
175
176 const MODE: &'static str = "r+";
178
179 const FEXT: &'static str = "text";
181}
182
183impl Filer for BaseFiler {}
184
185#[allow(dead_code)]
186impl BaseFiler {
187 pub fn new<S1, S2>(
209 name: S1,
210 base: S2,
211 temp: bool,
212 head_dir_path: Option<PathBuf>,
213 perm: Option<u32>,
214 reopen: bool,
215 clear: bool,
216 reuse: bool,
217 clean: bool,
218 filed: bool,
219 extensioned: bool,
220 mode: Option<String>,
221 fext: Option<String>,
222 defaults: Option<FilerDefaults>,
223 ) -> Result<Self, CoreError>
224 where
225 S1: Into<String>,
226 S2: Into<String>,
227 {
228 let name = name.into();
229 let base = base.into();
230
231 if Path::new(&name).is_absolute() {
233 return Err(CoreError::FilerError(format!(
234 "Not relative name={} path.",
235 name
236 )));
237 }
238
239 if Path::new(&base).is_absolute() {
240 return Err(CoreError::FilerError(format!(
241 "Not relative base={} path.",
242 base
243 )));
244 }
245
246 let defaults = defaults.unwrap_or_default();
247
248 let head_dir_path = head_dir_path.unwrap_or_else(|| PathBuf::from(defaults.head_dir_path));
249 let perm = perm.unwrap_or(defaults.perm);
250 let mode = mode.unwrap_or_else(|| defaults.mode.to_string());
251 let fext = fext.unwrap_or_else(|| defaults.fext.to_string());
252
253 let mut filer = Self {
254 name,
255 base,
256 temp,
257 head_dir_path,
258 path: None,
259 perm,
260 filed,
261 extensioned,
262 mode,
263 fext,
264 file: None,
265 opened: false,
266 defaults,
267 };
268
269 if reopen {
270 filer.reopen(
271 Some(temp),
272 None,
273 Some(perm),
274 clear,
275 reuse,
276 clean,
277 None,
278 None,
279 )?;
280 }
281
282 Ok(filer)
283 }
284
285 pub fn reopen(
302 &mut self,
303 temp: Option<bool>,
304 head_dir_path: Option<PathBuf>,
305 perm: Option<u32>,
306 clear: bool,
307 reuse: bool,
308 clean: bool,
309 mode: Option<String>,
310 fext: Option<String>,
311 ) -> Result<bool, CoreError> {
312 self.close(clear)?;
314
315 if let Some(t) = temp {
317 self.temp = t;
318 }
319
320 if let Some(path) = head_dir_path {
321 self.head_dir_path = path;
322 }
323
324 if let Some(p) = perm {
325 self.perm = p;
326 }
327
328 if let Some(m) = mode {
329 self.mode = m;
330 }
331
332 if let Some(ext) = fext {
333 self.fext = ext;
334 }
335
336 let path_needs_remake =
338 self.path.is_none() || !self.path.as_ref().map_or(false, |p| p.exists()) || !reuse;
339
340 if path_needs_remake {
341 let result = self.remake(
343 &self.name,
344 &self.base,
345 Some(self.temp),
346 Some(&self.head_dir_path),
347 Some(self.perm),
348 clean,
349 self.filed,
350 self.extensioned,
351 Some(&self.mode),
352 Some(&self.fext),
353 )?;
354
355 self.path = Some(result.0);
356 self.file = result.1;
357 } else if self.filed {
358 if let Some(path) = &self.path {
361 self.file = Some(self.open_file_with_perms(path, &self.mode, self.perm)?);
362 }
363 }
364
365 if !self.filed {
367 self.opened = true;
368 } else {
369 self.opened = self.file.is_some();
370 }
371
372 Ok(self.opened)
373 }
374
375 pub fn remake(
401 &self,
402 name: &str,
403 base: &str,
404 temp: Option<bool>,
405 head_dir_path: Option<&Path>,
406 perm: Option<u32>,
407 clean: bool,
408 filed: bool,
409 extensioned: bool,
410 mode: Option<&str>,
411 fext: Option<&str>,
412 ) -> Result<(PathBuf, Option<File>), CoreError> {
413 if Path::new(name).is_absolute() {
415 return Err(CoreError::NotRelativePath(format!("name={}", name)));
416 }
417
418 if Path::new(base).is_absolute() {
419 return Err(CoreError::NotRelativePath(format!("base={}", base)));
420 }
421
422 let temp = temp.unwrap_or(false);
424 let head_dir_path = head_dir_path.unwrap_or_else(|| Path::new(self.defaults.head_dir_path));
425 let perm = perm.unwrap_or(self.defaults.perm);
426 let mode = mode.unwrap_or(self.defaults.mode);
427 let fext = fext.unwrap_or(self.defaults.fext);
428
429 let tail_dir_path = if clean {
431 self.defaults.clean_tail_dir_path
432 } else {
433 self.defaults.tail_dir_path
434 };
435
436 let alt_tail_dir_path = if clean {
437 self.defaults.alt_clean_tail_dir_path
438 } else {
439 self.defaults.alt_tail_dir_path
440 };
441
442 let mut name_with_ext = name.to_string();
444 if filed || extensioned {
445 if !name.contains(&format!(".{}", fext)) {
446 name_with_ext = format!("{}.{}", name, fext);
447 }
448 }
449
450 if Path::new(&name_with_ext).is_absolute() {
451 return Err(CoreError::NotRelativePath(format!(
452 "name={}",
453 name_with_ext
454 )));
455 }
456
457 let mut file = None;
458 let path: PathBuf;
459
460 if temp {
461 let temp_head_dir = Path::new(self.defaults.temp_head_dir);
463 let temp_dir = create_temp_dir(
464 self.defaults.temp_prefix,
465 self.defaults.temp_suffix,
466 Some(temp_head_dir),
467 )
468 .map_err(|e| CoreError::IoError(format!("Unable to create temp dir: {}", e)))?;
469
470 let temp_path = temp_dir.path();
471
472 path = temp_path
473 .join(tail_dir_path)
474 .join(base)
475 .join(&name_with_ext);
476
477 if clean && path.exists() {
479 if path.is_file() {
480 if filed || extensioned {
481 fs::remove_file(&path).map_err(|e| {
482 CoreError::IoError(format!("Unable to remove file: {}", e))
483 })?;
484 } else {
485 if let Some(parent) = path.parent() {
486 fs::remove_dir_all(parent).map_err(|e| {
487 CoreError::IoError(format!("Unable to remove all: {}", e))
488 })?;
489 }
490 }
491 } else {
492 fs::remove_dir_all(&path).map_err(|e| {
493 CoreError::IoError(format!("Unable to remove all dir: {}", e))
494 })?;
495 }
496 }
497
498 if filed || extensioned {
499 if let Some(parent) = path.parent() {
500 if !parent.exists() {
501 fs::create_dir_all(parent).map_err(|e| {
502 CoreError::IoError(format!("Unable to create all dir: {}", e))
503 })?;
504 }
505 }
506
507 if filed {
508 file = Some(self.open_file_with_perms(&path, mode, perm)?);
509 }
510 } else {
511 fs::create_dir_all(&path)
512 .map_err(|e| CoreError::IoError(format!("Unable to create all dir: {}", e)))?;
513 }
514 } else {
515 let primary_path = PathBuf::from(head_dir_path)
517 .join(tail_dir_path)
518 .join(base)
519 .join(&name_with_ext);
520
521 let primary_path = expand_user_path(&primary_path)?;
523
524 if clean && primary_path.exists() {
526 if primary_path.is_file() {
527 if filed {
528 fs::remove_file(&primary_path).map_err(|e| {
529 CoreError::IoError(format!("Unable to remove file: {}", e))
530 })?;
531 } else {
532 if let Some(parent) = primary_path.parent() {
533 fs::remove_dir_all(parent).map_err(|e| {
534 CoreError::IoError(format!("Unable toremove all dir: {}", e))
535 })?;
536 }
537 }
538 } else {
539 fs::remove_dir_all(&primary_path).map_err(|e| {
540 CoreError::IoError(format!("Unable to remove all dir: {}", e))
541 })?;
542 }
543 }
544
545 let result = if !primary_path.exists() {
547 if filed || extensioned {
548 if let Some(parent) = primary_path.parent() {
549 if !parent.exists() {
550 match fs::create_dir_all(parent) {
551 Ok(_) => Ok(primary_path),
552 Err(_) => {
553 Err(CoreError::IoError("Unable to create dir".to_string()))
554 }
555 }
556 } else {
557 Ok(primary_path)
558 }
559 } else {
560 Ok(primary_path)
561 }
562 } else {
563 match fs::create_dir_all(&primary_path) {
564 Ok(_) => Ok(primary_path),
565 Err(_) => Err(CoreError::IoError("Unable to create dir".to_string())),
566 }
567 }
568 } else {
569 if !has_full_access(&primary_path)? {
571 Err(CoreError::PermissionError(
572 "Full access denied to primary path".to_string(),
573 ))
574 } else {
575 Ok(primary_path)
576 }
577 };
578
579 if result.is_err() {
581 let alt_path = PathBuf::from(self.defaults.alt_head_dir_path)
582 .join(alt_tail_dir_path)
583 .join(base)
584 .join(&name_with_ext);
585
586 let alt_path = expand_user_path(&alt_path)?;
588
589 if !alt_path.exists() {
590 if filed || extensioned {
591 if let Some(parent) = alt_path.parent() {
592 if !parent.exists() {
593 fs::create_dir_all(parent).map_err(|e| {
594 CoreError::IoError(format!(
595 "Unable to create parent dir: {}",
596 e
597 ))
598 })?;
599 }
600 }
601 } else {
602 fs::create_dir_all(&alt_path).map_err(|e| {
603 CoreError::IoError(format!("Unable to create all dir: {}", e))
604 })?;
605 }
606 }
607
608 if filed {
609 file = Some(self.open_file_with_perms(&alt_path, mode, perm)?);
610 }
611
612 path = alt_path;
613 } else {
614 let result_path = result?;
616 path = result_path;
617
618 if filed {
619 file = Some(self.open_file_with_perms(&path, mode, perm)?);
620 }
621 }
622
623 if !extensioned {
625 fs::set_permissions(&path, fs::Permissions::from_mode(perm)).map_err(|e| {
626 CoreError::IoError(format!("Unable to set file permissions {}", e))
627 })?;
628 }
629 }
630
631 Ok((path, file))
632 }
633
634 pub fn exists(
657 &self,
658 name: &str,
659 base: &str,
660 head_dir_path: Option<&Path>,
661 clean: bool,
662 filed: bool,
663 extensioned: bool,
664 fext: Option<&str>,
665 ) -> Result<bool, CoreError> {
666 if Path::new(name).is_absolute() {
668 return Err(CoreError::NotRelativePath(format!("name={}", name)));
669 }
670
671 if Path::new(base).is_absolute() {
672 return Err(CoreError::NotRelativePath(format!("base={}", base)));
673 }
674
675 let head_dir_path = head_dir_path.unwrap_or_else(|| Path::new(self.defaults.head_dir_path));
677 let fext = fext.unwrap_or(self.defaults.fext);
678
679 let tail_dir_path = if clean {
681 self.defaults.clean_tail_dir_path
682 } else {
683 self.defaults.tail_dir_path
684 };
685
686 let alt_tail_dir_path = if clean {
687 self.defaults.alt_clean_tail_dir_path
688 } else {
689 self.defaults.alt_tail_dir_path
690 };
691
692 let mut name_with_ext = name.to_string();
694 if filed || extensioned {
695 if !name.contains(&format!(".{}", fext)) {
696 name_with_ext = format!("{}.{}", name, fext);
697 }
698 }
699
700 if Path::new(&name_with_ext).is_absolute() {
701 return Err(CoreError::NotRelativePath(format!(
702 "name={}",
703 name_with_ext
704 )));
705 }
706
707 let primary_path = PathBuf::from(head_dir_path)
709 .join(tail_dir_path)
710 .join(base)
711 .join(&name_with_ext);
712
713 let primary_path = expand_user_path(&primary_path)?;
715
716 if primary_path.exists() {
718 return Ok(true);
719 }
720
721 let alt_path = PathBuf::from(self.defaults.alt_head_dir_path)
723 .join(alt_tail_dir_path)
724 .join(base)
725 .join(&name_with_ext);
726
727 let alt_path = expand_user_path(&alt_path)?;
729
730 Ok(alt_path.exists())
732 }
733
734 pub fn close(&mut self, clear: bool) -> Result<bool, CoreError> {
744 if let Some(file) = self.file.take() {
746 drop(file); }
748
749 self.opened = false;
750
751 if clear {
753 self.remove()?;
754 }
755
756 Ok(!self.opened)
758 }
759
760 fn remove(&mut self) -> Result<(), CoreError> {
762 if let Some(path) = &self.path {
763 if path.exists() {
764 if path.is_file() {
765 fs::remove_file(path)
766 .map_err(|e| CoreError::IoError(format!("Unable to remove file {}", e)))?;
767 } else {
768 fs::remove_dir_all(path).map_err(|e| {
769 CoreError::IoError(format!("Unable to remove dir all {}", e))
770 })?;
771 }
772 }
773 }
774
775 Ok(())
776 }
777
778 fn clear_path(&mut self) -> Result<(), CoreError> {
783 if let Some(path) = &self.path {
784 if path.exists() {
785 if path.is_file() {
786 fs::remove_file(path)
788 .map_err(|e| CoreError::IoError(format!("Unable to remove file {}", e)))?;
789
790 self.file = None;
792
793 if self.temp {
795 if let Some(parent) = path.parent() {
796 fs::remove_dir_all(parent).map_err(|e| {
797 CoreError::IoError(format!("Unable to remove all dir {}", e))
798 })?;
799 }
800 }
801 } else if self.extensioned {
802 fs::remove_file(path)
804 .map_err(|e| CoreError::IoError(format!("Unable to remove file {}", e)))?;
805
806 if self.temp {
808 if let Some(parent) = path.parent() {
809 fs::remove_dir_all(parent).map_err(|e| {
810 CoreError::IoError(format!("Unable to remove all dir parent {}", e))
811 })?;
812 }
813 }
814 } else {
815 fs::remove_dir_all(path).map_err(|e| {
817 CoreError::IoError(format!("Unable to remove all dir path {}", e))
818 })?;
819 }
820 }
821 }
822
823 Ok(())
824 }
825
826 fn open_file_with_perms(&self, path: &Path, mode: &str, perm: u32) -> Result<File, CoreError> {
828 let file = OpenOptions::new()
829 .read(mode.contains('r'))
830 .write(mode.contains('w') || mode.contains('+'))
831 .create(true)
832 .open(path)
833 .map_err(|e| CoreError::IoError(format!("Invalid permissiotns options {}", e)))?;
834
835 fs::set_permissions(path, fs::Permissions::from_mode(perm))
836 .map_err(|e| CoreError::IoError(format!("Unable to set permissions{}", e)))?;
837
838 Ok(file)
839 }
840
841 pub fn open(&mut self) -> io::Result<()> {
843 self.build_path();
845
846 if let Some(path) = &self.path {
847 if let Some(parent) = path.parent() {
849 fs::create_dir_all(parent)?;
850 fs::set_permissions(parent, fs::Permissions::from_mode(self.perm))?;
851 }
852
853 if self.filed {
854 let file = OpenOptions::new()
856 .read(self.mode.contains("r"))
857 .write(self.mode.contains("w") || self.mode.contains("+"))
858 .create(true)
859 .open(path)?;
860
861 fs::set_permissions(path, fs::Permissions::from_mode(self.perm))?;
863
864 self.file = Some(file);
865 } else {
866 fs::create_dir_all(path)?;
868 fs::set_permissions(path, fs::Permissions::from_mode(self.perm))?;
869 }
870
871 self.opened = true;
872 }
873
874 Ok(())
875 }
876
877 fn build_path(&mut self) {
879 let mut path = if self.temp {
880 let mut p = PathBuf::from(self.defaults.temp_head_dir);
881 p.push(format!(
882 "{}{}{}",
883 self.defaults.temp_prefix, self.name, self.defaults.temp_suffix
884 ));
885 p
886 } else {
887 let mut p = self.head_dir_path.clone();
888 p.push(self.defaults.tail_dir_path);
889 if !self.base.is_empty() {
890 p.push(&self.base);
891 }
892 p.push(&self.name);
893 p
894 };
895
896 if self.filed || self.extensioned {
898 let mut file_name = path
899 .file_name()
900 .unwrap_or_default()
901 .to_string_lossy()
902 .into_owned();
903 if !file_name.ends_with(&format!(".{}", self.fext)) {
904 file_name = format!("{}.{}", file_name, self.fext);
905 path.set_file_name(file_name);
906 }
907 }
908
909 self.path = Some(path);
910 }
911
912 pub fn get_path(&self) -> Option<&Path> {
914 self.path.as_deref()
915 }
916
917 pub fn get_file(&self) -> Option<&File> {
919 self.file.as_ref()
920 }
921
922 pub fn get_file_mut(&mut self) -> Option<&mut File> {
924 self.file.as_mut()
925 }
926}
927
928fn expand_user_path(path: &Path) -> Result<PathBuf, CoreError> {
930 let path_str = path.to_string_lossy();
931
932 if path_str.starts_with("~") {
933 let home = dirs::home_dir()
934 .ok_or_else(|| CoreError::OtherError("Could not find home directory".to_string()))?;
935
936 let remainder = path_str.strip_prefix("~").unwrap();
937 let remainder = if remainder.starts_with('/') {
938 &remainder[1..]
939 } else {
940 remainder
941 };
942
943 Ok(home.join(remainder))
944 } else {
945 Ok(path.to_path_buf())
946 }
947}
948
949fn has_full_access(path: &Path) -> Result<bool, CoreError> {
951 let metadata = fs::metadata(path).map_err(|e| CoreError::IoError(e.to_string()))?;
952
953 Ok(metadata.permissions().mode() & 0o600 == 0o600)
956}
957
958fn create_temp_dir(
959 prefix: &str,
960 suffix: &str,
961 temp_dir: Option<&Path>,
962) -> io::Result<tempfile::TempDir> {
963 let temp_path = temp_dir.unwrap_or_else(|| Path::new("/tmp"));
964 Builder::new()
965 .prefix(prefix)
966 .suffix(suffix)
967 .keep(true)
968 .tempdir_in(temp_path)
969}
970
971#[cfg(test)]
972mod tests {
973 use super::*;
974 use std::fs;
975 use std::io::{Read, Seek, SeekFrom, Write};
976 use std::path::{Path, PathBuf};
977
978 fn cleanup_test_dirs() {
979 let dir_path = Path::new("/usr/local/var/hio/test");
981 if dir_path.exists() {
982 let _ = fs::remove_dir_all(dir_path);
983 }
984
985 let home_dir = dirs::home_dir().unwrap();
987 let alt_dir_path = home_dir.join(".hio").join("test");
988 if alt_dir_path.exists() {
989 let _ = fs::remove_dir_all(alt_dir_path);
990 }
991 }
992
993 #[test]
994 fn test_filing_basic() {
995 cleanup_test_dirs();
996
997 let filer = BaseFiler::new(
999 "test", "", false, None, None, false, false, false, false, false, false, None, None,
1000 None,
1001 )
1002 .unwrap();
1003 assert!(!filer
1004 .exists("test", "", None, false, false, false, None)
1005 .unwrap());
1006
1007 let mut filer = BaseFiler::new(
1009 "test", "", false, None, None, true, false, false, false, false, false, None, None,
1010 None,
1011 )
1012 .unwrap();
1013 assert!(filer
1014 .exists("test", "", None, false, false, false, None)
1015 .unwrap());
1016 assert!(filer
1017 .path
1018 .as_ref()
1019 .unwrap()
1020 .to_str()
1021 .unwrap()
1022 .ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1023 assert!(filer.opened);
1024 assert!(filer.path.as_ref().unwrap().exists());
1025 assert!(filer.file.is_none());
1026
1027 let _ = filer.close(false);
1028 assert!(!filer.opened);
1029
1030 let norm_path_filer = filer.path.as_ref().unwrap().to_str().unwrap();
1032 let norm_path_filer = norm_path_filer.split(':').last().unwrap_or(norm_path_filer);
1034 assert!(norm_path_filer.ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1035 assert!(filer.path.as_ref().unwrap().exists());
1036
1037 let mut filer = filer;
1039 let _ = filer.reopen(None, None, None, false, false, false, None, None);
1040 assert!(filer.opened);
1041 assert!(filer
1042 .path
1043 .as_ref()
1044 .unwrap()
1045 .to_str()
1046 .unwrap()
1047 .ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1048 assert!(filer.path.as_ref().unwrap().exists());
1049
1050 let _ = filer.reopen(None, None, None, false, true, false, None, None);
1052 assert!(filer.opened);
1053 assert!(filer
1054 .path
1055 .as_ref()
1056 .unwrap()
1057 .to_str()
1058 .unwrap()
1059 .ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1060 assert!(filer.path.as_ref().unwrap().exists());
1061
1062 let _ = filer.reopen(None, None, None, true, true, false, None, None);
1064 assert!(filer.opened);
1065 assert!(filer
1066 .path
1067 .as_ref()
1068 .unwrap()
1069 .to_str()
1070 .unwrap()
1071 .ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1072 assert!(filer.path.as_ref().unwrap().exists());
1073
1074 let _ = filer.reopen(None, None, None, true, false, false, None, None);
1076 assert!(filer.opened);
1077 assert!(filer
1078 .path
1079 .as_ref()
1080 .unwrap()
1081 .to_str()
1082 .unwrap()
1083 .ends_with(&format!("keri{}test", std::path::MAIN_SEPARATOR)));
1084 assert!(filer.path.as_ref().unwrap().exists());
1085
1086 let _ = filer.close(true);
1088 assert!(!filer.path.as_ref().unwrap().exists());
1089 }
1090
1091 #[test]
1092 fn test_filing_clean() {
1093 cleanup_test_dirs();
1094
1095 let dir_path = Path::new("/usr/local/var/keri/clean/test");
1097 if dir_path.exists() {
1098 let _ = fs::remove_dir_all(dir_path);
1099 }
1100
1101 let home_dir = dirs::home_dir().unwrap();
1102 let alt_dir_path = home_dir.join(".keri").join("clean").join("test");
1103 if alt_dir_path.exists() {
1104 let _ = fs::remove_dir_all(alt_dir_path);
1105 }
1106
1107 let filer = BaseFiler::new(
1109 "test", "", false, None, None, false, false, false, true, false, false, None, None,
1110 None,
1111 )
1112 .unwrap();
1113 assert!(!filer
1114 .exists("test", "", None, true, false, false, None)
1115 .unwrap());
1116
1117 let mut filer = BaseFiler::new(
1119 "test", "", false, None, None, true, false, false, true, false, false, None, None, None,
1120 )
1121 .unwrap();
1122 assert!(filer
1123 .exists("test", "", None, true, false, false, None)
1124 .unwrap());
1125 assert!(filer
1126 .path
1127 .as_ref()
1128 .unwrap()
1129 .to_str()
1130 .unwrap()
1131 .ends_with(&format!(
1132 "keri{}clean{}test",
1133 std::path::MAIN_SEPARATOR,
1134 std::path::MAIN_SEPARATOR
1135 )));
1136 assert!(filer.opened);
1137 assert!(filer.path.as_ref().unwrap().exists());
1138 assert!(filer.file.is_none());
1139
1140 let _ = filer.close(false);
1141 assert!(!filer.opened);
1142
1143 let norm_path_filer = filer.path.as_ref().unwrap().to_str().unwrap();
1145
1146 let norm_path_filer = norm_path_filer.split(':').last().unwrap_or(norm_path_filer);
1148 assert!(norm_path_filer.ends_with(&format!(
1149 "keri{}clean{}test",
1150 std::path::MAIN_SEPARATOR,
1151 std::path::MAIN_SEPARATOR
1152 )));
1153 assert!(filer.path.as_ref().unwrap().exists());
1154
1155 let mut filer = filer;
1157
1158 let _ = filer.reopen(None, None, None, false, false, true, None, None);
1159 assert!(filer.opened);
1160 assert!(filer
1161 .path
1162 .as_ref()
1163 .unwrap()
1164 .to_str()
1165 .unwrap()
1166 .ends_with(&format!(
1167 "keri{}clean{}test",
1168 std::path::MAIN_SEPARATOR,
1169 std::path::MAIN_SEPARATOR
1170 )));
1171 assert!(filer.path.as_ref().unwrap().exists());
1172
1173 let _ = filer.reopen(None, None, None, false, true, true, None, None);
1174 assert!(filer.opened);
1175 assert!(filer
1176 .path
1177 .as_ref()
1178 .unwrap()
1179 .to_str()
1180 .unwrap()
1181 .ends_with(&format!(
1182 "keri{}clean{}test",
1183 std::path::MAIN_SEPARATOR,
1184 std::path::MAIN_SEPARATOR
1185 )));
1186 assert!(filer.path.as_ref().unwrap().exists());
1187
1188 let _ = filer.reopen(None, None, None, true, true, true, None, None);
1189 assert!(filer.opened);
1190 assert!(filer
1191 .path
1192 .as_ref()
1193 .unwrap()
1194 .to_str()
1195 .unwrap()
1196 .ends_with(&format!(
1197 "keri{}clean{}test",
1198 std::path::MAIN_SEPARATOR,
1199 std::path::MAIN_SEPARATOR
1200 )));
1201 assert!(filer.path.as_ref().unwrap().exists());
1202
1203 let _ = filer.reopen(None, None, None, true, false, true, None, None);
1204 assert!(filer.opened);
1205 assert!(filer
1206 .path
1207 .as_ref()
1208 .unwrap()
1209 .to_str()
1210 .unwrap()
1211 .ends_with(&format!(
1212 "keri{}clean{}test",
1213 std::path::MAIN_SEPARATOR,
1214 std::path::MAIN_SEPARATOR
1215 )));
1216 assert!(filer.path.as_ref().unwrap().exists());
1217
1218 let _ = filer.close(true);
1219 assert!(!filer.path.as_ref().unwrap().exists());
1220 }
1221
1222 #[test]
1223 fn test_filing_with_alt_path() {
1224 cleanup_test_dirs();
1225
1226 let home_dir = dirs::home_dir().unwrap();
1227 let alt_dir_path = home_dir.join(".keri").join("test");
1228 if alt_dir_path.exists() {
1229 let _ = fs::remove_dir_all(&alt_dir_path);
1230 }
1231
1232 let head_dir_path = if cfg!(windows) {
1234 PathBuf::from("C:\\Windows\\System32\\keri")
1235 } else {
1236 PathBuf::from("/root/keri")
1237 };
1238
1239 let filer = BaseFiler::new(
1241 "test",
1242 "",
1243 false,
1244 Some(head_dir_path.clone()),
1245 None,
1246 false,
1247 false,
1248 false,
1249 false,
1250 false,
1251 false,
1252 None,
1253 None,
1254 None,
1255 )
1256 .unwrap();
1257 assert!(!filer
1258 .exists("test", "", Some(&head_dir_path), false, false, false, None)
1259 .unwrap());
1260
1261 let mut filer = BaseFiler::new(
1263 "test",
1264 "",
1265 false,
1266 Some(head_dir_path.clone()),
1267 None,
1268 true,
1269 false,
1270 false,
1271 false,
1272 false,
1273 false,
1274 None,
1275 None,
1276 None,
1277 )
1278 .unwrap();
1279
1280 assert!(filer
1281 .exists("test", "", Some(&head_dir_path), false, false, false, None)
1282 .unwrap());
1283 assert!(filer
1284 .path
1285 .as_ref()
1286 .unwrap()
1287 .to_str()
1288 .unwrap()
1289 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1290 assert!(filer.opened);
1291 assert!(filer.path.as_ref().unwrap().exists());
1292 assert!(filer.file.is_none());
1293
1294 let _ = filer.close(false);
1295 assert!(!filer.opened);
1296 assert!(filer
1297 .path
1298 .as_ref()
1299 .unwrap()
1300 .to_str()
1301 .unwrap()
1302 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1303 assert!(filer.path.as_ref().unwrap().exists());
1304
1305 let mut filer = filer;
1307
1308 let _ = filer.reopen(None, None, None, false, false, false, None, None);
1309 assert!(filer.opened);
1310 assert!(filer
1311 .path
1312 .as_ref()
1313 .unwrap()
1314 .to_str()
1315 .unwrap()
1316 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1317 assert!(filer.path.as_ref().unwrap().exists());
1318
1319 let _ = filer.reopen(None, None, None, false, true, false, None, None);
1320 assert!(filer.opened);
1321 assert!(filer
1322 .path
1323 .as_ref()
1324 .unwrap()
1325 .to_str()
1326 .unwrap()
1327 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1328 assert!(filer.path.as_ref().unwrap().exists());
1329
1330 let _ = filer.reopen(None, None, None, true, true, false, None, None);
1331 assert!(filer.opened);
1332 assert!(filer
1333 .path
1334 .as_ref()
1335 .unwrap()
1336 .to_str()
1337 .unwrap()
1338 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1339 assert!(filer.path.as_ref().unwrap().exists());
1340
1341 let _ = filer.reopen(None, None, None, true, false, false, None, None);
1342 assert!(filer.opened);
1343 assert!(filer
1344 .path
1345 .as_ref()
1346 .unwrap()
1347 .to_str()
1348 .unwrap()
1349 .ends_with(&format!(".keri{}test", std::path::MAIN_SEPARATOR)));
1350 assert!(filer.path.as_ref().unwrap().exists());
1351
1352 let _ = filer.close(true);
1353 assert!(!filer.path.as_ref().unwrap().exists());
1354 }
1355
1356 #[test]
1357 fn test_filing_with_file() {
1358 cleanup_test_dirs();
1359
1360 let file_path = Path::new("/usr/local/var/keri/conf/test.text");
1362 if file_path.exists() {
1363 let _ = fs::remove_file(file_path);
1364 }
1365
1366 let home_dir = dirs::home_dir().unwrap();
1367 let alt_file_path = home_dir.join(".keri").join("conf").join("test.text");
1368 if alt_file_path.exists() {
1369 let _ = fs::remove_file(alt_file_path);
1370 }
1371
1372 assert!(!file_path.exists());
1373
1374 let filer = BaseFiler::new(
1376 "test", "conf", false, None, None, false, false, false, false, true, false, None, None,
1377 None,
1378 )
1379 .unwrap();
1380 assert!(!filer
1381 .exists("test", "", None, false, true, false, None)
1382 .unwrap());
1383
1384 let mut filer = BaseFiler::new(
1386 "test", "conf", false, None, None, true, false, false, false, true, false, None, None,
1387 None,
1388 )
1389 .unwrap();
1390
1391 assert!(filer
1392 .exists("test", "conf", None, false, true, false, None)
1393 .unwrap());
1394 assert!(filer
1395 .path
1396 .as_ref()
1397 .unwrap()
1398 .to_str()
1399 .unwrap()
1400 .ends_with(&format!(
1401 "keri{}conf{}test.text",
1402 std::path::MAIN_SEPARATOR,
1403 std::path::MAIN_SEPARATOR
1404 )));
1405 assert!(filer.opened);
1406 assert!(filer.path.as_ref().unwrap().exists());
1407 assert!(filer.file.is_some());
1408
1409 {
1411 let mut file = filer.file.as_ref().unwrap();
1412 let mut contents = String::new();
1413 let _ = file.read_to_string(&mut contents);
1414 assert!(contents.is_empty());
1415
1416 let msg = "Hello Jim\n";
1417 assert_eq!(file.write(msg.as_bytes()).unwrap(), msg.len());
1418 let _ = file.seek(SeekFrom::Start(0));
1419 let mut contents = String::new();
1420 let _ = file.read_to_string(&mut contents);
1421 assert_eq!(contents, msg);
1422 }
1423
1424 let _ = filer.close(false);
1425 assert!(!filer.opened);
1426 assert!(filer
1427 .path
1428 .as_ref()
1429 .unwrap()
1430 .to_str()
1431 .unwrap()
1432 .ends_with(&format!(
1433 "keri{}conf{}test.text",
1434 std::path::MAIN_SEPARATOR,
1435 std::path::MAIN_SEPARATOR
1436 )));
1437 assert!(filer.path.as_ref().unwrap().exists());
1438
1439 let mut filer = filer;
1441
1442 let _ = filer.reopen(None, None, None, false, false, false, None, None);
1443 assert!(filer.opened);
1444 assert!(filer
1445 .path
1446 .as_ref()
1447 .unwrap()
1448 .to_str()
1449 .unwrap()
1450 .ends_with(&format!(
1451 "keri{}conf{}test.text",
1452 std::path::MAIN_SEPARATOR,
1453 std::path::MAIN_SEPARATOR
1454 )));
1455 assert!(filer.path.as_ref().unwrap().exists());
1456
1457 let _ = filer.reopen(None, None, None, false, true, false, None, None);
1458 assert!(filer.opened);
1459 assert!(filer
1460 .path
1461 .as_ref()
1462 .unwrap()
1463 .to_str()
1464 .unwrap()
1465 .ends_with(&format!(
1466 "keri{}conf{}test.text",
1467 std::path::MAIN_SEPARATOR,
1468 std::path::MAIN_SEPARATOR
1469 )));
1470 assert!(filer.path.as_ref().unwrap().exists());
1471
1472 let _ = filer.reopen(None, None, None, true, true, false, None, None);
1473 assert!(filer.opened);
1474 assert!(filer
1475 .path
1476 .as_ref()
1477 .unwrap()
1478 .to_str()
1479 .unwrap()
1480 .ends_with(&format!(
1481 "keri{}conf{}test.text",
1482 std::path::MAIN_SEPARATOR,
1483 std::path::MAIN_SEPARATOR
1484 )));
1485 assert!(filer.path.as_ref().unwrap().exists());
1486
1487 let _ = filer.reopen(None, None, None, true, false, false, None, None);
1488 assert!(filer.opened);
1489 assert!(filer
1490 .path
1491 .as_ref()
1492 .unwrap()
1493 .to_str()
1494 .unwrap()
1495 .ends_with(&format!(
1496 "keri{}conf{}test.text",
1497 std::path::MAIN_SEPARATOR,
1498 std::path::MAIN_SEPARATOR
1499 )));
1500 assert!(filer.path.as_ref().unwrap().exists());
1501
1502 let _ = filer.close(true);
1503 assert!(!filer.path.as_ref().unwrap().exists());
1504 }
1505
1506 #[test]
1507 fn test_filing_with_file_and_alt_path() {
1508 cleanup_test_dirs();
1509
1510 let home_dir = dirs::home_dir().unwrap();
1511 let alt_file_path = home_dir.join(".keri").join("conf").join("test.text");
1512 if alt_file_path.exists() {
1513 let _ = fs::remove_file(&alt_file_path);
1514 }
1515
1516 let head_dir_path = if cfg!(windows) {
1518 PathBuf::from("C:\\Windows\\System32")
1519 } else {
1520 PathBuf::from("/root/keri")
1521 };
1522
1523 let filer = BaseFiler::new(
1525 "test",
1526 "conf",
1527 false,
1528 Some(head_dir_path.clone()),
1529 None,
1530 false,
1531 false,
1532 false,
1533 false,
1534 true,
1535 false,
1536 None,
1537 None,
1538 None,
1539 )
1540 .unwrap();
1541 assert!(!filer
1542 .exists(
1543 "test",
1544 "conf",
1545 Some(&head_dir_path),
1546 false,
1547 true,
1548 false,
1549 None
1550 )
1551 .unwrap());
1552
1553 let mut filer = BaseFiler::new(
1555 "test",
1556 "conf",
1557 false,
1558 Some(head_dir_path.clone()),
1559 None,
1560 true,
1561 false,
1562 false,
1563 false,
1564 true,
1565 false,
1566 None,
1567 None,
1568 None,
1569 )
1570 .unwrap();
1571
1572 assert!(filer
1573 .exists(
1574 "test",
1575 "conf",
1576 Some(&head_dir_path),
1577 false,
1578 true,
1579 false,
1580 None
1581 )
1582 .unwrap());
1583 assert!(filer
1584 .path
1585 .as_ref()
1586 .unwrap()
1587 .to_str()
1588 .unwrap()
1589 .ends_with(&format!(
1590 ".keri{}conf{}test.text",
1591 std::path::MAIN_SEPARATOR,
1592 std::path::MAIN_SEPARATOR
1593 )));
1594 assert!(filer.opened);
1595 assert!(filer.path.as_ref().unwrap().exists());
1596 assert!(filer.file.is_some());
1597
1598 {
1600 let mut file = filer.file.as_ref().unwrap();
1601 let mut contents = String::new();
1602 let _ = file.read_to_string(&mut contents);
1603 assert!(contents.is_empty());
1604
1605 let msg = "Hello Jim\n";
1606 assert_eq!(file.write(msg.as_bytes()).unwrap(), msg.len());
1607 let _ = file.seek(SeekFrom::Start(0));
1608 let mut contents = String::new();
1609 let _ = file.read_to_string(&mut contents);
1610 assert_eq!(contents, msg);
1611 }
1612
1613 let _ = filer.close(false);
1614 assert!(!filer.opened);
1615 assert!(filer
1616 .path
1617 .as_ref()
1618 .unwrap()
1619 .to_str()
1620 .unwrap()
1621 .ends_with(&format!(
1622 ".keri{}conf{}test.text",
1623 std::path::MAIN_SEPARATOR,
1624 std::path::MAIN_SEPARATOR
1625 )));
1626 assert!(filer.path.as_ref().unwrap().exists());
1627
1628 let mut filer = filer;
1630
1631 let _ = filer.reopen(None, None, None, false, false, false, None, None);
1632 assert!(filer.opened);
1633 assert!(filer
1634 .path
1635 .as_ref()
1636 .unwrap()
1637 .to_str()
1638 .unwrap()
1639 .ends_with(&format!(
1640 ".keri{}conf{}test.text",
1641 std::path::MAIN_SEPARATOR,
1642 std::path::MAIN_SEPARATOR
1643 )));
1644 assert!(filer.path.as_ref().unwrap().exists());
1645
1646 let _ = filer.reopen(None, None, None, false, true, false, None, None);
1647 assert!(filer.opened);
1648 assert!(filer
1649 .path
1650 .as_ref()
1651 .unwrap()
1652 .to_str()
1653 .unwrap()
1654 .ends_with(&format!(
1655 ".keri{}conf{}test.text",
1656 std::path::MAIN_SEPARATOR,
1657 std::path::MAIN_SEPARATOR
1658 )));
1659 assert!(filer.path.as_ref().unwrap().exists());
1660
1661 let _ = filer.reopen(None, None, None, true, true, false, None, None);
1662 assert!(filer.opened);
1663 assert!(filer
1664 .path
1665 .as_ref()
1666 .unwrap()
1667 .to_str()
1668 .unwrap()
1669 .ends_with(&format!(
1670 ".keri{}conf{}test.text",
1671 std::path::MAIN_SEPARATOR,
1672 std::path::MAIN_SEPARATOR
1673 )));
1674 assert!(filer.path.as_ref().unwrap().exists());
1675
1676 let _ = filer.reopen(None, None, None, true, false, false, None, None);
1677 assert!(filer.opened);
1678 assert!(filer
1679 .path
1680 .as_ref()
1681 .unwrap()
1682 .to_str()
1683 .unwrap()
1684 .ends_with(&format!(
1685 ".keri{}conf{}test.text",
1686 std::path::MAIN_SEPARATOR,
1687 std::path::MAIN_SEPARATOR
1688 )));
1689 assert!(filer.path.as_ref().unwrap().exists());
1690
1691 let _ = filer.close(true);
1692 assert!(!filer.path.as_ref().unwrap().exists());
1693 }
1694
1695 #[test]
1696 fn test_filing_with_temp() {
1697 {
1699 let mut filer = BaseFiler::new(
1700 "test", "", true, None, None, true, false, false, false, false, false, None, None,
1701 None,
1702 )
1703 .unwrap();
1704 assert!(filer
1705 .path
1706 .as_ref()
1707 .unwrap()
1708 .to_str()
1709 .unwrap()
1710 .starts_with("/tmp/keri_"));
1711 assert!(filer
1712 .path
1713 .as_ref()
1714 .unwrap()
1715 .to_str()
1716 .unwrap()
1717 .ends_with(&format!(
1718 "_test{}keri{}test",
1719 std::path::MAIN_SEPARATOR,
1720 std::path::MAIN_SEPARATOR
1721 )));
1722 assert!(filer.opened);
1723 assert!(filer.path.as_ref().unwrap().exists());
1724 assert!(filer.file.is_none());
1725
1726 let path = filer.path.clone();
1727 let _ = filer.close(true);
1728
1729 assert!(!path.unwrap().exists()); }
1731 }
1771
1772 #[test]
1773 fn test_filing_invalid_paths() {
1774 let name = if cfg!(windows) { "C:\\test" } else { "/test" };
1776
1777 let result = BaseFiler::new(
1778 name, "conf", false, None, None, true, false, false, false, true, false, None, None,
1779 None,
1780 );
1781
1782 assert!(result.is_err());
1783 if let Err(e) = result {
1784 assert!(matches!(e, CoreError::FilerError(_)));
1785 }
1786
1787 let base = if cfg!(windows) { "C:\\conf" } else { "/conf" };
1789
1790 let result = BaseFiler::new(
1791 "test", base, false, None, None, true, false, false, false, true, false, None, None,
1792 None,
1793 );
1794
1795 assert!(result.is_err());
1796 if let Err(e) = result {
1797 assert!(matches!(e, CoreError::FilerError(_)));
1798 }
1799 }
1800}