tree-type 0.4.5

Rust macros for creating type-safe filesystem tree structures
Documentation
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
//! Type-safe path navigation macros for Rust projects with fixed directory structures.
//!
//! # Quick Example
//!
//! Basic usage example showing type-safe navigation and setup.
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! // Define your directory structure
//! tree_type! {
//!     ProjectRoot {
//!         src/ {
//!             lib("lib.rs"),
//!             main("main.rs")
//!         },
//!         target/,
//!         readme("README.md")
//!     }
//! }
//!
//! // Each path gets its own type (which cna be overridden)
//! fn process_source(src: &ProjectRootSrc) -> std::io::Result<()> {
//!     let lib_rs_file = src.lib();      // ProjectRootSrcLib
//!     let main_rs_file = src.main();    // ProjectRootSrcMain
//!     Ok(())
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let project_root = temp_dir.path().join("project");
//! let project = ProjectRoot::new(project_root)?;
//! let src = project.src();           // ProjectRootSrc
//! let readme = project.readme();     // ProjectRootReadme
//!
//! process_source(&src)?;
//! // process_source(&readme)?;       // would be a compilation error
//!
//! // Setup entire structure
//! project.setup();                   // Creates src/, target/, and all files
//! # Ok(())
//! # }
//! ```
//!
//! # Overview
//!
//! `tree-type` provides macros for creating type-safe filesystem path types:
//!
//! - `tree_type!` - Define a tree of path types with automatic navigation methods
//! - `dir_type!` - Convenience wrapper for simple directory types (no children)
//! - `file_type!` - Convenience macro for simple file types (single file with operations)
//!
//! # Features
//!
//! - **Type Safety**: Each path in your directory structure gets its own type
//! - **Navigation Methods**: Automatic generation of navigation methods
//! - **Custom Names**: Support for custom type names and filenames
//! - **Dynamic IDs**: ID-based navigation for dynamic directory structures
//! - **Rich Operations**: Built-in filesystem operations (create, read, write, remove, etc.)
//!
//! # Installation
//!
//! Add to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! tree-type = "0.1.0"
//! ```
//!
//! ## Features
//!
//! All features are opt-in to minimize dependencies:
//!
//! | feature | description | dependencies |
//! |---|---|---|
//! | `serde` |Adds Serialize/Deserialize derives to all path types | `serde` |
//! | `enhanced-errors` | Enhanced error messages for filesystem operations | `fs-err`, `path_facts` |
//! | `walk` | Directory traversal methods | `walkdir` |
//! | `pattern-validation` | Regex pattern validation for dynamic ID blocks | `regex` |
//!
//! ```toml
//! # With all features
//! [dependencies]
//! tree-type = { version = "0.1.0", features = ["serde", "enhanced-errors", "walk", "pattern-validation"] }
//! ```
//!
//! # Usage Examples
//!
//! ## Basic Tree Structure
//!
//! Specify the type that represent the root of your tree, it will be a directory. Then within
//! `{}` specify the identifiers of the files and directories that are children of the
//! root. Directories as identified by having a trailing `/` after their identifier, otherwise
//! they are files.
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! tree_type! {
//!     ProjectRoot {
//!         src/,
//!         target/,
//!         readme("README.md")
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let project_root = temp_dir.path().join("project");
//! let project = ProjectRoot::new(project_root.clone())?;
//! let src = project.src();           // ProjectRootSrc
//! let readme = project.readme();     // ProjectRootReadme
//!
//! assert_eq!(src.as_path(), project_root.join("src"));
//! assert_eq!(readme.as_path(), project_root.join("README.md"));
//! # Ok(())
//! # }
//! ```
//!
//! ## Custom Filenames
//!
//! By default the filename will be the same as the identifier, (as long is it is valid for
//! the filesystem).
//!
//! To specify an alternative filename, e.g. one where the filename isn't a valid Rust
//! identifier, specify the filename as `identifier/("file-name")`. Note that the directory
//! indicator (`/`) comes after the identifier, not the directory name.
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! tree_type! {
//!     UserHome {
//!         ssh/(".ssh") {
//!             ecdsa_public("id_ecdsa.pub"),
//!             ed25519_public("id_ed25519.pub")
//!         }
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let home_dir = temp_dir.path().join("home");
//! let home = UserHome::new(home_dir.clone())?;
//! let ssh = home.ssh();                    // UserHomeSsh (maps to .ssh)
//! let key = ssh.ecdsa_public();            // UserHomeSshEcdsaPublic (maps to id_ecdsa.pub)
//!
//! assert_eq!(ssh.as_path(), home_dir.join(".ssh"));
//! assert_eq!(key.as_path(), home_dir.join(".ssh/id_ecdsa.pub"));
//! # Ok(())
//! # }
//! ```
//!
//! ## Custom Type Names
//!
//! `tree_type` will generate type names for each file and directory by appending the capitalised
//! identifier to the parent type, unless you override this with `as`.
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! tree_type! {
//!     ProjectRoot {
//!         src/ {              // as ProjectRootSrc
//!             main("main.rs") // as ProjectRootSrcMain
//!         },
//!         readme("README.md") as ReadmeFile // default would have been ProjectRootReadme
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let project_dir = temp_dir.path().join("project");
//! let project = ProjectRoot::new(project_dir)?;
//!
//! let src: ProjectRootSrc = project.src();
//! let main: ProjectRootSrcMain = src.main();
//! let readme: ReadmeFile = project.readme();
//! # Ok(())
//! }
//! ```
//!
//! ## Default File Content
//!
//! Create files with default content if they don't exist:
//!
//! ```
//! use tree_type::{tree_type, CreateDefaultOutcome};
//! # use tempfile::TempDir;
//!
//! fn default_config(file: &ProjectRootConfig) -> Result<String, std::io::Error> {
//!     Ok(format!("# Config for {}\n", file.as_path().display()))
//! }
//!
//! tree_type! {
//!     ProjectRoot {
//!         #[default("CHANGELOG\n")]
//!         changelog("CHANGELOG"),
//!
//!         #[default("# My Project\n")] // create file with the string as content
//!         readme("README.md"),
//!
//!         #[default(default_config)]
//!         config("config.toml"),
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let project_path = temp_dir.path();
//! let project = ProjectRoot::new(project_path)?;
//!
//! let changelog = project.changelog();
//! let readme = project.readme();
//! let config = project.config();
//!
//! changelog.write("existing content")?;
//!
//! assert!(changelog.exists()); // an existing file
//!
//! assert!(!readme.exists());   // don't exist yet
//! assert!(!config.exists());
//!
//! match project.setup() {
//!     Ok(_) => println!("Project structure created successfully"),
//!     Err(errors) => {
//!         for error in errors {
//!             match error {
//!                 tree_type::BuildError::Directory(path, e) => eprintln!("Dir error at {:?}: {}", path, e),
//!                 tree_type::BuildError::File(path, e) => eprintln!("File error at {:?}: {}", path, e),
//!             }
//!         }
//!     }
//! }
//! assert!(readme.exists());    // created and set to default content
//! assert_eq!(readme.read_to_string()?, "# My Project\n");
//!
//! assert!(config.exists());    // created and function sets the content
//! assert!(config.read_to_string()?.starts_with("# Config for "));
//!
//! assert!(changelog.exists()); // existing file is left unchanged
//! assert_eq!(changelog.read_to_string()?, "existing content");
//! # Ok(())
//! # }
//! ```
//! The function `f` in `#[default(f)]`:
//!
//! - Takes `&FileType` as parameter (self-aware, can access own path)
//! - Returns `Result<String, E>` where E can be any error type
//! - Allows network requests, file I/O, parsing, etc.
//! - Errors are propagated to the caller
//!
//! The `setup()` method:
//!
//! - Creates all directories in the tree
//! - Creates all files with a `#[default(function)]` attribute
//! - Collects all errors and continues processing (doesn't fail fast)
//! - Returns `Result<(), Vec<BuildError>>` with all errors if any occurred
//! - Skips files that already exist (won't overwrite)
//!
//! ### Dynamic ID
//!
//! Dynamic ID support allows you to define parameterized paths in your directory
//! structure where the actual directory/file names are determined at runtime using
//! ID parameters.
//!
//! ```
//! use tree_type::tree_type;
//! use tree_type::ValidatorResult;
//! # use tempfile::TempDir;
//!
//! fn is_valid_log_name(log_file: &LogFile) -> ValidatorResult {
//!     let mut result = ValidatorResult::default();
//!     let file_name = log_file.file_name();
//!     if !file_name.starts_with("log-") {
//!         result.errors.push(format!("log_file name '{file_name}' must start with 'log-'"));
//!     }
//!     result
//! }
//!
//! tree_type! {
//!     Root {
//!         users/ {
//!             [user_id: String]/ as UserDir {  // Dynamic directory
//!                 #[required]
//!                 #[default("{}")]
//!                 profile("profile.json"),
//!                 settings("settings.toml"),
//!                 posts/ {
//!                     [post_id: u32] as PostFile // nested dynamic
//!                 }
//!             }
//!         },
//!         logs/ {
//!             #[validate(is_valid_log_name)]
//!             [log_name: String] as LogFile    // Dynamic file (no trailing slash)
//!         }
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let root_dir = temp_dir.path().join("root");
//! let root = Root::new(root_dir.clone())?;
//!
//! let user_dir: UserDir = root.users().user_id("42");
//! let _result = user_dir.setup();
//! assert_eq!(user_dir.as_path(), root_dir.join("users/42"));
//! assert!(user_dir.profile().exists()); // required + default
//! assert!(!user_dir.settings().exists()); // not required and/or no default
//! assert_eq!(user_dir.settings().as_path(), root_dir.join("users/42/settings.toml"));
//!
//! let log_file = root.logs().log_name("foo.log");
//! assert_eq!(log_file.as_path(), root_dir.join("logs/foo.log"));
//! assert!(!log_file.exists()); // we need to create this ourselves
//!
//! // FIXME: can't validate a filename until the file exists
//! log_file.write("bar")?;
//!
//! // validation fails because `foo.log` doesn't start with `log-`
//! // FIXME: `validate()` should return a `Result<T, E>` rather then a ValidationReport
//! let report = root.logs().validate();
//! assert!(!report.is_ok());
//! assert_eq!(report.errors.len(), 1);
//! assert!(report.errors[0].message.contains("must start with 'log-'"));
//! # Ok(())
//! # }
//! ```
//!
//! # File Type Macro
//!
//! The `file_type` macro provides for when you only need to work with a single file rather
//! than a directory structure. You would use it instead of `tree_type` when you only need to
//! manage one file, not a directory tree, or when you need to treat several files in a directory
//! tree in a more generic way.
//!
//! The `tree_type` macro uses the `file_type` macro to represent any files defined in it.
//!
//! ```
//! use tree_type::file_type;
//!
//! file_type!(ConfigFile);
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = tempfile::TempDir::new()?;
//! # let root_dir = temp_dir.path().join("root");
//! let config_file = ConfigFile::new(root_dir.join("config.toml"))?;
//!
//! config_file.write("# new config file")?;
//! assert!(config_file.exists());
//! let config = config_file.read_to_string()?;
//! assert_eq!(config, "# new config file");
//! # Ok(())
//! # }
//! ```
//!
//! ## File Operations
//!
//! File types support:
//!
//! - `display()` - Get Display object for formatting paths
//! - `read_to_string()` - Read file as string
//! - `read()` - Read file as bytes
//! - `write()` - Write content to file
//! - `create_default()` - Create file with default content if it doesn't exist
//! - `exists()` - Check if file exists
//! - `remove()` - Delete file
//! - `fs_metadata()` - Get file metadata
//! - `secure()` (Unix only) - Set permissions to 0o600
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! tree_type! {
//!     ProjectRoot {
//!         readme("README.md") as Readme
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let project_dir = temp_dir.path().join("project");
//! let project = ProjectRoot::new(project_dir)?;
//! let readme = project.readme();
//!
//! // Write content to file
//! readme.write("# Hello World")?;
//!
//! assert!(readme.exists());
//!
//! // Read content back
//! let content = readme.read_to_string()?;
//! assert_eq!(content, "# Hello World");
//! # Ok(())
//! # }
//! ```
//!
//! # Directory Type Macro
//!
//! The `dir_type` macro provides for when you only need to work with a single directory rather
//! than a nested directory structure. You would use it instead of `tree_type` when you only need
//! to manage one directory, not a directory tree, or when you need to treat several directories
//! in a more generic way.
//!
//! The `tree_type` macro uses the `dir_type` macro to represent the directories defined in it.
//!
//! ```
//! use tree_type::dir_type;
//!
//! dir_type!(ConfigDir);
//!
//! fn handle_config(dir: &ConfigDir) -> std::io::Result<()> {
//!     if dir.exists() {
//!         // ...
//!     } else {
//!         // ...
//!     }
//!     Ok(())
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = tempfile::TempDir::new()?;
//! # let root_dir = temp_dir.path().join("root");
//! let config_dir = ConfigDir::new(root_dir.join("config"))?;
//!
//! config_dir.create_all()?;
//! handle_config(&config_dir)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Directory Operations
//!
//! Directory types support:
//!
//! -  `display()` - Get Display object for formatting paths
//! -  `create_all()` - Create directory and parents
//! -  `create()` - [deprecated] Create directory (parent must exist)
//! -  `setup()` - [deprecated] Create directory and all child directories/files recursively
//! -  `validate()` - [deprecated] Validate tree structure without creating anything
//! -  `ensure()` - Validate and create missing required paths
//! -  `exists()` - Check if directory exists
//! -  `read_dir()` - List directory contents
//! -  `remove()` - Remove empty directory
//! -  `remove_all()` - Remove directory recursively
//! -  `fs_metadata()` - Get directory metadata
//!
//! With `walk` feature enabled:
//!
//! -  `walk_dir()` - Walk directory tree (returns iterator)
//! -  `walk()` - Walk with callbacks for dirs/files
//! -  `size_in_bytes()` - Calculate total size recursively
//!
//! # Symbolic links
//!
//! Create (soft) symbolic links to other files or directories in the tree.
//!
//! This feature is only available on unix-like environments (i.e. `#[cfg(unix)]`).
//!
//! ```
//! use tree_type::tree_type;
//! # use tempfile::TempDir;
//!
//! tree_type! {
//!     App {
//!         config/ {
//!             #[default("production settings")]
//!             production("prod.toml"),
//!    
//!             #[default("staging settings")]
//!             staging("staging.toml"),
//!             
//!             #[default("development settings")]
//!             development("dev.toml"),
//!             
//!             #[symlink(production)] // sibling
//!             active("active.toml")
//!         },
//!         data/ {
//!             #[symlink(/config/production)] // cross-directory
//!             config("config.toml"),
//!         }
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! # let temp_dir = TempDir::new()?;
//! # let app_path = temp_dir.path().join("app");
//! let app = App::new(app_path)?;
//!
//! let _result = app.setup();
//!
//! assert!(app.config().active().exists());
//! assert!(app.data().config().exists());
//!
//! // /config/active.toml -> /config/prod.toml
//! assert_eq!(app.config().active().read_to_string()?, "production settings");
//! // /data/config -> /config/active.toml -> /config/prod.toml
//! assert_eq!(app.data().config().read_to_string()?, "production settings");
//! # Ok(())
//! # }
//! ```
//!
//! Symlink targets must exist, so the target should have a `#[required]` attribute for
//! directories, or `#[default...]` attribute for files.
//!
//! # Parent Navigation
//!
//! The `parent()` method provides type-safe navigation to parent directories. Tree-type offers three different `parent()` method variants depending on the type you're working with:
//!
//! ## Method Variants Comparison
//!
//! | Type | Method Signature | Return Type | Behavior |
//! |------|------------------|-------------|----------|
//! | `GenericFile` | `parent(&self)` | `GenericDir` | Always succeeds - files must have parents |
//! | `GenericDir` | `parent(&self)` | `Option<GenericDir>` | May fail for root directories |
//! | Generated types | `parent(&self)` | Exact parent type | Type-safe, no Option needed |
//! | Generated root types | `parent(&self)` | `Option<GenericDir` | May fail if Root type is root directory |
//!
//! ## `GenericFile` Parent Method
//!
//! Files always have a parent directory, so `GenericFile::parent()` returns `GenericDir` directly:
//!
//! ```
//! use tree_type::GenericFile;
//! use std::path::Path;
//!
//! # fn main() -> std::io::Result<()> {
//! let file = GenericFile::new("/path/to/file.txt")?;
//! let parent_dir = file.parent();  // Returns GenericDir
//! assert_eq!(parent_dir.as_path(), Path::new("/path/to"));
//! # Ok(())
//! # }
//! ```
//!
//! ## `GenericDir` Parent Method
//!
//! Directories may not have a parent (root directories), so `GenericDir::parent()` returns `Option<GenericDir>`:
//!
//! ```
//! use tree_type::GenericDir;
//!
//! # fn main() -> std::io::Result<()> {
//! let dir = GenericDir::new("/path/to/dir")?;
//! if let Some(parent_dir) = dir.parent() {
//!     println!("Parent: {parent_dir}");
//! } else {
//!     println!("This is a root directory");
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Generated Type Parent Method
//!
//! Generated types from `tree_type!` macro provide type-safe parent navigation that returns the exact parent type:
//!
//! ```
//! #![expect(deprecated)]
//! use tree_type::tree_type;
//! use tree_type::GenericDir;
//!
//! tree_type! {
//!     ProjectRoot {
//!         src/ as SrcDir {
//!             main("main.rs") as MainFile
//!         }
//!     }
//! }
//!
//! # fn main() -> std::io::Result<()> {
//! let project = ProjectRoot::new("/project")?;
//! let src = project.src();
//! let main_file = src.main();
//!
//! // Type-safe parent navigation - no Option needed
//! let main_parent: SrcDir = main_file.parent();
//! let src_parent: ProjectRoot = src.parent();
//! let project_parent: Option<GenericDir> = project.parent();
//! # Ok(())
//! # }
//! ```
//!
//! ## Safety Notes
//!
//! - `GenericFile::parent()` may panic if the file path has no parent (extremely rare)
//! - `GenericDir::parent()` returns `None` for root directories
//! - Generated type `parent()` methods are guaranteed to return valid parent types
//!
//! # Contributing
//!
//! Contributions are welcome! Please feel free to submit a Pull Request
//! at <https://codeberg.org/kemitix/tree-type/issues>
//!

pub mod deps;
pub mod fs;

use std::io::ErrorKind;

// Re-export the proc macros for user convenience
pub use tree_type_proc_macro::dir_type;
pub use tree_type_proc_macro::file_type;
pub use tree_type_proc_macro::tree_type;

pub enum GenericPath {
    File(GenericFile),
    Dir(GenericDir),
}

impl TryFrom<std::fs::DirEntry> for GenericPath {
    type Error = std::io::Error;

    fn try_from(value: std::fs::DirEntry) -> Result<Self, Self::Error> {
        let path: &std::path::Path = &value.path();
        GenericPath::try_from(path)
    }
}

#[cfg(feature = "walk")]
impl TryFrom<crate::deps::walk::DirEntry> for GenericPath {
    type Error = std::io::Error;

    fn try_from(value: crate::deps::walk::DirEntry) -> Result<Self, Self::Error> {
        GenericPath::try_from(value.path())
    }
}

#[cfg(feature = "enhanced-errors")]
impl TryFrom<crate::deps::enhanced_errors::DirEntry> for GenericPath {
    type Error = std::io::Error; // because ::fs_err::Error is private

    fn try_from(value: crate::deps::enhanced_errors::DirEntry) -> Result<Self, Self::Error> {
        let path: &std::path::Path = &value.path();
        GenericPath::try_from(path)
    }
}

impl TryFrom<&std::path::Path> for GenericPath {
    type Error = std::io::Error;

    fn try_from(path: &std::path::Path) -> Result<Self, Self::Error> {
        let path = resolve_path(path)?;
        if path.is_file() {
            Ok(GenericPath::File(GenericFile { path }))
        } else if path.is_dir() {
            Ok(GenericPath::Dir(GenericDir { path }))
        } else {
            Err(std::io::Error::other("unsupported path type"))
        }
    }
}

impl std::fmt::Display for GenericPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GenericPath::File(file) => write!(f, "{}", file.path.display()),
            GenericPath::Dir(dir) => write!(f, "{}", dir.path.display()),
        }
    }
}

impl std::fmt::Debug for GenericPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GenericPath::File(file) => write!(f, "GenericPath::File({})", file.path.display()),
            GenericPath::Dir(dir) => write!(f, "GenericPath::Dir({})", dir.path.display()),
        }
    }
}

fn resolve_path(path: &std::path::Path) -> Result<std::path::PathBuf, std::io::Error> {
    use std::collections::HashSet;
    let mut p = path.to_path_buf();
    let mut seen = HashSet::new();
    seen.insert(p.clone());
    while p.is_symlink() {
        p = p.read_link()?;
        if seen.contains(&p) {
            return Err(std::io::Error::other("symlink loop"));
        }
    }
    Ok(p)
}

// Generate GenericFile using the proc macro
#[allow(unexpected_cfgs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct GenericFile {
    path: std::path::PathBuf,
}

impl GenericFile {
    /// Create a new wrapper for a file
    ///
    /// # Errors
    ///
    /// If the file name is invalid. Invalid file name inclued empty file name.
    pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
        let path_buf = path.into();
        let file_name = path_buf.file_name();
        if file_name.is_none() {
            return Err(std::io::Error::from(ErrorKind::InvalidFilename));
        }
        Ok(Self { path: path_buf })
    }

    #[must_use]
    pub fn as_path(&self) -> &std::path::Path {
        &self.path
    }

    #[must_use]
    pub fn exists(&self) -> bool {
        self.path.exists()
    }

    #[must_use]
    pub fn as_generic(&self) -> GenericFile {
        self.clone()
    }

    /// Reads the entire contents of a file into a bytes vector.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::read`
    pub fn read(&self) -> std::io::Result<Vec<u8>> {
        fs::read(&self.path)
    }

    /// Reads the entire contents of a file into a string.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::read_to_string`
    pub fn read_to_string(&self) -> std::io::Result<String> {
        fs::read_to_string(&self.path)
    }

    /// Writes a slice as the entire contents of a file.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::write`
    pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
        if let Some(parent) = self.path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::write(&self.path, contents)
    }

    /// Create an empty file if it doesn't already exist
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::open`
    pub fn create(&self) -> std::io::Result<()> {
        if let Some(parent) = self.path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::create_file(&self.path)
    }

    /// Removes a file from the filesystem.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::remove_file`
    pub fn remove(&self) -> std::io::Result<()> {
        fs::remove_file(&self.path)
    }

    /// Given a path, queries the file system to get information about a file, directory, etc.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::metadata`
    pub fn fs_metadata(&self) -> std::io::Result<fs::Metadata> {
        fs::metadata(&self.path)
    }

    /// Returns the final component of the path as a String.
    /// See [`std::path::Path::file_name`] for more details.
    ///
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn file_name(&self) -> String {
        self.path
            .file_name()
            .expect("validated in new")
            .to_string_lossy()
            .to_string()
    }

    /// Rename/move this file to a new path.
    ///
    /// Consumes the original instance and returns a new instance with the updated path on success.
    /// On failure, returns both the error and the original instance for recovery.
    /// Parent directories are created automatically if they don't exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use tree_type::GenericFile;
    ///
    /// # fn main() -> std::io::Result<()> {
    /// let file = GenericFile::new("old.txt")?;
    /// match file.rename("new.txt") {
    ///     Ok(renamed_file) => {
    ///         // Use renamed_file
    ///     }
    ///     Err((error, original_file)) => {
    ///         // Handle error, original_file is still available
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::rename`
    pub fn rename(
        self,
        new_path: impl AsRef<std::path::Path>,
    ) -> Result<Self, (std::io::Error, Self)> {
        let new_path = new_path.as_ref();

        // Create parent directories if they don't exist
        if let Some(parent) = new_path.parent() {
            if !parent.exists() {
                if let Err(e) = fs::create_dir_all(parent) {
                    return Err((e, self));
                }
            }
        }

        // Attempt the rename
        match fs::rename(&self.path, new_path) {
            Ok(()) => Self::new(new_path).map_err(|e| (e, self)),
            Err(e) => Err((e, self)),
        }
    }

    /// Set file permissions to 0o600 (read/write for owner only).
    ///
    /// This method is only available on Unix systems.
    ///
    /// # Examples
    ///
    /// ```
    /// use tree_type::GenericFile;
    /// # use tempfile::TempDir;
    ///
    /// # fn main() -> std::io::Result<()> {
    /// # let temp_dir = TempDir::new()?;
    /// # let secret_file = temp_dir.path().join("secret.txt");
    /// let file = GenericFile::new(secret_file)?;
    /// file.write("content");
    /// file.secure()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::set_permissions`
    #[cfg(unix)]
    pub fn secure(&self) -> std::io::Result<()> {
        use std::os::unix::fs::PermissionsExt;
        let permissions = std::fs::Permissions::from_mode(0o600);
        fs::set_permissions(&self.path, permissions)
    }

    /// Get the parent directory as `GenericDir`.
    /// Files always have a parent directory.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn parent(&self) -> GenericDir {
        let parent_path = self
            .path
            .parent()
            .expect("Files must have a parent directory");
        GenericDir::new(parent_path).expect("Parent path should be valid")
    }
}

impl AsRef<std::path::Path> for GenericFile {
    fn as_ref(&self) -> &std::path::Path {
        &self.path
    }
}

impl std::fmt::Display for GenericFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.path.display())
    }
}

impl std::fmt::Debug for GenericFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "GenericFile({})", self.path.display())
    }
}

/// Generic directory type for type-erased directory operations.
///
/// This type can be used when you need to work with directories in a generic way,
/// without knowing their specific type at compile time. It supports conversion
/// to and from any typed directory struct.
///
/// # Examples
///
/// ```
/// use tree_type::{dir_type, GenericDir};
///
/// dir_type!(CacheDir);
///
/// # fn main() -> std::io::Result<()> {
/// let cache = CacheDir::new("/var/cache")?;
/// let generic: GenericDir = cache.into();
/// let cache_again = CacheDir::from_generic(generic);
/// # Ok(())
/// # }
/// ```
#[allow(unexpected_cfgs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct GenericDir {
    path: std::path::PathBuf,
}

impl GenericDir {
    /// Create a new wrapper for a directory
    ///
    /// # Errors
    ///
    /// If the directory is invalid. Invalid directory includes being empty.
    pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
        let path_buf = path.into();
        // For directories, allow root paths and paths with filename components
        // Only reject empty paths or invalid paths like ".."
        if path_buf.as_os_str().is_empty() {
            return Err(std::io::Error::from(ErrorKind::InvalidFilename));
        }
        Ok(Self { path: path_buf })
    }

    #[must_use]
    pub fn as_path(&self) -> &std::path::Path {
        &self.path
    }

    #[must_use]
    pub fn exists(&self) -> bool {
        self.path.exists()
    }

    /// Returns a clone of the `GenericDir`
    #[must_use]
    pub fn as_generic(&self) -> GenericDir {
        self.clone()
    }

    /// Creates a new, empty directory at the provided path
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::create_dir`
    pub fn create(&self) -> std::io::Result<()> {
        fs::create_dir(&self.path)
    }

    /// Recursively create a directory and all of its parent components if they are missing.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::create_dir_all`
    pub fn create_all(&self) -> std::io::Result<()> {
        fs::create_dir_all(&self.path)
    }

    /// Removes an empty directory.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::remove_all`
    pub fn remove(&self) -> std::io::Result<()> {
        fs::remove_dir(&self.path)
    }

    /// Removes a directory at this path, after removing all its contents. Use carefully!
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::remove_dir_all`
    pub fn remove_all(&self) -> std::io::Result<()> {
        fs::remove_dir_all(&self.path)
    }

    /// Returns an iterator over the entries within a directory.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::read_dir`
    #[cfg(feature = "enhanced-errors")]
    pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<GenericPath>>> {
        crate::deps::enhanced_errors::read_dir(&self.path)
            .map(|read_dir| read_dir.map(|result| result.and_then(GenericPath::try_from)))
    }

    /// Returns an iterator over the entries within a directory.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::read_dir`
    #[cfg(not(feature = "enhanced-errors"))]
    pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<GenericPath>>> {
        std::fs::read_dir(&self.path)
            .map(|read_dir| read_dir.map(|result| result.and_then(GenericPath::try_from)))
    }

    /// Given a path, queries the file system to get information about a file, directory, etc.
    ///
    /// # Errors
    ///
    /// May return any of the same errors as `std::fs::metadata`
    pub fn fs_metadata(&self) -> std::io::Result<std::fs::Metadata> {
        fs::metadata(&self.path)
    }

    #[cfg(feature = "walk")]
    #[must_use]
    pub fn walk_dir(&self) -> crate::deps::walk::WalkDir {
        crate::deps::walk::WalkDir::new(&self.path)
    }

    #[cfg(feature = "walk")]
    pub fn walk(&self) -> impl Iterator<Item = std::io::Result<GenericPath>> {
        crate::deps::walk::WalkDir::new(&self.path)
            .into_iter()
            .map(|r| {
                r.map_err(std::convert::Into::into)
                    .and_then(GenericPath::try_from)
            })
    }

    #[cfg(feature = "walk")]
    /// Calculate total size in bytes of directory contents
    ///
    /// # Errors
    ///
    /// Returns an error if there are issues accessing files or directories during traversal.
    pub fn size_in_bytes(&self) -> std::io::Result<u64> {
        let mut total = 0u64;
        for entry in crate::deps::walk::WalkDir::new(&self.path) {
            let entry = entry?;
            if entry.file_type().is_file() {
                total += entry.metadata()?.len();
            }
        }
        Ok(total)
    }

    #[cfg(feature = "walk")]
    /// List directory contents with metadata
    ///
    /// # Errors
    ///
    /// Returns an error if there are issues accessing files or directories during traversal.
    pub fn lsl(&self) -> std::io::Result<Vec<(std::path::PathBuf, std::fs::Metadata)>> {
        let mut results = Vec::new();
        for entry in crate::deps::walk::WalkDir::new(&self.path) {
            let entry = entry?;
            let metadata = entry.metadata()?;
            results.push((entry.path().to_path_buf(), metadata));
        }
        Ok(results)
    }

    /// Returns the final component of the path as a String.
    /// For root paths like "/", returns an empty string.
    /// See [`std::path::Path::file_name`] for more details.
    #[must_use]
    pub fn file_name(&self) -> String {
        self.path
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_default()
    }

    /// Renames this directory to a new name, replacing the original item if
    /// `to` already exists.
    ///
    /// Consumes the original instance and returns a new instance with the updated path on success.
    /// On failure, returns both the error and the original instance for recovery.
    /// Parent directories are created automatically if they don't exist.
    ///
    /// # Examples
    ///
    /// ```
    /// use tree_type::GenericDir;
    ///
    /// # fn main() -> std::io::Result<()> {
    /// let dir = GenericDir::new("old_dir")?;
    /// match dir.rename("new_dir") {
    ///     Ok(renamed_dir) => {
    ///         // Use renamed_dir
    ///     }
    ///     Err((error, original_dir)) => {
    ///         // Handle error, original_dir is still available
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::rename`
    pub fn rename(
        self,
        new_path: impl AsRef<std::path::Path>,
    ) -> Result<Self, (std::io::Error, Self)> {
        let new_path = new_path.as_ref();

        // Create parent directories if they don't exist
        if let Some(parent) = new_path.parent() {
            if !parent.exists() {
                if let Err(e) = std::fs::create_dir_all(parent) {
                    return Err((e, self));
                }
            }
        }

        // Attempt the rename
        match fs::rename(&self.path, new_path) {
            Ok(()) => Self::new(new_path).map_err(|e| (e, self)),
            Err(e) => Err((e, self)),
        }
    }

    /// Set directory permissions to 0o700 (read/write/execute for owner only).
    ///
    /// This method is only available on Unix systems.
    ///
    /// # Examples
    ///
    /// ```
    /// use tree_type::GenericDir;
    /// # use tempfile::TempDir;
    ///
    /// # fn main() -> std::io::Result<()> {
    /// # let temp_dir = TempDir::new()?;
    /// # let secret_dir = temp_dir.path().join("secret");
    /// let dir = GenericDir::new(secret_dir)?;
    /// dir.create()?;
    /// dir.secure()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///  
    /// May return any of the same errors as `std::fs::set_permissions`
    #[cfg(unix)]
    pub fn secure(&self) -> std::io::Result<()> {
        use std::os::unix::fs::PermissionsExt;
        let permissions = std::fs::Permissions::from_mode(0o700);
        fs::set_permissions(&self.path, permissions)
    }

    /// Get the parent directory as `GenericDir`.
    /// Returns None for directories at the root level.
    #[must_use]
    pub fn parent(&self) -> Option<GenericDir> {
        self.path
            .parent()
            .and_then(|parent_path| GenericDir::new(parent_path).ok())
    }
}

impl AsRef<std::path::Path> for GenericDir {
    fn as_ref(&self) -> &std::path::Path {
        &self.path
    }
}

impl std::fmt::Display for GenericDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.path.display())
    }
}

impl std::fmt::Debug for GenericDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "GenericDir({})", self.path.display())
    }
}

/// Outcome of calling `create_default()` on a file type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CreateDefaultOutcome {
    /// File was created with default content
    Created,
    /// File already existed, no action taken
    AlreadyExists,
}

/// Error type for `setup()` operations
#[derive(Debug)]
pub enum BuildError {
    /// Error creating a directory
    Directory(std::path::PathBuf, std::io::Error),
    /// Error creating a file with default content
    File(std::path::PathBuf, Box<dyn std::error::Error>),
}

/// Controls whether validation/ensure operations recurse into child paths
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Recursive {
    /// Validate/ensure only this level
    No,
    /// Validate/ensure entire tree
    Yes,
}

/// Validation error for a specific path
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Path that failed validation
    pub path: std::path::PathBuf,
    /// Error message
    pub message: String,
}

/// Validation warning for a specific path
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationWarning {
    /// Path that generated warning
    pub path: std::path::PathBuf,
    /// Warning message
    pub message: String,
}

/// Result of validation operation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationReport {
    /// Validation errors
    pub errors: Vec<ValidationError>,
    /// Validation warnings
    pub warnings: Vec<ValidationWarning>,
}

impl ValidationReport {
    /// Create empty validation report
    #[must_use]
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Check if validation passed (no errors)
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }

    /// Merge another report into this one
    pub fn merge(&mut self, other: ValidationReport) {
        self.errors.extend(other.errors);
        self.warnings.extend(other.warnings);
    }
}

impl Default for ValidationReport {
    fn default() -> Self {
        Self::new()
    }
}

/// Result returned by validator functions
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ValidatorResult {
    /// Validation errors
    pub errors: Vec<String>,
    /// Validation warnings
    pub warnings: Vec<String>,
}