cuenv-core 0.40.6

Core types and error handling for the cuenv ecosystem
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
//! Core types and utilities for cuenv
//!
//! This crate provides enhanced error handling with miette diagnostics,
//! structured error reporting, and contextual information.
//!
//! ## Type-safe wrappers
//!
//! This crate provides validated newtype wrappers for common domain types:
//!
//! - [`PackageDir`] - A validated directory path that must exist and be a directory
//! - [`PackageName`] - A validated package name following CUE package naming rules
//!
//! ## Examples
//!
//! ```rust
//! use cuenv_core::{PackageDir, PackageName};
//! use std::path::Path;
//!
//! // Validate a directory exists and is actually a directory
//! let pkg_dir = match PackageDir::try_from(Path::new(".")) {
//!     Ok(dir) => dir,
//!     Err(e) => {
//!         eprintln!("Invalid directory: {}", e);
//!         return;
//!     }
//! };
//!
//! // Validate a package name follows naming rules
//! let pkg_name = match PackageName::try_from("my-package") {
//!     Ok(name) => name,
//!     Err(e) => {
//!         eprintln!("Invalid package name: {}", e);
//!         return;
//!     }
//! };
//! ```

// Rust 1.92 compiler bug: false positives for thiserror/miette derive macro fields
// https://github.com/rust-lang/rust/issues/147648
#![allow(unused_assignments)]

pub mod affected;
pub mod base;
pub mod ci;
pub mod config;
pub mod contributors;
pub mod cue;
pub mod environment;
pub mod http;
pub mod lockfile;
pub mod manifest;
pub mod module;
pub mod owners;
pub mod paths;
pub mod rules;
pub mod runtime;
pub mod secrets;
pub mod shell;
pub mod sync;
pub mod tasks;
pub mod tools;

// Re-export affected detection types
pub use affected::{AffectedBy, matches_pattern};

// Re-export module types for convenience
pub use module::{Instance, InstanceKind, ModuleEvaluation};

/// Version of the `cuenv-core` crate (used by task cache metadata)
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg(test)]
pub mod test_utils;

use miette::{Diagnostic, SourceSpan};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Main error type for cuenv operations with enhanced diagnostics
#[derive(Error, Debug, Diagnostic)]
pub enum Error {
    #[error("Configuration error: {message}")]
    #[diagnostic(
        code(cuenv::config::invalid),
        help("Check your cuenv.cue configuration file for syntax errors or invalid values")
    )]
    Configuration {
        #[source_code]
        src: String,
        #[label("invalid configuration")]
        span: Option<SourceSpan>,
        message: String,
    },

    #[error("FFI operation failed in {function}: {message}")]
    #[diagnostic(code(cuenv::ffi::error))]
    Ffi {
        function: &'static str,
        message: String,
        #[help]
        help: Option<String>,
    },

    #[error("CUE parsing failed: {message}")]
    #[diagnostic(code(cuenv::cue::parse_error))]
    CueParse {
        path: Box<Path>,
        #[source_code]
        src: Option<String>,
        #[label("parsing failed here")]
        span: Option<SourceSpan>,
        message: String,
        suggestions: Option<Vec<String>>,
    },

    #[error("I/O {operation} failed{}", path.as_ref().map_or(String::new(), |p| format!(": {}", p.display())))]
    #[diagnostic(
        code(cuenv::io::error),
        help("Check file permissions and ensure the path exists")
    )]
    Io {
        #[source]
        source: std::io::Error,
        path: Option<Box<Path>>,
        operation: String,
    },

    #[error("Text encoding error")]
    #[diagnostic(
        code(cuenv::encoding::utf8),
        help("The file contains invalid UTF-8. Ensure your files use UTF-8 encoding.")
    )]
    Utf8 {
        #[source]
        source: std::str::Utf8Error,
        file: Option<Box<Path>>,
    },

    #[error("Operation timed out after {seconds} seconds")]
    #[diagnostic(
        code(cuenv::timeout),
        help("Try increasing the timeout or check if the operation is stuck")
    )]
    Timeout { seconds: u64 },

    #[error("Validation failed: {message}")]
    #[diagnostic(code(cuenv::validation::failed))]
    Validation {
        #[source_code]
        src: Option<String>,
        #[label("validation failed")]
        span: Option<SourceSpan>,
        message: String,
        #[related]
        related: Vec<Error>,
    },

    #[error("Task execution failed: {message}")]
    #[diagnostic(code(cuenv::task::execution))]
    Execution {
        message: String,
        #[help]
        help: Option<String>,
    },

    #[error("Tool resolution failed: {message}")]
    #[diagnostic(code(cuenv::tool::resolution))]
    ToolResolution {
        message: String,
        #[help]
        help: Option<String>,
    },

    #[error("Platform error: {message}")]
    #[diagnostic(
        code(cuenv::platform::error),
        help("This platform may not be supported by the tool provider")
    )]
    Platform { message: String },

    #[error("Task '{task_name}' failed with exit code {exit_code}")]
    #[diagnostic(code(cuenv::task::failed))]
    TaskFailed {
        task_name: String,
        exit_code: i32,
        stdout: String,
        stderr: String,
        #[help]
        help: Option<String>,
    },

    #[error("Task graph error: {message}")]
    #[diagnostic(code(cuenv::task::graph))]
    TaskGraph {
        message: String,
        #[help]
        help: Option<String>,
    },

    #[error("Secret resolution failed: {message}")]
    #[diagnostic(code(cuenv::secret::resolution))]
    SecretResolution {
        message: String,
        #[help]
        help: Option<String>,
    },
}

impl Error {
    #[must_use]
    pub fn configuration(msg: impl Into<String>) -> Self {
        Error::Configuration {
            src: String::new(),
            span: None,
            message: msg.into(),
        }
    }

    #[must_use]
    pub fn configuration_with_source(
        msg: impl Into<String>,
        src: impl Into<String>,
        span: Option<SourceSpan>,
    ) -> Self {
        Error::Configuration {
            src: src.into(),
            span,
            message: msg.into(),
        }
    }

    #[must_use]
    pub fn ffi(function: &'static str, message: impl Into<String>) -> Self {
        Error::Ffi {
            function,
            message: message.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn ffi_with_help(
        function: &'static str,
        message: impl Into<String>,
        help: impl Into<String>,
    ) -> Self {
        Error::Ffi {
            function,
            message: message.into(),
            help: Some(help.into()),
        }
    }

    #[must_use]
    pub fn cue_parse(path: &Path, message: impl Into<String>) -> Self {
        Error::CueParse {
            path: path.into(),
            src: None,
            span: None,
            message: message.into(),
            suggestions: None,
        }
    }

    #[must_use]
    pub fn cue_parse_with_source(
        path: &Path,
        message: impl Into<String>,
        src: impl Into<String>,
        span: Option<SourceSpan>,
        suggestions: Option<Vec<String>>,
    ) -> Self {
        Error::CueParse {
            path: path.into(),
            src: Some(src.into()),
            span,
            message: message.into(),
            suggestions,
        }
    }

    #[must_use]
    pub fn validation(msg: impl Into<String>) -> Self {
        Error::Validation {
            src: None,
            span: None,
            message: msg.into(),
            related: Vec::new(),
        }
    }

    #[must_use]
    pub fn validation_with_source(
        msg: impl Into<String>,
        src: impl Into<String>,
        span: Option<SourceSpan>,
    ) -> Self {
        Error::Validation {
            src: Some(src.into()),
            span,
            message: msg.into(),
            related: Vec::new(),
        }
    }

    #[must_use]
    pub fn execution(msg: impl Into<String>) -> Self {
        Error::Execution {
            message: msg.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn execution_with_help(msg: impl Into<String>, help: impl Into<String>) -> Self {
        Error::Execution {
            message: msg.into(),
            help: Some(help.into()),
        }
    }

    #[must_use]
    pub fn tool_resolution(msg: impl Into<String>) -> Self {
        Error::ToolResolution {
            message: msg.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn tool_resolution_with_help(msg: impl Into<String>, help: impl Into<String>) -> Self {
        Error::ToolResolution {
            message: msg.into(),
            help: Some(help.into()),
        }
    }

    #[must_use]
    pub fn platform(msg: impl Into<String>) -> Self {
        Error::Platform {
            message: msg.into(),
        }
    }

    #[must_use]
    pub fn task_failed(
        task_name: impl Into<String>,
        exit_code: i32,
        stdout: impl Into<String>,
        stderr: impl Into<String>,
    ) -> Self {
        Error::TaskFailed {
            task_name: task_name.into(),
            exit_code,
            stdout: stdout.into(),
            stderr: stderr.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn task_failed_with_help(
        task_name: impl Into<String>,
        exit_code: i32,
        stdout: impl Into<String>,
        stderr: impl Into<String>,
        help: impl Into<String>,
    ) -> Self {
        Error::TaskFailed {
            task_name: task_name.into(),
            exit_code,
            stdout: stdout.into(),
            stderr: stderr.into(),
            help: Some(help.into()),
        }
    }

    #[must_use]
    pub fn task_graph(message: impl Into<String>) -> Self {
        Error::TaskGraph {
            message: message.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn task_graph_with_help(message: impl Into<String>, help: impl Into<String>) -> Self {
        Error::TaskGraph {
            message: message.into(),
            help: Some(help.into()),
        }
    }

    #[must_use]
    pub fn secret_resolution(message: impl Into<String>) -> Self {
        Error::SecretResolution {
            message: message.into(),
            help: None,
        }
    }

    #[must_use]
    pub fn secret_resolution_with_help(
        message: impl Into<String>,
        help: impl Into<String>,
    ) -> Self {
        Error::SecretResolution {
            message: message.into(),
            help: Some(help.into()),
        }
    }
}

// Implement conversions for common error types
impl From<std::io::Error> for Error {
    fn from(source: std::io::Error) -> Self {
        Error::Io {
            source,
            path: None,
            operation: "unknown (unmapped error conversion)".to_string(),
        }
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(source: std::str::Utf8Error) -> Self {
        Error::Utf8 { source, file: None }
    }
}

impl From<cuenv_hooks::Error> for Error {
    fn from(source: cuenv_hooks::Error) -> Self {
        Error::Execution {
            message: source.to_string(),
            help: None,
        }
    }
}

impl From<cuenv_task_graph::Error> for Error {
    fn from(err: cuenv_task_graph::Error) -> Self {
        let help = match &err {
            cuenv_task_graph::Error::CycleDetected { .. } => {
                Some("Check for circular dependencies between tasks".into())
            }
            cuenv_task_graph::Error::MissingDependency { task, dependency } => Some(format!(
                "Add task '{}' or remove it from {}'s dependsOn",
                dependency, task
            )),
            cuenv_task_graph::Error::MissingDependencies { missing } => {
                let suggestions: Vec<String> = missing
                    .iter()
                    .map(|(task, dep)| {
                        format!("  - Add '{}' or remove from {}'s dependsOn", dep, task)
                    })
                    .collect();
                Some(format!(
                    "Fix missing dependencies:\n{}",
                    suggestions.join("\n")
                ))
            }
            cuenv_task_graph::Error::TopologicalSortFailed { .. } => None,
            cuenv_task_graph::Error::DuplicateNodeName {
                name,
                existing_kind,
                new_kind,
            } => Some(format!(
                "Rename the {new_kind} '{name}' to avoid collision with the existing {existing_kind}"
            )),
        };
        Error::TaskGraph {
            message: err.to_string(),
            help,
        }
    }
}

/// Result type alias for cuenv operations
pub type Result<T> = std::result::Result<T, Error>;

/// Type-safe replacement for `dry_run: bool` function parameters.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
pub enum DryRun {
    /// Perform the operation for real
    #[default]
    No,
    /// Preview the operation without making changes
    Yes,
}

impl DryRun {
    /// Returns `true` if this is a dry run.
    #[must_use]
    pub const fn is_dry_run(self) -> bool {
        matches!(self, Self::Yes)
    }
}

impl From<bool> for DryRun {
    fn from(v: bool) -> Self {
        if v { Self::Yes } else { Self::No }
    }
}

/// Type-safe replacement for `capture_output: bool` function parameters.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
pub enum OutputCapture {
    /// Capture stdout/stderr into buffers
    #[default]
    Capture,
    /// Stream stdout/stderr to the terminal
    Stream,
}

impl OutputCapture {
    /// Returns `true` if output should be captured.
    #[must_use]
    pub const fn should_capture(self) -> bool {
        matches!(self, Self::Capture)
    }
}

impl From<bool> for OutputCapture {
    fn from(v: bool) -> Self {
        if v { Self::Capture } else { Self::Stream }
    }
}

/// Configuration limits
pub struct Limits {
    pub max_path_length: usize,
    pub max_package_name_length: usize,
    pub max_output_size: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_path_length: 4096,
            max_package_name_length: 256,
            max_output_size: 100 * 1024 * 1024, // 100MB
        }
    }
}

/// A validated directory path that must exist and be a directory
///
/// This newtype wrapper ensures that any instance represents a path that:
/// - Exists on the filesystem
/// - Is actually a directory (not a file or symlink to file)
/// - Can be accessed for metadata reading
///
/// # Examples
///
/// ```rust
/// use cuenv_core::PackageDir;
/// use std::path::Path;
///
/// // Try to create from current directory
/// match PackageDir::try_from(Path::new(".")) {
///     Ok(dir) => println!("Valid directory: {}", dir.as_path().display()),
///     Err(e) => eprintln!("Invalid directory: {}", e),
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct PackageDir(PathBuf);

impl PackageDir {
    /// Get the path as a reference
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }

    /// Convert into the underlying PathBuf
    #[must_use]
    pub fn into_path_buf(self) -> PathBuf {
        self.0
    }
}

impl AsRef<Path> for PackageDir {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

/// Errors that can occur when validating a PackageDir
#[derive(Error, Debug, Clone, Diagnostic)]
pub enum PackageDirError {
    /// The path does not exist
    #[error("path does not exist: {0}")]
    #[diagnostic(
        code(cuenv::package_dir::not_found),
        help("Make sure the directory exists and you have permission to access it")
    )]
    NotFound(String),

    /// The path exists but is not a directory
    #[error("path is not a directory: {0}")]
    #[diagnostic(
        code(cuenv::package_dir::not_directory),
        help("The path must point to a directory, not a file")
    )]
    NotADirectory(String),

    /// An I/O error occurred while checking the path
    #[error("io error accessing path: {0}")]
    #[diagnostic(
        code(cuenv::package_dir::io_error),
        help("Check file permissions and ensure you have access to the path")
    )]
    Io(String),
}

impl TryFrom<&Path> for PackageDir {
    type Error = PackageDirError;

    /// Try to create a PackageDir from a path
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cuenv_core::PackageDir;
    /// use std::path::Path;
    ///
    /// match PackageDir::try_from(Path::new(".")) {
    ///     Ok(dir) => println!("Valid directory"),
    ///     Err(e) => eprintln!("Error: {}", e),
    /// }
    /// ```
    fn try_from(input: &Path) -> std::result::Result<Self, Self::Error> {
        match std::fs::metadata(input) {
            Ok(meta) => {
                if meta.is_dir() {
                    Ok(PackageDir(input.to_path_buf()))
                } else {
                    Err(PackageDirError::NotADirectory(input.display().to_string()))
                }
            }
            Err(e) => {
                if e.kind() == std::io::ErrorKind::NotFound {
                    Err(PackageDirError::NotFound(input.display().to_string()))
                } else {
                    Err(PackageDirError::Io(e.to_string()))
                }
            }
        }
    }
}

/// A validated CUE package name
///
/// Package names must follow CUE naming conventions:
/// - 1-64 characters in length
/// - Start with alphanumeric character (A-Z, a-z, 0-9)
/// - Contain only alphanumeric, hyphen (-), or underscore (_) characters
///
/// # Examples
///
/// ```rust
/// use cuenv_core::PackageName;
///
/// // Valid package names
/// assert!(PackageName::try_from("my-package").is_ok());
/// assert!(PackageName::try_from("package_123").is_ok());
/// assert!(PackageName::try_from("app").is_ok());
///
/// // Invalid package names
/// assert!(PackageName::try_from("-invalid").is_err());  // starts with hyphen
/// assert!(PackageName::try_from("invalid.name").is_err());  // contains dot
/// assert!(PackageName::try_from("").is_err());  // empty
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct PackageName(String);

impl PackageName {
    /// Get the package name as a string slice
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Convert into the underlying String
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for PackageName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

/// Errors that can occur when validating a PackageName
#[derive(Error, Debug, Clone, Diagnostic)]
pub enum PackageNameError {
    /// The package name is invalid
    #[error("invalid package name: {0}")]
    #[diagnostic(
        code(cuenv::package_name::invalid),
        help(
            "Package names must be 1-64 characters, start with alphanumeric, and contain only alphanumeric, hyphen, or underscore characters"
        )
    )]
    Invalid(String),
}

impl TryFrom<&str> for PackageName {
    type Error = PackageNameError;

    /// Try to create a PackageName from a string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cuenv_core::PackageName;
    ///
    /// match PackageName::try_from("my-package") {
    ///     Ok(name) => println!("Valid package name: {}", name),
    ///     Err(e) => eprintln!("Error: {}", e),
    /// }
    /// ```
    fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
        let bytes = s.as_bytes();

        // Check length bounds
        if bytes.is_empty() || bytes.len() > 64 {
            return Err(PackageNameError::Invalid(s.to_string()));
        }

        // Check first character must be alphanumeric
        let first = bytes[0];
        let is_alnum =
            |b: u8| b.is_ascii_uppercase() || b.is_ascii_lowercase() || b.is_ascii_digit();

        if !is_alnum(first) {
            return Err(PackageNameError::Invalid(s.to_string()));
        }

        // Check all characters are valid
        let valid = |b: u8| is_alnum(b) || b == b'-' || b == b'_';
        for &b in bytes {
            if !valid(b) {
                return Err(PackageNameError::Invalid(s.to_string()));
            }
        }

        Ok(PackageName(s.to_string()))
    }
}

impl TryFrom<String> for PackageName {
    type Error = PackageNameError;

    /// Try to create a PackageName from an owned String
    fn try_from(s: String) -> std::result::Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use miette::SourceSpan;
    use std::path::Path;

    #[test]
    fn test_error_configuration() {
        let err = Error::configuration("test message");
        assert_eq!(err.to_string(), "Configuration error: test message");

        if let Error::Configuration { message, .. } = err {
            assert_eq!(message, "test message");
        } else {
            panic!("Expected Configuration error");
        }
    }

    #[test]
    fn test_error_configuration_with_source() {
        let src = "test source code";
        let span = SourceSpan::from(0..4);
        let err = Error::configuration_with_source("config error", src, Some(span));

        if let Error::Configuration {
            src: source,
            span: s,
            message,
        } = err
        {
            assert_eq!(source, "test source code");
            assert_eq!(s, Some(SourceSpan::from(0..4)));
            assert_eq!(message, "config error");
        } else {
            panic!("Expected Configuration error");
        }
    }

    #[test]
    fn test_error_ffi() {
        let err = Error::ffi("test_function", "FFI failed");
        assert_eq!(
            err.to_string(),
            "FFI operation failed in test_function: FFI failed"
        );

        if let Error::Ffi {
            function,
            message,
            help,
        } = err
        {
            assert_eq!(function, "test_function");
            assert_eq!(message, "FFI failed");
            assert!(help.is_none());
        } else {
            panic!("Expected Ffi error");
        }
    }

    #[test]
    fn test_error_ffi_with_help() {
        let err = Error::ffi_with_help("test_func", "error msg", "try this instead");

        if let Error::Ffi {
            function,
            message,
            help,
        } = err
        {
            assert_eq!(function, "test_func");
            assert_eq!(message, "error msg");
            assert_eq!(help, Some("try this instead".to_string()));
        } else {
            panic!("Expected Ffi error");
        }
    }

    #[test]
    fn test_error_cue_parse() {
        let path = Path::new("/test/path.cue");
        let err = Error::cue_parse(path, "parsing failed");
        assert_eq!(err.to_string(), "CUE parsing failed: parsing failed");

        if let Error::CueParse {
            path: p, message, ..
        } = err
        {
            assert_eq!(p.as_ref(), Path::new("/test/path.cue"));
            assert_eq!(message, "parsing failed");
        } else {
            panic!("Expected CueParse error");
        }
    }

    #[test]
    fn test_error_cue_parse_with_source() {
        let path = Path::new("/test/file.cue");
        let src = "package test";
        let span = SourceSpan::from(0..7);
        let suggestions = vec!["Check syntax".to_string(), "Verify imports".to_string()];

        let err = Error::cue_parse_with_source(
            path,
            "parse error",
            src,
            Some(span),
            Some(suggestions.clone()),
        );

        if let Error::CueParse {
            path: p,
            src: source,
            span: s,
            message,
            suggestions: sugg,
        } = err
        {
            assert_eq!(p.as_ref(), Path::new("/test/file.cue"));
            assert_eq!(source, Some("package test".to_string()));
            assert_eq!(s, Some(SourceSpan::from(0..7)));
            assert_eq!(message, "parse error");
            assert_eq!(sugg, Some(suggestions));
        } else {
            panic!("Expected CueParse error");
        }
    }

    #[test]
    fn test_error_validation() {
        let err = Error::validation("validation failed");
        assert_eq!(err.to_string(), "Validation failed: validation failed");

        if let Error::Validation {
            message, related, ..
        } = err
        {
            assert_eq!(message, "validation failed");
            assert!(related.is_empty());
        } else {
            panic!("Expected Validation error");
        }
    }

    #[test]
    fn test_error_validation_with_source() {
        let src = "test validation source";
        let span = SourceSpan::from(5..15);
        let err = Error::validation_with_source("validation error", src, Some(span));

        if let Error::Validation {
            src: source,
            span: s,
            message,
            ..
        } = err
        {
            assert_eq!(source, Some("test validation source".to_string()));
            assert_eq!(s, Some(SourceSpan::from(5..15)));
            assert_eq!(message, "validation error");
        } else {
            panic!("Expected Validation error");
        }
    }

    #[test]
    fn test_error_timeout() {
        let err = Error::Timeout { seconds: 30 };
        assert_eq!(err.to_string(), "Operation timed out after 30 seconds");
    }

    #[test]
    fn test_error_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err: Error = io_err.into();

        if let Error::Io { operation, .. } = err {
            assert_eq!(operation, "unknown (unmapped error conversion)");
        } else {
            panic!("Expected Io error");
        }
    }

    #[test]
    fn test_error_from_utf8_error() {
        let bytes = vec![0xFF, 0xFE];
        let utf8_err = std::str::from_utf8(&bytes).unwrap_err();
        let err: Error = utf8_err.into();

        assert!(matches!(err, Error::Utf8 { .. }));
    }

    #[test]
    fn test_limits_default() {
        let limits = Limits::default();
        assert_eq!(limits.max_path_length, 4096);
        assert_eq!(limits.max_package_name_length, 256);
        assert_eq!(limits.max_output_size, 100 * 1024 * 1024);
    }

    #[test]
    fn test_result_type_alias() {
        let ok_result: Result<i32> = Ok(42);
        assert!(ok_result.is_ok());
        if let Ok(value) = ok_result {
            assert_eq!(value, 42);
        }

        let err_result: Result<i32> = Err(Error::configuration("test"));
        assert!(err_result.is_err());
    }

    #[test]
    fn test_error_display() {
        let errors = vec![
            (Error::configuration("test"), "Configuration error: test"),
            (
                Error::ffi("func", "msg"),
                "FFI operation failed in func: msg",
            ),
            (
                Error::cue_parse(Path::new("/test"), "msg"),
                "CUE parsing failed: msg",
            ),
            (Error::validation("msg"), "Validation failed: msg"),
            (
                Error::Timeout { seconds: 10 },
                "Operation timed out after 10 seconds",
            ),
        ];

        for (error, expected) in errors {
            assert_eq!(error.to_string(), expected);
        }
    }

    #[test]
    fn test_error_diagnostic_codes() {
        use miette::Diagnostic;

        let config_err = Error::configuration("test");
        assert_eq!(
            config_err.code().unwrap().to_string(),
            "cuenv::config::invalid"
        );

        let ffi_err = Error::ffi("func", "msg");
        assert_eq!(ffi_err.code().unwrap().to_string(), "cuenv::ffi::error");

        let cue_err = Error::cue_parse(Path::new("/test"), "msg");
        assert_eq!(
            cue_err.code().unwrap().to_string(),
            "cuenv::cue::parse_error"
        );

        let validation_err = Error::validation("msg");
        assert_eq!(
            validation_err.code().unwrap().to_string(),
            "cuenv::validation::failed"
        );

        let timeout_err = Error::Timeout { seconds: 5 };
        assert_eq!(timeout_err.code().unwrap().to_string(), "cuenv::timeout");
    }

    #[test]
    fn test_package_dir_validation() {
        // Current directory should be valid
        let result = PackageDir::try_from(Path::new("."));
        assert!(result.is_ok(), "Current directory should be valid");

        // Get methods should work
        let pkg_dir = result.unwrap();
        assert_eq!(pkg_dir.as_path(), Path::new("."));
        assert_eq!(pkg_dir.as_ref(), Path::new("."));
        assert_eq!(pkg_dir.into_path_buf(), PathBuf::from("."));

        // Non-existent directory should fail with NotFound
        let result = PackageDir::try_from(Path::new("/path/does/not/exist"));
        assert!(result.is_err());
        match result.unwrap_err() {
            PackageDirError::NotFound(_) => {} // Expected
            other => panic!("Expected NotFound error, got: {:?}", other),
        }

        // Path to a file should fail with NotADirectory
        // Create a temporary file
        let temp_path = std::env::temp_dir().join("cuenv_test_file");
        let file = std::fs::File::create(&temp_path).unwrap();
        drop(file);

        let result = PackageDir::try_from(temp_path.as_path());
        assert!(result.is_err());
        match result.unwrap_err() {
            PackageDirError::NotADirectory(_) => {} // Expected
            other => panic!("Expected NotADirectory error, got: {:?}", other),
        }

        // Clean up
        std::fs::remove_file(temp_path).ok();
    }

    #[test]
    fn test_package_name_validation() {
        // Valid package names
        let max_len_string = "a".repeat(64);
        let valid_names = vec![
            "my-package",
            "package_123",
            "a",        // Single character
            "A",        // Uppercase
            "0package", // Starts with number
            "package-with-hyphens",
            "package_with_underscores",
            max_len_string.as_str(), // Max length
        ];

        for name in valid_names {
            let result = PackageName::try_from(name);
            assert!(result.is_ok(), "'{}' should be valid", name);

            // Test the String variant too
            let result = PackageName::try_from(name.to_string());
            assert!(result.is_ok(), "'{}' as String should be valid", name);

            // Verify methods work correctly
            let pkg_name = result.unwrap();
            assert_eq!(pkg_name.as_str(), name);
            assert_eq!(pkg_name.as_ref(), name);
            assert_eq!(pkg_name.to_string(), name);
            assert_eq!(pkg_name.into_string(), name.to_string());
        }

        // Invalid package names
        let too_long_string = "a".repeat(65);
        let invalid_names = vec![
            "",                       // Empty
            "-invalid",               // Starts with hyphen
            "_invalid",               // Starts with underscore
            "invalid.name",           // Contains dot
            "invalid/name",           // Contains slash
            "invalid:name",           // Contains colon
            too_long_string.as_str(), // Too long
            "invalid@name",           // Contains @
            "invalid#name",           // Contains #
            "invalid name",           // Contains space
        ];

        for name in invalid_names {
            let result = PackageName::try_from(name);
            assert!(result.is_err(), "'{}' should be invalid", name);

            // Verify error type is correct
            assert!(matches!(result.unwrap_err(), PackageNameError::Invalid(_)));
        }
    }
}