1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
//! HIO filing module
//!
//! File and directory management for KERI installations
use std::fs::{self, DirBuilder, File};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
use crate::hio::errors::HioError;
use crate::hio::helping::ocfn;
/// Filer instances manage file directories and files to hold KERI installation
/// specific resources like databases and configuration files.
///
/// # File/Directory Creation Mode Notes
/// `.perm` provides default restricted access permissions to directory and/or files
/// `0o1700` == 960
///
/// - Sticky bit: When this bit is set on a directory it means that a file in that
/// directory can be renamed or deleted only by the owner of the file, by the owner
/// of the directory, or by a privileged process.
/// - Owner has read permission
/// - Owner has write permission
/// - Owner has execute permission
#[derive(Debug)]
pub struct Filer {
/// Class constants - using associated constants instead of class variables
head_dir_path: PathBuf,
pub(crate) tail_dir_path: PathBuf,
pub(crate) clean_tail_dir_path: PathBuf,
alt_head_dir_path: PathBuf,
pub(crate) alt_tail_dir_path: PathBuf,
pub(crate) alt_clean_tail_dir_path: PathBuf,
pub(crate) temp_prefix: String,
temp_suffix: String,
/// Instance attributes
pub name: String,
pub base: String,
pub temp: bool,
pub path: Option<PathBuf>,
pub perm: u32,
pub filed: bool,
pub extensioned: bool,
pub mode: String,
pub fext: String,
pub file: Option<File>,
pub opened: bool,
/// Hold temp directory to keep it alive
_temp_dir: Option<TempDir>,
}
impl Filer {
// Class constants
const DEFAULT_HEAD_DIR_PATH: &'static str = "/usr/local/var";
const DEFAULT_TAIL_DIR_PATH: &'static str = "hio";
const DEFAULT_CLEAN_TAIL_DIR_PATH: &'static str = "hio/clean";
const DEFAULT_ALT_TAIL_DIR_PATH: &'static str = ".hio";
const DEFAULT_ALT_CLEAN_TAIL_DIR_PATH: &'static str = ".hio/clean";
const DEFAULT_TEMP_PREFIX: &'static str = "hio_";
const DEFAULT_TEMP_SUFFIX: &'static str = "_test";
const DEFAULT_PERM: u32 = 0o1700; // S_ISVTX | S_IRUSR | S_IWUSR | S_IXUSR
const DEFAULT_MODE: &'static str = "r+";
const DEFAULT_FEXT: &'static str = "text";
/// Create a new Filer instance
///
/// # Arguments
/// * `name` - Unique identifier of file/directory
/// * `base` - Optional directory path segment inserted before name
/// * `temp` - True means use temporary directory, clear on close
/// * `head_dir_path` - Optional head directory pathname
/// * `perm` - Optional numeric OS dir permissions
/// * `reopen` - True means (re)open with this init
/// * `clear` - True means remove directory upon close when reopening
/// * `reuse` - True means reuse self.path if already exists
/// * `clean` - True means path uses clean tail variant
/// * `filed` - True means .path is file path not directory path
/// * `extensioned` - When not filed: True means ensure .path ends with fext
/// * `mode` - File open mode when filed
/// * `fext` - File extension when filed or extensioned
pub fn new(
name: Option<String>,
base: Option<String>,
temp: Option<bool>,
head_dir_path: Option<PathBuf>,
perm: Option<u32>,
reopen: Option<bool>,
clear: Option<bool>,
reuse: Option<bool>,
clean: Option<bool>,
filed: Option<bool>,
extensioned: Option<bool>,
mode: Option<String>,
fext: Option<String>,
) -> Result<Self, HioError> {
let name = name.unwrap_or_else(|| "main".to_string());
let base = base.unwrap_or_default();
// Validate relative paths
if Path::new(&name).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative name path: {}",
name
)));
}
if !base.is_empty() && Path::new(&base).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative base path: {}",
base
)));
}
let alt_head_dir_path = dirs::home_dir().unwrap_or_else(|| PathBuf::from("~"));
let mut filer = Filer {
head_dir_path: head_dir_path
.unwrap_or_else(|| PathBuf::from(Self::DEFAULT_HEAD_DIR_PATH)),
tail_dir_path: PathBuf::from(Self::DEFAULT_TAIL_DIR_PATH),
clean_tail_dir_path: PathBuf::from(Self::DEFAULT_CLEAN_TAIL_DIR_PATH),
alt_head_dir_path,
alt_tail_dir_path: PathBuf::from(Self::DEFAULT_ALT_TAIL_DIR_PATH),
alt_clean_tail_dir_path: PathBuf::from(Self::DEFAULT_ALT_CLEAN_TAIL_DIR_PATH),
temp_prefix: Self::DEFAULT_TEMP_PREFIX.to_string(),
temp_suffix: Self::DEFAULT_TEMP_SUFFIX.to_string(),
name,
base,
temp: temp.unwrap_or(false),
path: None,
perm: perm.unwrap_or(Self::DEFAULT_PERM),
filed: filed.unwrap_or(false),
extensioned: extensioned.unwrap_or(false),
mode: mode.unwrap_or_else(|| Self::DEFAULT_MODE.to_string()),
fext: fext.unwrap_or_else(|| Self::DEFAULT_FEXT.to_string()),
file: None,
opened: false,
_temp_dir: None,
};
if reopen.unwrap_or(true) {
filer.reopen(
None,
None,
None,
clear.unwrap_or(false),
reuse.unwrap_or(false),
clean.unwrap_or(false),
None,
None,
)?;
}
Ok(filer)
}
/// Open if closed or close and reopen if opened or create and open if not
///
/// # Arguments
/// * `temp` - Optional temp mode override
/// * `head_dir_path` - Optional head directory pathname override
/// * `perm` - Optional permissions override
/// * `clear` - True means remove directory upon close
/// * `reuse` - True means reuse self.path if already exists
/// * `clean` - True means path uses clean tail variant
/// * `mode` - Optional file open mode override
/// * `fext` - Optional file extension override
pub fn reopen(
&mut self,
temp: Option<bool>,
head_dir_path: Option<PathBuf>,
perm: Option<u32>,
clear: bool,
reuse: bool,
clean: bool,
mode: Option<String>,
fext: Option<String>,
) -> Result<bool, HioError> {
self.close(clear)?;
// Update parameters if provided
if let Some(temp) = temp {
self.temp = temp;
}
if let Some(head_dir_path) = head_dir_path {
self.head_dir_path = head_dir_path;
}
if let Some(perm) = perm {
self.perm = perm;
}
if let Some(mode) = mode {
self.mode = mode;
}
if let Some(fext) = fext {
self.fext = fext;
}
let should_remake = self.path.is_none() || !self.path.as_ref().unwrap().exists() || !reuse;
if should_remake {
let (path, file, temp_dir) = self.remake(
&self.name.clone(),
&self.base.clone(),
Some(self.temp),
Some(self.head_dir_path.clone()),
Some(self.perm),
clean,
self.filed,
self.extensioned,
Some(self.mode.clone()),
Some(self.fext.clone()),
)?;
self.path = Some(path);
self.file = file;
self._temp_dir = temp_dir;
} else if self.filed && self.path.is_some() {
// File exists, just open it
let path = self.path.as_ref().unwrap();
let file = ocfn(
path,
self.mode.contains('r'),
self.mode.contains('w') || self.mode.contains('+'),
self.mode.contains('a'),
self.mode.contains('w') && !self.mode.contains('+'),
true,
false,
self.perm,
)?;
self.file = Some(file);
}
self.opened = if !self.filed {
true
} else {
self.file.is_some()
};
Ok(self.opened)
}
/// Make and return (path, file, temp_dir) by opening or creating directory or file at path
#[allow(clippy::too_many_arguments)]
pub fn remake(
&self,
name: &str,
base: &str,
temp: Option<bool>,
head_dir_path: Option<PathBuf>,
perm: Option<u32>,
clean: bool,
filed: bool,
extensioned: bool,
mode: Option<String>,
fext: Option<String>,
) -> Result<(PathBuf, Option<File>, Option<TempDir>), HioError> {
// Validate relative paths
if Path::new(name).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative name path: {}",
name
)));
}
if !base.is_empty() && Path::new(base).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative base path: {}",
base
)));
}
let temp = temp.unwrap_or(false);
let head_dir_path = head_dir_path.unwrap_or_else(|| self.head_dir_path.clone());
let perm = perm.unwrap_or(self.perm);
let mode = mode.unwrap_or_else(|| self.mode.clone());
let fext = fext.unwrap_or_else(|| self.fext.clone());
let tail_dir_path = if clean {
&self.clean_tail_dir_path
} else {
&self.tail_dir_path
};
let alt_tail_dir_path = if clean {
&self.alt_clean_tail_dir_path
} else {
&self.alt_tail_dir_path
};
// Add extension if needed
let final_name = if filed || extensioned {
let path = Path::new(name);
if path.extension().is_none() {
format!("{}.{}", name, fext)
} else {
name.to_string()
}
} else {
name.to_string()
};
let mut temp_dir_holder = None;
let mut file = None;
let path = if temp {
// Create temporary directory
let temp_dir = tempfile::Builder::new()
.prefix(&self.temp_prefix)
.suffix(&self.temp_suffix)
.tempdir()
.map_err(HioError::IoError)?;
let temp_path = temp_dir
.path()
.join(tail_dir_path)
.join(base)
.join(&final_name);
// Handle clean option for temp
if clean && temp_path.exists() {
if temp_path.is_file() {
if filed || extensioned {
fs::remove_file(&temp_path).map_err(HioError::IoError)?;
} else if let Some(parent) = temp_path.parent() {
fs::remove_dir_all(parent).map_err(HioError::IoError)?;
}
} else {
fs::remove_dir_all(&temp_path).map_err(HioError::IoError)?;
}
}
// Create directory structure and file if needed
if filed || extensioned {
if let Some(parent) = temp_path.parent() {
DirBuilder::new()
.mode(perm)
.recursive(true)
.create(parent)
.map_err(HioError::IoError)?;
}
if filed {
file = Some(ocfn(
&temp_path,
mode.contains('r'),
mode.contains('w') || mode.contains('+'),
mode.contains('a'),
mode.contains('w') && !mode.contains('+'),
true,
false,
perm,
)?);
}
} else {
DirBuilder::new()
.mode(perm)
.recursive(true)
.create(&temp_path)
.map_err(HioError::IoError)?;
}
temp_dir_holder = Some(temp_dir);
temp_path
} else {
// Persistent directory
let mut persistent_path = head_dir_path
.join(tail_dir_path)
.join(base)
.join(&final_name);
// Handle clean option
if clean && persistent_path.exists() {
if persistent_path.is_file() {
if filed {
fs::remove_file(&persistent_path).map_err(HioError::IoError)?;
} else if let Some(parent) = persistent_path.parent() {
fs::remove_dir_all(parent).map_err(HioError::IoError)?;
}
} else {
fs::remove_dir_all(&persistent_path).map_err(HioError::IoError)?;
}
}
// Try to create at primary path, fall back to alt if needed
let result = self.try_create_path(&persistent_path, filed, extensioned, &mode, perm);
match result {
Ok(f) => {
file = f;
}
Err(_) => {
// Fall back to alternative path
persistent_path = self
.alt_head_dir_path
.join(alt_tail_dir_path)
.join(base)
.join(&final_name);
file =
self.try_create_path(&persistent_path, filed, extensioned, &mode, perm)?;
}
}
// Set permissions on the final path
if !extensioned {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(perm);
fs::set_permissions(&persistent_path, perms).map_err(HioError::IoError)?;
}
}
persistent_path
};
Ok((path, file, temp_dir_holder))
}
/// Helper method to try creating path with fallback logic
fn try_create_path(
&self,
path: &Path,
filed: bool,
extensioned: bool,
mode: &str,
perm: u32,
) -> Result<Option<File>, HioError> {
if !path.exists() {
// Path doesn't exist, create it
if filed || extensioned {
if let Some(parent) = path.parent() {
DirBuilder::new()
.mode(perm)
.recursive(true)
.create(parent)
.map_err(HioError::IoError)?;
}
if filed {
let file = ocfn(
path,
mode.contains('r'),
mode.contains('w') || mode.contains('+'),
mode.contains('a'),
mode.contains('w') && !mode.contains('+'),
true,
false,
perm,
)?;
Ok(Some(file))
} else {
Ok(None)
}
} else {
DirBuilder::new()
.mode(perm)
.recursive(true)
.create(path)
.map_err(HioError::IoError)?;
Ok(None)
}
} else {
// Path exists, check access and open file if needed
if filed {
let file = ocfn(
path,
mode.contains('r'),
mode.contains('w') || mode.contains('+'),
mode.contains('a'),
mode.contains('w') && !mode.contains('+'),
true,
false,
perm,
)?;
Ok(Some(file))
} else {
Ok(None)
}
}
}
/// Check if path exists for a given set of parameters
pub fn exists(
&self,
name: &str,
base: &str,
head_dir_path: Option<&Path>,
clean: bool,
filed: bool,
extensioned: bool,
fext: Option<&str>,
) -> Result<bool, HioError> {
// Validate relative paths
if Path::new(name).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative name path: {}",
name
)));
}
if !base.is_empty() && Path::new(base).is_absolute() {
return Err(HioError::FilerError(format!(
"Not relative base path: {}",
base
)));
}
let head_dir_path = head_dir_path.unwrap_or(&self.head_dir_path);
let fext = fext.unwrap_or(&self.fext);
let tail_dir_path = if clean {
&self.clean_tail_dir_path
} else {
&self.tail_dir_path
};
let alt_tail_dir_path = if clean {
&self.alt_clean_tail_dir_path
} else {
&self.alt_tail_dir_path
};
// Add extension if needed
let final_name = if filed || extensioned {
let path = Path::new(name);
if path.extension().is_none() {
format!("{}.{}", name, fext)
} else {
name.to_string()
}
} else {
name.to_string()
};
// Check primary path
let primary_path = head_dir_path
.join(tail_dir_path)
.join(base)
.join(&final_name);
if primary_path.exists() {
return Ok(true);
}
// Check alternative path
let alt_path = self
.alt_head_dir_path
.join(alt_tail_dir_path)
.join(base)
.join(&final_name);
Ok(alt_path.exists())
}
/// Close file if any and optionally remove directory or file at path
pub fn close(&mut self, clear: bool) -> Result<bool, HioError> {
// Close file if open
if self.file.is_some() {
self.file = None; // File is automatically closed when dropped
}
self.opened = false;
if clear {
self.clear_path()?;
}
Ok(!self.opened) // True means closed
}
/// Remove directory/file at end of path
fn clear_path(&mut self) -> Result<(), HioError> {
if let Some(path) = &self.path {
if path.exists() {
if path.is_file() {
// Remove file
fs::remove_file(path).map_err(HioError::IoError)?;
self.file = None;
// If temp, also remove parent directory
if self.temp {
if let Some(parent) = path.parent() {
fs::remove_dir_all(parent).map_err(HioError::IoError)?;
}
}
} else if self.extensioned {
// Path end has file extension, remove as file
fs::remove_file(path).map_err(HioError::IoError)?;
// If temp, also remove parent directory
if self.temp {
if let Some(parent) = path.parent() {
fs::remove_dir_all(parent).map_err(HioError::IoError)?;
}
}
} else {
// Remove directory and all contents
fs::remove_dir_all(path).map_err(HioError::IoError)?;
}
}
}
// Clear temp directory holder to allow cleanup
self._temp_dir = None;
Ok(())
}
}
impl Drop for Filer {
fn drop(&mut self) {
// Ensure cleanup on drop
let _ = self.close(self.temp);
}
}
// Simple context manager - no builder needed
pub struct FilerContext {
pub filer: Filer,
clear_on_drop: bool,
}
impl FilerContext {
pub fn new(filer: Filer, clear: bool) -> Self {
let clear_on_drop = filer.temp || clear;
Self {
filer,
clear_on_drop,
}
}
}
impl Drop for FilerContext {
fn drop(&mut self) {
let _ = self.filer.close(self.clear_on_drop);
}
}
impl std::ops::Deref for FilerContext {
type Target = Filer;
fn deref(&self) -> &Self::Target {
&self.filer
}
}
impl std::ops::DerefMut for FilerContext {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.filer
}
}
pub fn open_filer(
name: Option<String>,
temp: Option<bool>,
reopen: Option<bool>,
clear: Option<bool>,
) -> Result<FilerContext, HioError> {
let name = name.unwrap_or_else(|| "test".to_string());
let temp = temp.unwrap_or(true);
let reopen = reopen.unwrap_or(true);
let clear = clear.unwrap_or(false);
let filer = Filer::new(
Some(name), // name
None, // base
Some(temp), // temp - this is the key fix
None, // head_dir_path
None, // perm
Some(reopen), // reopen
Some(clear), // clear
None, // reuse
None, // clean
None, // filed
None, // extensioned
None, // mode
None, // fext
)?;
Ok(FilerContext::new(filer, clear))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use std::sync::Mutex;
// Force tests to run sequentially to avoid race conditions
static TEST_MUTEX: Mutex<()> = Mutex::new(());
fn cleanup_all_test_dirs() {
// Clean up ALL possible test directories more thoroughly
let dirs_to_clean = vec![
"/usr/local/var/hio", // Clean entire hio directory
"/usr/local/var/hio/test",
"/usr/local/var/hio/clean",
"/usr/local/var/hio/clean/test",
"/usr/local/var/hio/conf",
"/usr/local/var/hio/conf/test.text",
];
for dir in dirs_to_clean {
let path = PathBuf::from(dir);
if path.exists() {
if path.is_file() {
let _ = fs::remove_file(&path);
} else {
let _ = fs::remove_dir_all(&path);
}
}
}
if let Some(home) = dirs::home_dir() {
let alt_dirs = vec![
home.join(".hio"), // Clean entire .hio directory
home.join(".hio/test"),
home.join(".hio/clean"),
home.join(".hio/clean/test"),
home.join(".hio/conf"),
home.join(".hio/conf/test.text"),
];
for dir in alt_dirs {
if dir.exists() {
if dir.is_file() {
let _ = fs::remove_file(&dir);
} else {
let _ = fs::remove_dir_all(&dir);
}
}
}
}
// Small delay to ensure filesystem operations complete
std::thread::sleep(std::time::Duration::from_millis(10));
}
#[test]
fn test_filing() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
cleanup_all_test_dirs();
// Test basic directory creation
let exists_before = {
let filer = Filer::new(
Some("test".to_string()),
None,
None,
None,
None,
Some(false), // reopen=false
None,
None,
None,
None,
None,
None,
None,
)?;
filer.exists("test", "", None, false, false, false, None)?
};
assert!(!exists_before);
// Test with reopen=true (default)
let mut filer = Filer::new(
Some("test".to_string()),
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)?;
assert!(filer.exists("test", "", None, false, false, false, None)?);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/test"));
assert!(filer.opened);
assert!(filer.path.as_ref().unwrap().exists());
assert!(filer.file.is_none());
filer.close(false)?;
assert!(!filer.opened);
// Verify path exists after close
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen without reuse (remake)
filer.reopen(None, None, None, false, false, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen with reuse=true
filer.reopen(None, None, None, false, true, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen with reuse=true, clear=true (should remake even with reuse)
filer.reopen(None, None, None, true, true, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen with clear=true (should remake)
filer.reopen(None, None, None, true, false, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
// Test close with clear=true
let path_before_clear = filer.path.clone();
filer.close(true)?;
assert!(!path_before_clear.unwrap().exists());
cleanup_all_test_dirs();
Ok(())
}
#[test]
fn test_filing_clean() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
cleanup_all_test_dirs();
// Test clean path variant
let exists_before = {
let filer = Filer::new(
Some("test".to_string()),
None,
None,
None,
None,
Some(false), // reopen=false
None,
None,
Some(true), // clean=true
None,
None,
None,
None,
)?;
filer.exists("test", "", None, true, false, false, None)?
};
assert!(!exists_before);
let mut filer = Filer::new(
Some("test".to_string()),
None,
None,
None,
None,
None,
None,
None,
Some(true), // clean=true
None,
None,
None,
None,
)?;
assert!(filer.exists("test", "", None, true, false, false, None)?);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/clean/test"));
assert!(filer.opened);
assert!(filer.path.as_ref().unwrap().exists());
assert!(filer.file.is_none());
filer.close(false)?;
assert!(!filer.opened);
// Test various reopen scenarios with clean=true
filer.reopen(None, None, None, false, false, true, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/clean/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, false, true, true, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/clean/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, true, true, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/clean/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, false, true, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/clean/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.close(true)?;
assert!(!filer.path.as_ref().unwrap().exists());
cleanup_all_test_dirs();
Ok(())
}
#[test]
fn test_filing_alt_path() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
cleanup_all_test_dirs();
// Test with alt path by using a restricted head directory
let restricted_head = PathBuf::from("/root/hio/hio");
let exists_before = {
let filer = Filer::new(
Some("test".to_string()),
None,
None,
Some(restricted_head.clone()),
None,
Some(false), // reopen=false
None,
None,
None,
None,
None,
None,
None,
)?;
filer.exists(
"test",
"",
Some(&restricted_head),
false,
false,
false,
None,
)?
};
assert!(!exists_before);
let mut filer = Filer::new(
Some("test".to_string()),
None,
None,
Some(restricted_head.clone()),
None,
None,
None,
None,
None,
None,
None,
None,
None,
)?;
assert!(filer.exists(
"test",
"",
Some(&restricted_head),
false,
false,
false,
None
)?);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.opened);
assert!(filer.path.as_ref().unwrap().exists());
assert!(filer.file.is_none());
filer.close(false)?;
assert!(!filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
// Test various reopen scenarios with alt path
filer.reopen(None, None, None, false, false, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, false, true, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, true, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, false, false, None, None)?;
assert!(filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/test"));
assert!(filer.path.as_ref().unwrap().exists());
filer.close(true)?;
assert!(!filer.path.as_ref().unwrap().exists());
cleanup_all_test_dirs();
Ok(())
}
#[test]
fn test_filing_with_file() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
cleanup_all_test_dirs();
// Test Filer with file not dir
let exists_before = {
let filer = Filer::new(
Some("test".to_string()),
Some("conf".to_string()),
None,
None,
None,
Some(false), // reopen=false
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
)?;
filer.exists("test", "conf", None, false, true, false, None)?
};
assert!(!exists_before);
let mut filer = Filer::new(
Some("test".to_string()),
Some("conf".to_string()),
None,
None,
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
)?;
assert!(filer.exists("test", "conf", None, false, true, false, None)?);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.opened);
assert!(filer.path.as_ref().unwrap().exists());
assert!(filer.file.is_some());
// Test file operations
if let Some(ref mut file) = filer.file {
let msg = "Hello Jim\n";
let bytes_written = file.write(msg.as_bytes())?;
assert_eq!(bytes_written, msg.len());
file.seek(SeekFrom::Start(0))?;
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
assert_eq!(buffer, msg);
}
filer.close(false)?;
assert!(!filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen scenarios with file
filer.reopen(None, None, None, false, false, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, false, true, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, true, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, false, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains("hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.close(true)?;
assert!(!filer.path.as_ref().unwrap().exists());
cleanup_all_test_dirs();
Ok(())
}
#[test]
fn test_filing_with_file_alt_path() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
cleanup_all_test_dirs();
// Test Filer with file not dir and with Alt path
let restricted_head = PathBuf::from("/root/hio");
let exists_before = {
let filer = Filer::new(
Some("test".to_string()),
Some("conf".to_string()),
None,
Some(restricted_head.clone()),
None,
Some(false), // reopen=false
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
)?;
filer.exists(
"test",
"conf",
Some(&restricted_head),
false,
true,
false,
None,
)?
};
assert!(!exists_before);
let mut filer = Filer::new(
Some("test".to_string()),
Some("conf".to_string()),
None,
Some(restricted_head.clone()),
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
)?;
assert!(filer.exists(
"test",
"conf",
Some(&restricted_head),
false,
true,
false,
None
)?);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.opened);
assert!(filer.path.as_ref().unwrap().exists());
assert!(filer.file.is_some());
// Test file operations
if let Some(ref mut file) = filer.file {
let msg = "Hello Jim\n";
let bytes_written = file.write(msg.as_bytes())?;
assert_eq!(bytes_written, msg.len());
file.seek(SeekFrom::Start(0))?;
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
assert_eq!(buffer, msg);
}
filer.close(false)?;
assert!(!filer.opened);
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
// Test reopen scenarios
filer.reopen(None, None, None, false, false, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, false, true, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, true, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.reopen(None, None, None, true, false, false, None, None)?;
assert!(filer.opened);
assert!(filer.file.is_some());
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.contains(".hio/conf/test.text"));
assert!(filer.path.as_ref().unwrap().exists());
filer.close(true)?;
assert!(!filer.path.as_ref().unwrap().exists());
cleanup_all_test_dirs();
Ok(())
}
#[test]
fn test_open_filer_context() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
// Test open_filer with defaults (temp=true)
let temp_path = {
let filer_ctx = open_filer(None, None, None, None)?;
// Check temp directory structure
let path_str = filer_ctx.path.as_ref().unwrap().to_string_lossy();
assert!(path_str.contains("hio_"));
assert!(path_str.contains("_test/hio/test"));
assert!(filer_ctx.opened);
assert!(filer_ctx.path.as_ref().unwrap().exists());
assert!(filer_ctx.file.is_none());
filer_ctx.path.clone()
}; // filer_ctx is dropped here, should clear temp files
Ok(())
}
#[test]
fn test_open_filer_context_filed() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
// Test open_filer with filed=true but temp=true
let filer = Filer::new(
Some("test".to_string()),
None, // base
Some(true), // temp=true
None, // head_dir_path
None, // perm
None, // reopen (default true)
None, // clear
None, // reuse
None, // clean
Some(true), // filed=true
None, // extensioned
None, // mode
None, // fext
)?;
let filer_ctx = FilerContext::new(filer, false);
let path_str = filer_ctx.path.as_ref().unwrap().to_string_lossy();
// More flexible assertions for temp directories
assert!(filer_ctx.temp, "Should be using temp directory");
assert!(path_str.contains("test.text"), "Should end with test.text");
assert!(filer_ctx.opened);
assert!(filer_ctx.path.as_ref().unwrap().exists());
assert!(filer_ctx.file.is_some());
Ok(())
}
#[test]
fn test_bad_file_paths() {
let _guard = TEST_MUTEX.lock().unwrap();
// Test absolute name path (should fail)
let result = Filer::new(
Some("/test".to_string()),
Some("conf".to_string()),
None,
None,
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
);
assert!(matches!(result, Err(HioError::FilerError(_))));
// Test absolute base path (should fail)
let result = Filer::new(
Some("test".to_string()),
Some("/conf".to_string()),
None,
None,
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
None,
);
assert!(matches!(result, Err(HioError::FilerError(_))));
}
#[test]
fn test_filer_extension_handling() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
// Test that extension is added when filed=true and no extension provided
let filer = Filer::new(
Some("testfile".to_string()), // no extension
None,
Some(true), // temp=true
None,
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
Some("dat".to_string()), // custom extension
)?;
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.ends_with("testfile.dat"));
assert!(filer.opened);
assert!(filer.file.is_some());
Ok(())
}
#[test]
fn test_filer_with_existing_extension() -> Result<(), HioError> {
let _guard = TEST_MUTEX.lock().unwrap();
// Test that existing extension is preserved
let filer = Filer::new(
Some("testfile.json".to_string()), // has extension
None,
Some(true), // temp=true
None,
None,
None,
None,
None,
None,
Some(true), // filed=true
None,
None,
Some("dat".to_string()), // different extension - should be ignored
)?;
assert!(filer
.path
.as_ref()
.unwrap()
.to_string_lossy()
.ends_with("testfile.json"));
assert!(filer.opened);
assert!(filer.file.is_some());
Ok(())
}
}