uvm_detect 1.1.1

Unity project detection and version extraction library
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
use std::{
    collections::HashMap,
    fs::{self, File},
    io::{self, BufRead, BufReader},
    path::{Path, PathBuf},
    str::FromStr,
};
use unity_version::RevisionHash;
use unity_version::Version;
use unity_version::CompleteVersion;


/// Configuration options for Unity project detection.
///
/// This struct provides a builder-style API similar to `std::fs::OpenOptions` for configuring
/// how Unity project detection should behave. Use the builder methods to customize the search
/// behavior, then call the detection methods to perform the actual search.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use uvm_detect::DetectOptions;
///
/// // Basic usage with default options
/// let project_path = DetectOptions::new()
///     .detect_unity_project_dir(Path::new("."))?;
///
/// // Recursive search with custom depth limit
/// let project_path = DetectOptions::new()
///     .recursive(true)
///     .max_depth(3)
///     .detect_unity_project_dir(Path::new("./projects"))?;
///
/// // Get version with custom options
/// let version = DetectOptions::new()
///     .recursive(true)
///     .max_depth(5)
///     .detect_project_version(Path::new("."))?;
///
/// // Get complete version with revision hash
/// let complete_version = DetectOptions::new()
///     .detect_project_complete_version(Path::new("."))?;
/// println!("Version: {}, Revision: {}", 
///          complete_version.version(), complete_version.revision());
///
/// // Get just the revision hash
/// let revision_hash = DetectOptions::new()
///     .detect_project_version_revision_hash(Path::new("."))?;
/// println!("Revision hash: {}", revision_hash);
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Default)]
pub struct DetectOptions {
    /// Whether to search recursively through subdirectories
    pub recursive: bool,
    /// Maximum depth to search when recursive is enabled (u32::MAX = unlimited)
    pub max_depth: u32,
    /// Whether to use case-sensitive path matching
    pub case_sensitive: bool,
}

impl DetectOptions {
    /// Creates a new `DetectOptions` with default settings.
    ///
    /// Default settings:
    /// - `recursive`: false (search only in specified directory)
    /// - `max_depth`: u32::MAX (unlimited depth when recursive)
    /// - `case_sensitive`: true (use case-sensitive path matching)
    pub fn new() -> Self {
        Self {
            recursive: false,
            max_depth: u32::MAX,
            case_sensitive: true,
        }
    }

    /// Sets whether to search recursively through subdirectories.
    ///
    /// When `true`, the search will traverse into subdirectories looking for Unity projects.
    /// When `false`, only the specified directory is searched.
    ///
    /// # Arguments
    ///
    /// * `recursive` - Whether to enable recursive search
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use uvm_detect::DetectOptions;
    /// use std::path::Path;
    ///
    /// // Search recursively
    /// let result = DetectOptions::new()
    ///     .recursive(true)
    ///     .detect_unity_project_dir(Path::new("."))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
        self.recursive = recursive;
        self
    }

    /// Sets the maximum depth to search when recursive search is enabled.
    ///
    /// This limits how deep the recursive search will go. A depth of 1 means only
    /// immediate subdirectories are searched. Use `u32::MAX` for unlimited depth.
    ///
    /// # Arguments
    ///
    /// * `max_depth` - Maximum search depth, or `u32::MAX` for unlimited
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use uvm_detect::DetectOptions;
    /// use std::path::Path;
    ///
    /// // Search recursively but only 2 levels deep
    /// let result = DetectOptions::new()
    ///     .recursive(true)
    ///     .max_depth(2)
    ///     .detect_unity_project_dir(Path::new("."))?;
    ///
    /// // Search with unlimited depth
    /// let result = DetectOptions::new()
    ///     .recursive(true)
    ///     .max_depth(u32::MAX)
    ///     .detect_unity_project_dir(Path::new("."))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn max_depth(&mut self, max_depth: u32) -> &mut Self {
        self.max_depth = max_depth;
        self
    }

    /// Sets whether to use case-sensitive path matching.
    ///
    /// This affects how file and directory names are compared during search.
    ///
    /// # Arguments
    ///
    /// * `case_sensitive` - Whether to use case-sensitive matching
    ///
    /// # Note
    ///
    /// This option is reserved for future functionality and does not currently affect behavior.
    pub fn case_sensitive(&mut self, case_sensitive: bool) -> &mut Self {
        self.case_sensitive = case_sensitive;
        self
    }

    /// Detects and parses the Unity version from a Unity project.
    ///
    /// This function locates a Unity project directory using the configured options and reads 
    /// the ProjectVersion.txt file to extract Unity editor version information. It prioritizes 
    /// the version with revision information if available, falling back to the basic editor version.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to start searching from
    ///
    /// # Returns
    ///
    /// * `Ok(Version)` - The parsed Unity version if found and valid
    /// * `Err(io::Error)` - An error if the project is not found, the version file cannot be read,
    ///   or the version string cannot be parsed
    ///
    /// # File Format
    ///
    /// The function reads ProjectSettings/ProjectVersion.txt and looks for lines like:
    /// - `m_EditorVersion: 2021.3.16f1`
    /// - `m_EditorVersionWithRevision: 2021.3.16f1 (4016570cf34f)`
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use uvm_detect::DetectOptions;
    ///
    /// // Basic version detection
    /// let version = DetectOptions::new()
    ///     .detect_project_version(Path::new("./my-unity-project"))?;
    /// println!("Unity version: {}", version);
    ///
    /// // Recursive search with depth limit
    /// let version = DetectOptions::new()
    ///     .recursive(true)
    ///     .max_depth(3)
    ///     .detect_project_version(Path::new("./projects"))?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn detect_project_version(&self, dir: &Path) -> io::Result<Version> {
        let v = self.detect_project_version_str(dir)?;
        Version::from_str(&v)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Can't parse Unity version"))
    }

    pub fn detect_project_version_str(&self, dir: &Path) -> io::Result<String> {
        let project_version = self.detect_unity_project_dir(dir).and_then(|p| {
            self.try_get_project_version(p).ok_or_else(|| {
                io::Error::new(io::ErrorKind::NotFound, "ProjectVersion.txt not found")
            })
        })?;

        let file = File::open(project_version)?;
        let lines = BufReader::new(file).lines();

        let mut editor_versions: HashMap<&'static str, String> = HashMap::with_capacity(2);

        for line in lines {
            if let Ok(line) = line {
                if line.starts_with("m_EditorVersion: ") {
                    let value = line.replace("m_EditorVersion: ", "");
                    editor_versions.insert("EditorVersion", value.to_owned());
                }

                if line.starts_with("m_EditorVersionWithRevision: ") {
                    let value = line.replace("m_EditorVersionWithRevision: ", "");
                    editor_versions.insert("EditorVersionWithRevision", value.to_owned());
                }
            }
        }

        let v = editor_versions
            .get("EditorVersionWithRevision")
            .or_else(|| editor_versions.get("EditorVersion"))
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "Can't parse Unity version")
            })?; 
        Ok(v.to_owned())
    }

    /// Detects and extracts the revision hash from a Unity project version.
    ///
    /// This function locates a Unity project directory and reads the ProjectVersion.txt file
    /// to extract the revision hash from the Unity editor version information. It requires
    /// the version to include a revision hash (e.g., "2021.3.55f1 (f87d5274e360)").
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to start searching from
    ///
    /// # Returns
    ///
    /// * `Ok(RevisionHash)` - If a valid revision hash is found
    /// * `Err(io::Error)` - If the project is not found, version file cannot be read,
    ///   the version string is invalid, or no revision hash is present
    ///
    /// # Error Types
    ///
    /// - `NotFound` - Unity project or version file not found
    /// - `InvalidInput` - Version format is invalid or no revision hash present
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use uvm_detect::DetectOptions;
    ///
    /// // Version with revision hash: "2021.3.55f1 (f87d5274e360)"
    /// match DetectOptions::new()
    ///     .detect_project_version_revision_hash(Path::new("./project")) {
    ///     Ok(hash) => println!("Found revision hash: {}", hash),
    ///     Err(e) => println!("Error: {}", e),
    /// }
    ///
    /// // If you want Optional behavior, use .ok():
    /// let hash_opt = DetectOptions::new()
    ///     .detect_project_version_revision_hash(Path::new("./project"))
    ///     .ok();
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn detect_project_version_revision_hash(&self, dir: &Path) -> io::Result<RevisionHash> {
        // Delegate to the complete version function and extract just the revision hash
        let complete_version = self.detect_project_complete_version(dir)?;
        Ok(complete_version.revision().clone())
    }

    /// Detects and parses the complete Unity version (version + revision hash) from a Unity project.
    ///
    /// This function locates a Unity project directory and reads the ProjectVersion.txt file
    /// to extract both the Unity version and revision hash. It requires the version to include 
    /// a revision hash (e.g., "2021.3.55f1 (f87d5274e360)").
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to start searching from
    ///
    /// # Returns
    ///
    /// * `Ok(CompleteVersion)` - If a valid version with revision hash is found
    /// * `Err(io::Error)` - If the project is not found, version file cannot be read,
    ///   the version string is invalid, or no revision hash is present
    ///
    /// # Error Types
    ///
    /// - `NotFound` - Unity project or version file not found
    /// - `InvalidInput` - Version format is invalid or no revision hash present
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use uvm_detect::DetectOptions;
    ///
    /// // Version with revision hash: "2021.3.55f1 (f87d5274e360)"
    /// match DetectOptions::new()
    ///     .detect_project_complete_version(Path::new("./project")) {
    ///     Ok(complete_version) => {
    ///         println!("Version: {}", complete_version.version());
    ///         println!("Revision: {}", complete_version.revision());
    ///         println!("Complete: {}", complete_version); // "2021.3.55f1 (f87d5274e360)"
    ///     },
    ///     Err(e) => println!("Error: {}", e),
    /// }
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn detect_project_complete_version(&self, dir: &Path) -> io::Result<CompleteVersion> {
        let version_str = self.detect_project_version_str(dir)?;
        
        CompleteVersion::from_str(&version_str)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))
    }

    /// Detects a Unity project directory by searching for Unity project markers.
    ///
    /// This function searches for Unity project directories using the configured options. It looks 
    /// for the presence of a valid Unity project structure (specifically, a ProjectSettings/ProjectVersion.txt file).
    /// The search behavior (recursive vs. current directory only, max depth) is determined by the 
    /// configuration set via the builder methods.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory path to start searching from
    ///
    /// # Returns
    ///
    /// * `Ok(PathBuf)` - The path to the Unity project directory if found
    /// * `Err(io::Error)` - An error if no Unity project is found or if there are I/O issues
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use uvm_detect::DetectOptions;
    ///
    /// // Search for Unity project in current directory only
    /// if let Ok(project_path) = DetectOptions::new().detect_unity_project_dir(Path::new(".")) {
    ///     println!("Found Unity project at: {}", project_path.display());
    /// }
    ///
    /// // Search recursively through subdirectories with depth limit
    /// match DetectOptions::new()
    ///     .recursive(true)
    ///     .max_depth(5)
    ///     .detect_unity_project_dir(Path::new(".")) {
    ///     Ok(project_path) => println!("Found Unity project at: {}", project_path.display()),
    ///     Err(e) => println!("No Unity project found: {}", e),
    /// }
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn detect_unity_project_dir(&self, dir: &Path) -> io::Result<PathBuf> {
        self.detect_unity_project_dir_with_depth(dir, 0)
    }

    fn detect_unity_project_dir_with_depth(&self, dir: &Path, current_depth: u32) -> io::Result<PathBuf> {
        let error = Err(io::Error::new(
            io::ErrorKind::NotFound,
            "Unable to find a Unity project",
        ));

        // Check if the path is a directory
        if !dir.is_dir() {
            return error;
        }

        // Check if this directory contains a Unity project
        if self.try_get_project_version(dir).is_some() {
            return Ok(dir.to_path_buf());
        }

        // If not recursive, or we've hit max depth, stop here
        if !self.recursive || current_depth >= self.max_depth {
            return error;
        }

        // Search subdirectories
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            
            // Only recurse into directories
            if path.is_dir() {
                let result = self.detect_unity_project_dir_with_depth(&path, current_depth + 1);
                if result.is_ok() {
                    return result;
                }
            }
        }

        error
    }

    /// Attempts to get the path to the Unity ProjectVersion.txt file if it exists.
    ///
    /// This function constructs the expected path to Unity's ProjectVersion.txt file
    /// within a Unity project structure and checks if the file exists.
    ///
    /// # Arguments
    ///
    /// * `base_dir` - The base directory to check for Unity project structure
    ///
    /// # Returns
    ///
    /// * `Some(PathBuf)` - The path to ProjectSettings/ProjectVersion.txt if it exists
    /// * `None` - If the file doesn't exist (indicating the directory is not a Unity project)
    ///
    /// # Unity Project Structure
    ///
    /// A valid Unity project should have the following structure:
    /// ```text
    /// ProjectRoot/
    /// ├── ProjectSettings/
    /// │   └── ProjectVersion.txt  ← This file is checked
    /// ├── Assets/
    /// └── ...
    /// ```
    fn try_get_project_version<P: AsRef<Path>>(&self, base_dir: P) -> Option<PathBuf> {
        let project_version = base_dir
            .as_ref()
            .join("ProjectSettings")
            .join("ProjectVersion.txt");
        if project_version.exists() {
            Some(project_version)
        } else {
            None
        }
    }
}

/// Detects a Unity project directory using default options.
///
/// This is a convenience function that uses default detection options (non-recursive search).
/// For more control over the search behavior, use `DetectOptions`.
///
/// # Arguments
///
/// * `dir` - The directory path to search in
///
/// # Returns
///
/// * `Ok(PathBuf)` - The path to the Unity project directory if found
/// * `Err(io::Error)` - An error if no Unity project is found
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use uvm_detect::{detect_unity_project_dir, DetectOptions};
///
/// // Simple search in current directory
/// let project_path = detect_unity_project_dir(Path::new("."))?;
///
/// // For recursive search, use DetectOptions
/// let project_path = DetectOptions::new()
///     .recursive(true)
///     .detect_unity_project_dir(Path::new("."))?;
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn detect_unity_project_dir(dir: &Path) -> io::Result<PathBuf> {
    DetectOptions::new().detect_unity_project_dir(dir)
}

/// Detects and parses the Unity version from a Unity project using default options.
///
/// This is a convenience function that uses default detection options (non-recursive search).
/// For more control over the search behavior, use `DetectOptions`.
///
/// This function locates a Unity project directory and reads the ProjectVersion.txt file
/// to extract the Unity editor version information. It prioritizes the version with
/// revision information if available, falling back to the basic editor version.
///
/// # Arguments
///
/// * `project_path` - The path to start searching for a Unity project
///
/// # Returns
///
/// * `Ok(Version)` - The parsed Unity version if found and valid
/// * `Err(io::Error)` - An error if the project is not found, the version file cannot be read,
///   or the version string cannot be parsed
///
/// # File Format
///
/// The function reads ProjectSettings/ProjectVersion.txt and looks for lines like:
/// - `m_EditorVersion: 2021.3.16f1`
/// - `m_EditorVersionWithRevision: 2021.3.16f1 (4016570cf34f)`
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use uvm_detect::{detect_project_version, DetectOptions};
///
/// // Simple version detection
/// let version = detect_project_version(Path::new("./my-unity-project"))?;
/// println!("Unity version: {}", version);
///
/// // For recursive search with custom options
/// let version = DetectOptions::new()
///     .recursive(true)
///     .max_depth(3)
///     .detect_project_version(Path::new("./projects"))?;
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn detect_project_version(project_path: &Path) -> io::Result<Version> {
    DetectOptions::new().detect_project_version(project_path)
}

/// Detects and extracts the revision hash from a Unity project version.
/// 
/// Convenience function using default detection options.
/// 
/// # Arguments
/// 
/// * `project_path` - The path to start searching for a Unity project
/// 
/// # Returns
/// 
/// * `Ok(RevisionHash)` - If a valid revision hash is found
/// * `Err(io::Error)` - If the project is not found, version file cannot be read,
///   the version string is invalid, or no revision hash is present
/// 
/// # Examples
/// 
/// ```no_run
/// use std::path::Path;
/// use uvm_detect::detect_project_version_revision_hash;
/// 
/// match detect_project_version_revision_hash(Path::new("./my-unity-project")) {
///     Ok(hash) => println!("Found revision hash: {}", hash),
///     Err(e) => println!("Error: {}", e),
/// }
/// 
/// // If you want Optional behavior, use .ok():
/// let hash_opt = detect_project_version_revision_hash(Path::new("./my-unity-project")).ok();
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn detect_project_version_revision_hash(project_path: &Path) -> io::Result<RevisionHash> {
    DetectOptions::new().detect_project_version_revision_hash(project_path)
}

/// Detects and parses the complete Unity version (version + revision hash) from a Unity project.
/// 
/// Convenience function using default detection options.
/// 
/// # Arguments
/// 
/// * `project_path` - The path to start searching for a Unity project
/// 
/// # Returns
/// 
/// * `Ok(CompleteVersion)` - If a valid version with revision hash is found
/// * `Err(io::Error)` - If the project is not found, version file cannot be read,
///   the version string is invalid, or no revision hash is present
/// 
/// # Examples
/// 
/// ```no_run
/// use std::path::Path;
/// use uvm_detect::detect_project_complete_version;
/// 
/// match detect_project_complete_version(Path::new("./my-unity-project")) {
///     Ok(complete_version) => {
///         println!("Version: {}", complete_version.version());
///         println!("Revision: {}", complete_version.revision());
///         println!("Complete: {}", complete_version); // "2021.3.55f1 (f87d5274e360)"
///     },
///     Err(e) => println!("Error: {}", e),
/// }
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn detect_project_complete_version(project_path: &Path) -> io::Result<CompleteVersion> {
    DetectOptions::new().detect_project_complete_version(project_path)
}

/// Attempts to get the path to the Unity ProjectVersion.txt file if it exists.
/// 
/// Convenience function using default detection options.
pub fn try_get_project_version<P: AsRef<Path>>(base_dir: P) -> Option<PathBuf> {
    DetectOptions::new().try_get_project_version(base_dir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use tempfile::TempDir;

    fn create_unity_project(base_dir: &Path, version_content: &str) -> std::io::Result<()> {
        let project_settings = base_dir.join("ProjectSettings");
        fs::create_dir_all(&project_settings)?;

        let version_file = project_settings.join("ProjectVersion.txt");
        fs::write(version_file, version_content)?;

        Ok(())
    }

    #[test]
    fn test_try_get_project_version_valid_project() {
        let temp_dir = TempDir::new().unwrap();
        create_unity_project(temp_dir.path(), "m_EditorVersion: 2021.3.16f1").unwrap();

        let result = try_get_project_version(temp_dir.path());
        assert!(result.is_some());

        let path = result.unwrap();
        assert!(path.ends_with("ProjectSettings/ProjectVersion.txt"));
        assert!(path.exists());
    }

    #[test]
    fn test_try_get_project_version_no_project() {
        let temp_dir = TempDir::new().unwrap();
        // Don't create Unity project structure

        let result = try_get_project_version(temp_dir.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_try_get_project_version_missing_project_settings() {
        let temp_dir = TempDir::new().unwrap();
        // Create directory but no ProjectSettings
        fs::create_dir(temp_dir.path().join("Assets")).unwrap();

        let result = try_get_project_version(temp_dir.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_detect_unity_project_dir_current_directory() {
        let temp_dir = TempDir::new().unwrap();
        create_unity_project(temp_dir.path(), "m_EditorVersion: 2021.3.16f1").unwrap();

        let result = detect_unity_project_dir(temp_dir.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), temp_dir.path());
    }

    #[test]
    fn test_detect_unity_project_dir_not_found_no_recursion() {
        let temp_dir = TempDir::new().unwrap();
        // Create a subdirectory with Unity project, but don't search recursively
        let subdir = temp_dir.path().join("subproject");
        fs::create_dir(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2021.3.16f1").unwrap();

        let result = detect_unity_project_dir(temp_dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_unity_project_dir_recursive_search() {
        let temp_dir = TempDir::new().unwrap();
        // Create a subdirectory with Unity project and search recursively
        let subdir = temp_dir.path().join("subproject");
        fs::create_dir(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2021.3.16f1").unwrap();

        let result = DetectOptions::new().recursive(true).detect_unity_project_dir(temp_dir.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), subdir);
    }

    #[test]
    fn test_detect_unity_project_dir_nested_recursive() {
        let temp_dir = TempDir::new().unwrap();
        // Create nested directories with Unity project deep inside
        let nested_path = temp_dir
            .path()
            .join("level1")
            .join("level2")
            .join("unity_project");
        fs::create_dir_all(&nested_path).unwrap();
        create_unity_project(&nested_path, "m_EditorVersion: 2021.3.16f1").unwrap();

        let result = DetectOptions::new().recursive(true).detect_unity_project_dir(temp_dir.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), nested_path);
    }

    #[test]
    fn test_detect_project_version_with_editor_version() {
        let temp_dir = TempDir::new().unwrap();
        let version_content =
            "m_EditorVersion: 2021.3.16f1\nm_EditorVersionWithRevision: 2021.3.16f1 (4016570cf34f)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version(temp_dir.path());
        assert!(result.is_ok());

        let version = result.unwrap();
        assert_eq!(version.to_string(), "2021.3.16f1");
    }

    #[test]
    fn test_detect_project_version_with_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content =
            "m_EditorVersion: 2020.3.1f1\nm_EditorVersionWithRevision: 2021.3.16f1 (4016570cf34f)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version(temp_dir.path());
        assert!(result.is_ok());

        let version = result.unwrap();
        // Should prefer the version with revision
        assert_eq!(version.to_string(), "2021.3.16f1");
    }

    #[test]
    fn test_detect_project_version_only_editor_version() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2019.4.31f1\nSomeOtherField: value";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version(temp_dir.path());
        assert!(result.is_ok());

        let version = result.unwrap();
        assert_eq!(version.to_string(), "2019.4.31f1");
    }

    #[test]
    fn test_detect_project_version_no_version_info() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "SomeField: value\nAnotherField: another_value";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version(temp_dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_project_version_malformed_version() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: not_a_valid_version";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version(temp_dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_project_version_recursive() {
        let temp_dir = TempDir::new().unwrap();
        let subdir = temp_dir.path().join("my_project");
        fs::create_dir(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2022.1.5f1").unwrap();

        let result = DetectOptions::new().recursive(true).detect_project_version(temp_dir.path());
        assert!(result.is_ok());

        let version = result.unwrap();
        assert_eq!(version.to_string(), "2022.1.5f1");
    }

    #[test]
    fn test_detect_project_version_no_project_found() {
        let temp_dir = TempDir::new().unwrap();
        // Empty directory with no Unity project

        let result = DetectOptions::new().recursive(true).detect_project_version(temp_dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_options_builder_pattern() {
        let temp_dir = TempDir::new().unwrap();
        let subdir = temp_dir.path().join("nested").join("project");
        fs::create_dir_all(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2023.1.0f1").unwrap();

        // Test builder pattern chaining
        let result = DetectOptions::new()
            .recursive(true)
            .max_depth(5)
            .case_sensitive(true)
            .detect_unity_project_dir(temp_dir.path());

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), subdir);
    }

    #[test]
    fn test_detect_options_convenience_functions() {
        let temp_dir = TempDir::new().unwrap();
        create_unity_project(temp_dir.path(), "m_EditorVersion: 2022.3.5f1").unwrap();

        // Test convenience function
        let result = detect_unity_project_dir(temp_dir.path());
        assert!(result.is_ok());

        // Test convenience function for version detection
        let version_result = detect_project_version(temp_dir.path());
        assert!(result.is_ok());
        assert_eq!(version_result.unwrap().to_string(), "2022.3.5f1");
    }

    #[test] 
    fn test_detect_options_default_vs_custom() {
        let temp_dir = TempDir::new().unwrap();
        let subdir = temp_dir.path().join("deep").join("project");
        fs::create_dir_all(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2021.2.8f1").unwrap();

        // Default options should not find nested project
        let default_result = DetectOptions::new().detect_unity_project_dir(temp_dir.path());
        assert!(default_result.is_err());

        // Custom options with recursion should find it
        let recursive_result = DetectOptions::new()
            .recursive(true)
            .detect_unity_project_dir(temp_dir.path());
        assert!(recursive_result.is_ok());
        assert_eq!(recursive_result.unwrap(), subdir);
    }

    #[test]
    fn test_max_depth_limiting() {
        let temp_dir = TempDir::new().unwrap();
        
        // Create a deep nested structure: temp/level1/level2/level3/project
        let deep_project = temp_dir.path()
            .join("level1")
            .join("level2") 
            .join("level3")
            .join("project");
        fs::create_dir_all(&deep_project).unwrap();
        create_unity_project(&deep_project, "m_EditorVersion: 2023.2.1f1").unwrap();

        // With max_depth = 2, should not find the project (it's at depth 4)
        let limited_result = DetectOptions::new()
            .recursive(true)
            .max_depth(2)
            .detect_unity_project_dir(temp_dir.path());
        assert!(limited_result.is_err());

        // With max_depth = 5, should find the project
        let deep_result = DetectOptions::new()
            .recursive(true)
            .max_depth(5)
            .detect_unity_project_dir(temp_dir.path());
        assert!(deep_result.is_ok());
        assert_eq!(deep_result.unwrap(), deep_project);

        // With no max_depth limit, should also find it
        let unlimited_result = DetectOptions::new()
            .recursive(true)
            .detect_unity_project_dir(temp_dir.path());
        assert!(unlimited_result.is_ok());
        assert_eq!(unlimited_result.unwrap(), deep_project);
    }

    #[test]
    fn test_max_depth_zero_means_current_only() {
        let temp_dir = TempDir::new().unwrap();
        
        // Create Unity project in subdirectory
        let subdir = temp_dir.path().join("subproject");
        fs::create_dir(&subdir).unwrap();
        create_unity_project(&subdir, "m_EditorVersion: 2022.1.0f1").unwrap();

        // With max_depth = 0 and recursive = true, should behave like recursive = false
        let depth_zero_result = DetectOptions::new()
            .recursive(true)
            .max_depth(0)
            .detect_unity_project_dir(temp_dir.path());
        assert!(depth_zero_result.is_err());

        // But should still find project in the current directory
        let current_dir_result = DetectOptions::new()
            .recursive(true)
            .max_depth(0)
            .detect_unity_project_dir(&subdir);
        assert!(current_dir_result.is_ok());
        assert_eq!(current_dir_result.unwrap(), subdir);
    }

    #[test]
    fn test_combined_options() {
        let temp_dir = TempDir::new().unwrap();
        
        // Create a structure: temp/level1/level2/project
        let project_path = temp_dir.path().join("level1").join("level2").join("project");
        fs::create_dir_all(&project_path).unwrap();
        create_unity_project(&project_path, "m_EditorVersion: 2023.1.15f1").unwrap();

        // Test combining recursive, max_depth, and other options
        let result = DetectOptions::new()
            .recursive(true)
            .max_depth(3)
            .case_sensitive(true)
            .detect_unity_project_dir(temp_dir.path());
        
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), project_path);
    }

    #[test]
    fn test_detect_project_version_revision_hash_with_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2021.3.55f1\nm_EditorVersionWithRevision: 2021.3.55f1 (f87d5274e360)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_ok());
        
        let revision_hash = result.unwrap();
        assert_eq!(revision_hash.as_str(), "f87d5274e360");
    }

    #[test]
    fn test_detect_project_version_revision_hash_without_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2021.3.55f1";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
    }

    #[test]
    fn test_detect_project_version_revision_hash_convenience_function_with_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersionWithRevision: 2022.1.5f1 (abc123def456)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_ok());
        
        let revision_hash = result.unwrap();
        assert_eq!(revision_hash.as_str(), "abc123def456");
    }

    #[test]
    fn test_detect_project_version_revision_hash_convenience_function_without_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2022.1.5f1";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
    }

    #[test]
    fn test_detect_project_version_revision_hash_different_unity_versions() {
        // Test different Unity version formats
        let test_cases = vec![
            ("2019.4.31f1 (be6d8d9ca5f4)", Some("be6d8d9ca5f4")),
            ("2020.3.48f1 (b805b124c6b2)", Some("b805b124c6b2")),
            ("2021.3.16f1 (4016570cf34f)", Some("4016570cf34f")),
            ("2022.3.5f1 (9674261d40ee)", Some("9674261d40ee")),
            ("2023.1.0a1 (123456789abc)", Some("123456789abc")),
            ("2023.2.0b5 (fedcba098765)", Some("fedcba098765")),
            ("2024.1.0p1 (111222333444)", Some("111222333444")),
            ("2019.4.31f1", None),
            ("2020.3.48f1", None),
            ("2021.3.16f1", None),
            ("2022.3.5f1", None),
        ];

        for (version_with_revision, expected_hash) in test_cases {
            let temp_dir = TempDir::new().unwrap();
            let version_content = format!("m_EditorVersionWithRevision: {}", version_with_revision);
            create_unity_project(temp_dir.path(), &version_content).unwrap();

            let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
            
            match expected_hash {
                Some(expected) => {
                    assert!(result.is_ok(), "Expected success for version with revision: {}", version_with_revision);
                    let revision_hash = result.unwrap();
                    assert_eq!(revision_hash.as_str(), expected, "Hash mismatch for: {}", version_with_revision);
                }
                None => {
                    assert!(result.is_err(), "Expected error for version without revision: {}", version_with_revision);
                    let error = result.unwrap_err();
                    assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
                    assert!(error.to_string().contains("Failed to parse unity version string"));
                }
            }
        }
    }

    #[test]
    fn test_detect_project_version_revision_hash_invalid_hash_length() {
        let temp_dir = TempDir::new().unwrap();
        // Invalid revision hash - too short
        let version_content = "m_EditorVersionWithRevision: 2021.3.55f1 (f87d527)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
        assert!(error.to_string().contains("f87d527"));
    }

    #[test]
    fn test_detect_project_version_revision_hash_invalid_hash_characters() {
        let temp_dir = TempDir::new().unwrap();
        // Invalid revision hash - contains non-hex characters
        let version_content = "m_EditorVersionWithRevision: 2021.3.55f1 (f87d5274e36z)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
        assert!(error.to_string().contains("f87d5274e36z"));
    }

    #[test]
    fn test_detect_project_version_revision_hash_malformed_version() {
        let temp_dir = TempDir::new().unwrap();
        // Completely invalid version format
        let version_content = "m_EditorVersionWithRevision: not_a_valid_version (f87d5274e360)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
        assert!(error.to_string().contains("not_a_valid_version"));
    }

    #[test]
    fn test_detect_project_version_revision_hash_no_project() {
        let temp_dir = TempDir::new().unwrap();
        // Empty directory with no Unity project

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn test_detect_project_version_revision_hash_recursive_search() {
        let temp_dir = TempDir::new().unwrap();
        let subdir = temp_dir.path().join("my_project");
        fs::create_dir(&subdir).unwrap();
        let version_content = "m_EditorVersionWithRevision: 2023.1.10f1 (deadbeefcafe)";
        create_unity_project(&subdir, version_content).unwrap();

        let result = DetectOptions::new()
            .recursive(true)
            .detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_ok());
        
        let revision_hash = result.unwrap();
        assert_eq!(revision_hash.as_str(), "deadbeefcafe");
    }

    #[test]
    fn test_detect_project_version_revision_hash_prefers_with_revision() {
        let temp_dir = TempDir::new().unwrap();
        // Test that when both m_EditorVersion and m_EditorVersionWithRevision are present,
        // it uses the one with revision for hash extraction
        let version_content = "m_EditorVersion: 2021.3.55f1\nm_EditorVersionWithRevision: 2021.3.55f1 (f87d5274e360)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(result.is_ok());
        
        let revision_hash = result.unwrap();
        assert_eq!(revision_hash.as_str(), "f87d5274e360");
    }

    #[test]
    fn test_detect_project_complete_version_with_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2021.3.55f1\nm_EditorVersionWithRevision: 2021.3.55f1 (f87d5274e360)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_complete_version(temp_dir.path());
        assert!(result.is_ok());
        
        let complete_version = result.unwrap();
        assert_eq!(complete_version.version().to_string(), "2021.3.55f1");
        assert_eq!(complete_version.revision().as_str(), "f87d5274e360");
        assert_eq!(complete_version.to_string(), "2021.3.55f1 (f87d5274e360)");
    }

    #[test]
    fn test_detect_project_complete_version_without_revision() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersion: 2021.3.55f1";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_complete_version(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
    }

    #[test]
    fn test_detect_project_complete_version_convenience_function() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersionWithRevision: 2022.3.10f1 (abc123def456)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = detect_project_complete_version(temp_dir.path());
        assert!(result.is_ok());
        
        let complete_version = result.unwrap();
        assert_eq!(complete_version.version().to_string(), "2022.3.10f1");
        assert_eq!(complete_version.revision().as_str(), "abc123def456");
        assert_eq!(complete_version.to_string(), "2022.3.10f1 (abc123def456)");
    }

    #[test]
    fn test_detect_project_complete_version_invalid_hash() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersionWithRevision: 2021.3.55f1 (invalid)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        let result = DetectOptions::new().detect_project_complete_version(temp_dir.path());
        assert!(result.is_err());
        
        let error = result.unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
        assert!(error.to_string().contains("Failed to parse unity version string"));
    }

    #[test]
    fn test_detect_project_complete_version_backwards_compatibility() {
        let temp_dir = TempDir::new().unwrap();
        let version_content = "m_EditorVersionWithRevision: 2021.3.55f1 (f87d5274e360)";
        create_unity_project(temp_dir.path(), version_content).unwrap();

        // Test that existing functions still work
        let version_result = DetectOptions::new().detect_project_version(temp_dir.path());
        assert!(version_result.is_ok());
        assert_eq!(version_result.unwrap().to_string(), "2021.3.55f1");

        let hash_result = DetectOptions::new().detect_project_version_revision_hash(temp_dir.path());
        assert!(hash_result.is_ok());
        assert_eq!(hash_result.unwrap().as_str(), "f87d5274e360");

        // Test new complete version function
        let complete_result = DetectOptions::new().detect_project_complete_version(temp_dir.path());
        assert!(complete_result.is_ok());
        let complete_version = complete_result.unwrap();
        assert_eq!(complete_version.version().to_string(), "2021.3.55f1");
        assert_eq!(complete_version.revision().as_str(), "f87d5274e360");
    }
}