sublime_pkg_tools 0.0.27

Package and version management toolkit for Node.js projects with changeset support
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
//! Changeset error types for package tools.
//!
//! **What**: Defines error types specific to changeset creation, loading, storage,
//! archiving, and management operations.
//!
//! **How**: Uses `thiserror` for error definitions with rich context information including
//! changeset IDs, branch names, storage paths, and git integration details. Implements
//! `AsRef<str>` for string conversion.
//!
//! **Why**: To provide clear, actionable error messages for changeset operations, enabling
//! users to quickly identify and fix issues with changeset storage, validation, and
//! git integration.
//!
//! # Examples
//!
//! ```rust
//! use sublime_pkg_tools::error::{ChangesetError, ChangesetResult};
//!
//! fn load_changeset(branch: &str) -> ChangesetResult<String> {
//!     if branch.is_empty() {
//!         return Err(ChangesetError::InvalidBranch {
//!             branch: branch.to_string(),
//!             reason: "Branch name cannot be empty".to_string(),
//!         });
//!     }
//!     Ok("changeset-data".to_string())
//! }
//! ```

use std::path::PathBuf;
use thiserror::Error;

/// Result type alias for changeset operations.
///
/// This type alias simplifies error handling in changeset-related functions
/// by defaulting to `ChangesetError` as the error type.
///
/// # Examples
///
/// ```rust
/// use sublime_pkg_tools::error::{ChangesetError, ChangesetResult};
///
/// fn create_changeset() -> ChangesetResult<String> {
///     Ok("changeset-id".to_string())
/// }
/// ```
pub type ChangesetResult<T> = Result<T, ChangesetError>;

/// Errors that can occur during changeset operations.
///
/// This enum covers all possible error scenarios when working with changesets,
/// including storage operations, validation, git integration, and archiving.
///
/// # Examples
///
/// ## Handling changeset errors
///
/// ```rust
/// use sublime_pkg_tools::error::ChangesetError;
/// use std::path::PathBuf;
///
/// fn handle_changeset_error(error: ChangesetError) {
///     match error {
///         ChangesetError::NotFound { branch } => {
///             eprintln!("Changeset not found for branch: {}", branch);
///         }
///         ChangesetError::StorageError { path, reason } => {
///             eprintln!("Storage error at {}: {}", path.display(), reason);
///         }
///         _ => eprintln!("Changeset error: {}", error),
///     }
/// }
/// ```
///
/// ## Converting from string representation
///
/// ```rust
/// use sublime_pkg_tools::error::ChangesetError;
///
/// let error = ChangesetError::InvalidBranch {
///     branch: "".to_string(),
///     reason: "empty branch name".to_string(),
/// };
///
/// let error_msg: &str = error.as_ref();
/// assert!(error_msg.contains("invalid branch"));
/// ```
#[derive(Debug, Error, Clone)]
pub enum ChangesetError {
    /// Changeset not found for the specified branch.
    ///
    /// This error occurs when attempting to load a changeset that does not exist
    /// for the given branch name.
    #[error("Changeset not found for branch '{branch}'")]
    NotFound {
        /// The branch name for which the changeset was not found.
        branch: String,
    },

    /// Invalid branch name provided.
    ///
    /// This error occurs when a branch name is empty, contains invalid characters,
    /// or does not meet the required format.
    #[error("Invalid branch name '{branch}': {reason}")]
    InvalidBranch {
        /// The invalid branch name.
        branch: String,
        /// Description of why the branch name is invalid.
        reason: String,
    },

    /// Changeset validation failed.
    /// Configuration validation failed with one or more validation errors.
    ///
    /// This error occurs when the changeset structure is invalid or incomplete,
    /// such as missing required fields or containing invalid data.
    #[error("Changeset validation failed")]
    ValidationFailed {
        /// List of validation error messages.
        errors: Vec<String>,
    },

    /// Storage operation failed.
    ///
    /// This error occurs when reading from or writing to changeset storage fails
    /// due to filesystem errors, permission issues, or corruption.
    #[error("Changeset storage error at '{path}': {reason}")]
    StorageError {
        /// Path where the storage error occurred.
        path: PathBuf,
        /// Description of the storage error.
        reason: String,
    },

    /// Failed to serialize or deserialize changeset data.
    ///
    /// This error occurs when converting changeset data to/from JSON or other
    /// serialization formats fails.
    #[error("Failed to {operation} changeset data: {reason}")]
    SerializationError {
        /// The operation that failed (e.g., "serialize", "deserialize").
        operation: String,
        /// Description of the serialization error.
        reason: String,
    },

    /// Changeset already exists for the branch.
    ///
    /// This error occurs when attempting to create a new changeset for a branch
    /// that already has one.
    #[error("Changeset already exists for branch '{branch}' at '{path}'")]
    AlreadyExists {
        /// The branch name.
        branch: String,
        /// Path to the existing changeset file.
        path: PathBuf,
    },

    /// Git operation failed during changeset operations.
    ///
    /// This error occurs when git commands or operations fail during changeset
    /// management, such as retrieving commit information.
    #[error("Git operation failed: {operation} - {reason}")]
    GitError {
        /// Description of the git operation that failed.
        operation: String,
        /// Detailed error message from git.
        reason: String,
    },

    /// Failed to archive changeset.
    ///
    /// This error occurs when moving a changeset to the history/archive location
    /// fails, possibly due to filesystem issues.
    #[error("Failed to archive changeset for branch '{branch}': {reason}")]
    ArchiveError {
        /// The branch name of the changeset being archived.
        branch: String,
        /// Description of why archiving failed.
        reason: String,
    },

    /// Invalid changeset ID format.
    ///
    /// This error occurs when a changeset ID does not match the expected format
    /// or contains invalid characters.
    #[error("Invalid changeset ID '{id}': {reason}")]
    InvalidId {
        /// The invalid changeset ID.
        id: String,
        /// Description of why the ID is invalid.
        reason: String,
    },

    /// Package not found in changeset.
    ///
    /// This error occurs when attempting to access or modify a package in a
    /// changeset that doesn't contain that package.
    #[error("Package '{package}' not found in changeset for branch '{branch}'")]
    PackageNotInChangeset {
        /// The branch name.
        branch: String,
        /// The package name that was not found.
        package: String,
    },

    /// Invalid environment name.
    ///
    /// This error occurs when an environment name is not in the list of
    /// configured available environments.
    #[error("Invalid environment '{environment}': not in available environments {available:?}")]
    InvalidEnvironment {
        /// The invalid environment name.
        environment: String,
        /// List of available/valid environment names.
        available: Vec<String>,
    },

    /// Empty changeset with no packages.
    ///
    /// This error occurs when attempting to save or process a changeset that
    /// contains no packages.
    #[error("Changeset for branch '{branch}' is empty (no packages)")]
    EmptyChangeset {
        /// The branch name of the empty changeset.
        branch: String,
    },

    /// Commit not found in repository.
    ///
    /// This error occurs when attempting to add a commit to a changeset but
    /// the commit hash does not exist in the git repository.
    #[error("Commit '{commit}' not found in repository")]
    CommitNotFound {
        /// The commit hash that was not found.
        commit: String,
    },

    /// Invalid commit hash format.
    ///
    /// This error occurs when a commit hash does not match the expected format
    /// (typically 40-character hex string for full SHA).
    #[error("Invalid commit hash '{commit}': {reason}")]
    InvalidCommit {
        /// The invalid commit hash.
        commit: String,
        /// Description of why the commit hash is invalid.
        reason: String,
    },

    /// History query failed.
    ///
    /// This error occurs when querying the changeset history fails, possibly
    /// due to corrupted archive files or filesystem issues.
    #[error("Failed to query changeset history: {reason}")]
    HistoryQueryFailed {
        /// Description of why the history query failed.
        reason: String,
    },

    /// Permission denied for changeset operation.
    ///
    /// This error occurs when the process lacks necessary permissions to read,
    /// write, or modify changeset files.
    #[error("Permission denied for changeset operation at '{path}': {operation}")]
    PermissionDenied {
        /// Path where permission was denied.
        path: PathBuf,
        /// The operation that was attempted.
        operation: String,
    },

    /// Concurrent modification detected.
    ///
    /// This error occurs when a changeset file has been modified by another
    /// process between read and write operations.
    #[error(
        "Concurrent modification detected for changeset '{branch}': expected timestamp {expected}, found {actual}"
    )]
    ConcurrentModification {
        /// The branch name of the changeset.
        branch: String,
        /// Expected last modification timestamp.
        expected: String,
        /// Actual last modification timestamp.
        actual: String,
    },

    /// Invalid changeset path configuration.
    ///
    /// This error occurs when the configured changeset storage path is invalid,
    /// inaccessible, or points to an invalid location.
    #[error("Invalid changeset path configuration '{path}': {reason}")]
    InvalidPath {
        /// The invalid path.
        path: PathBuf,
        /// Description of why the path is invalid.
        reason: String,
    },

    /// Failed to lock changeset for exclusive access.
    ///
    /// This error occurs when attempting to acquire an exclusive lock on a
    /// changeset file fails, possibly due to another process holding the lock.
    #[error("Failed to lock changeset for branch '{branch}': {reason}")]
    LockFailed {
        /// The branch name of the changeset.
        branch: String,
        /// Description of why the lock failed.
        reason: String,
    },

    /// Git integration operation failed.
    ///
    /// This error occurs when git integration operations fail during package
    /// detection, commit analysis, or other git-related operations.
    #[error("Git integration failed during {operation}: {reason}")]
    GitIntegration {
        /// Description of the git integration operation that failed.
        operation: String,
        /// Detailed error message.
        reason: String,
    },
}

impl AsRef<str> for ChangesetError {
    /// Returns a string representation of the error.
    ///
    /// This implementation enables the error to be used in contexts that require
    /// string references, such as logging or display operations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::error::ChangesetError;
    ///
    /// let error = ChangesetError::NotFound {
    ///     branch: "feature/new-api".to_string(),
    /// };
    ///
    /// let msg: &str = error.as_ref();
    /// assert!(msg.contains("not found"));
    /// ```
    fn as_ref(&self) -> &str {
        match self {
            Self::NotFound { .. } => "changeset not found",
            Self::InvalidBranch { .. } => "invalid branch name",
            Self::ValidationFailed { .. } => "changeset validation failed",
            Self::StorageError { .. } => "changeset storage error",
            Self::SerializationError { .. } => "changeset serialization error",
            Self::AlreadyExists { .. } => "changeset already exists",
            Self::GitError { .. } => "git error",
            Self::ArchiveError { .. } => "changeset archive error",
            Self::InvalidId { .. } => "invalid changeset id",
            Self::PackageNotInChangeset { .. } => "package not in changeset",
            Self::InvalidEnvironment { .. } => "invalid environment",
            Self::EmptyChangeset { .. } => "empty changeset",
            Self::CommitNotFound { .. } => "commit not found",
            Self::InvalidCommit { .. } => "invalid commit",
            Self::HistoryQueryFailed { .. } => "history query failed",
            Self::PermissionDenied { .. } => "permission denied",
            Self::ConcurrentModification { .. } => "concurrent modification",
            Self::InvalidPath { .. } => "invalid changeset path",
            Self::LockFailed { .. } => "lock failed",
            Self::GitIntegration { .. } => "git integration error",
        }
    }
}

impl ChangesetError {
    /// Returns the number of errors for `ValidationFailed` variant.
    ///
    /// This helper method provides a convenient way to get the count of validation
    /// errors without pattern matching.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::error::ChangesetError;
    ///
    /// let error = ChangesetError::ValidationFailed {
    ///     errors: vec![
    ///         "Missing bump type".to_string(),
    ///         "Empty packages list".to_string(),
    ///     ],
    /// };
    ///
    /// assert_eq!(error.count(), 2);
    /// ```
    #[must_use]
    pub fn count(&self) -> usize {
        match self {
            Self::ValidationFailed { errors } => errors.len(),
            _ => 1,
        }
    }

    /// Returns the formatted error list as a single string.
    ///
    /// This helper method formats all validation errors as a bulleted list,
    /// useful for displaying multiple errors in a user-friendly format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::error::ChangesetError;
    ///
    /// let error = ChangesetError::ValidationFailed {
    ///     errors: vec![
    ///         "Invalid bump".to_string(),
    ///         "Missing packages".to_string(),
    ///     ],
    /// };
    ///
    /// let formatted = error.errors();
    /// assert!(formatted.contains("Invalid bump"));
    /// assert!(formatted.contains("Missing packages"));
    /// ```
    #[must_use]
    pub fn errors(&self) -> String {
        match self {
            Self::ValidationFailed { errors } => {
                errors.iter().map(|e| format!("  - {}", e)).collect::<Vec<_>>().join("\n")
            }
            _ => self.to_string(),
        }
    }

    /// Returns whether this error is transient and might succeed on retry.
    ///
    /// Some changeset errors (like concurrent modifications or lock failures)
    /// might be recoverable through retry, while others (like validation errors) are not.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::error::ChangesetError;
    /// use std::path::PathBuf;
    ///
    /// let lock_error = ChangesetError::LockFailed {
    ///     branch: "main".to_string(),
    ///     reason: "already locked".to_string(),
    /// };
    /// assert!(lock_error.is_transient());
    ///
    /// let validation_error = ChangesetError::ValidationFailed {
    ///     errors: vec!["invalid data".to_string()],
    /// };
    /// assert!(!validation_error.is_transient());
    /// ```
    #[must_use]
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            Self::LockFailed { .. }
                | Self::ConcurrentModification { .. }
                | Self::StorageError { .. }
                | Self::GitError { .. }
        )
    }
}