subx-cli 1.6.0

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
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
//! Comprehensive error types for the SubX CLI application operations.
//!
//! This module defines the `SubXError` enum covering all error conditions
//! that can occur during subtitle processing, AI service integration,
//! audio analysis, file matching, and general command execution.
//!
//! It also provides helper methods to construct errors and generate
//! user-friendly messages.
use thiserror::Error;

/// Represents all possible errors in the SubX application.
///
/// Each variant provides specific context to facilitate debugging and
/// user-friendly reporting.
///
/// # Examples
///
/// ```rust
/// use subx_cli::error::{SubXError, SubXResult};
///
/// fn example() -> SubXResult<()> {
///     Err(SubXError::SubtitleFormat {
///         format: "SRT".to_string(),
///         message: "Invalid timestamp format".to_string(),
///     })
/// }
/// ```
///
/// # Exit Codes
///
/// Each error variant maps to an exit code via `SubXError::exit_code`.
#[derive(Error, Debug)]
pub enum SubXError {
    /// I/O operation failed during file system access.
    ///
    /// This variant wraps `std::io::Error` and provides context about
    /// file operations that failed.
    ///
    /// # Common Causes
    /// - Permission issues
    /// - Insufficient disk space
    /// - Network filesystem errors
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Configuration error due to invalid or missing settings.
    ///
    /// Contains a human-readable message describing the issue.
    #[error("Configuration error: {message}")]
    Config {
        /// Description of the configuration error
        message: String,
    },

    /// Subtitle format error indicating invalid timestamps or structure.
    ///
    /// Provides the subtitle format and detailed message.
    #[error("Subtitle format error [{format}]: {message}")]
    SubtitleFormat {
        /// The subtitle format that caused the error (e.g., "SRT", "ASS")
        format: String,
        /// Detailed error message describing the issue
        message: String,
    },

    /// AI service encountered an error.
    ///
    /// Captures the raw error message from the AI provider.
    #[error("AI service error: {0}")]
    AiService(String),

    /// API request error with specified source.
    ///
    /// Represents errors that occur during API requests, providing both
    /// the error message and the source of the API error.
    #[error("API error [{source:?}]: {message}")]
    Api {
        /// Error message from the API
        message: String,
        /// Source of the API error
        source: ApiErrorSource,
    },

    /// Audio processing error during analysis or format conversion.
    ///
    /// Provides a message describing the audio processing failure.
    #[error("Audio processing error: {message}")]
    AudioProcessing {
        /// Description of the audio processing error
        message: String,
    },

    /// Error during file matching or discovery.
    ///
    /// Contains details about path resolution or pattern matching failures.
    #[error("File matching error: {message}")]
    FileMatching {
        /// Description of the file matching error
        message: String,
    },
    /// Indicates that a file operation failed because the target exists.
    #[error("File already exists: {0}")]
    FileAlreadyExists(String),
    /// Indicates that the specified file was not found.
    #[error("File not found: {0}")]
    FileNotFound(String),
    /// Invalid file name encountered.
    #[error("Invalid file name: {0}")]
    InvalidFileName(String),
    /// Generic file operation failure with message.
    #[error("File operation failed: {0}")]
    FileOperationFailed(String),
    /// Generic command execution error.
    #[error("{0}")]
    CommandExecution(String),

    /// No input path was specified for the operation.
    #[error("No input path specified")]
    NoInputSpecified,

    /// The provided path is invalid or malformed.
    #[error("Invalid path: {0}")]
    InvalidPath(std::path::PathBuf),

    /// The specified path does not exist on the filesystem.
    #[error("Path not found: {0}")]
    PathNotFound(std::path::PathBuf),

    /// Unable to read the specified directory.
    #[error("Unable to read directory: {path}")]
    DirectoryReadError {
        /// The directory path that could not be read
        path: std::path::PathBuf,
        /// The underlying I/O error
        #[source]
        source: std::io::Error,
    },

    /// Invalid synchronization configuration: please specify video and subtitle files, or use -i parameter for batch processing.
    #[error(
        "Invalid sync configuration: please specify video and subtitle files, or use -i parameter for batch processing"
    )]
    InvalidSyncConfiguration,

    /// Unsupported file type encountered.
    #[error("Unsupported file type: {0}")]
    UnsupportedFileType(String),

    /// Catch-all error variant wrapping any other failure.
    #[error("Unknown error: {0}")]
    Other(#[from] anyhow::Error),
}

// Unit test: SubXError error types and helper methods
#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    #[test]
    fn test_config_error_creation() {
        let error = SubXError::config("test config error");
        assert!(matches!(error, SubXError::Config { .. }));
        assert_eq!(error.to_string(), "Configuration error: test config error");
    }

    #[test]
    fn test_subtitle_format_error_creation() {
        let error = SubXError::subtitle_format("SRT", "invalid format");
        assert!(matches!(error, SubXError::SubtitleFormat { .. }));
        let msg = error.to_string();
        assert!(msg.contains("SRT"));
        assert!(msg.contains("invalid format"));
    }

    #[test]
    fn test_audio_processing_error_creation() {
        let error = SubXError::audio_processing("decode failed");
        assert!(matches!(error, SubXError::AudioProcessing { .. }));
        assert_eq!(error.to_string(), "Audio processing error: decode failed");
    }

    #[test]
    fn test_file_matching_error_creation() {
        let error = SubXError::file_matching("match failed");
        assert!(matches!(error, SubXError::FileMatching { .. }));
        assert_eq!(error.to_string(), "File matching error: match failed");
    }

    #[test]
    fn test_io_error_conversion() {
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let subx_error: SubXError = io_error.into();
        assert!(matches!(subx_error, SubXError::Io(_)));
    }

    #[test]
    fn test_exit_codes() {
        assert_eq!(SubXError::config("test").exit_code(), 2);
        assert_eq!(SubXError::subtitle_format("SRT", "test").exit_code(), 4);
        assert_eq!(SubXError::audio_processing("test").exit_code(), 5);
        assert_eq!(SubXError::file_matching("test").exit_code(), 6);
    }

    #[test]
    fn test_user_friendly_messages() {
        let config_error = SubXError::config("missing key");
        let message = config_error.user_friendly_message();
        assert!(message.contains("Configuration error:"));
        assert!(message.contains("subx-cli config --help"));

        let ai_error = SubXError::ai_service("network failure".to_string());
        let message = ai_error.user_friendly_message();
        assert!(message.contains("AI service error:"));
        assert!(message.contains("check network connection"));
    }

    /// Audit: enumerates every `SubXError` variant and asserts that a
    /// representative instance — built from non-sensitive dummy data —
    /// never surfaces an OpenAI-style API key prefix (`sk-`) through
    /// `Display`, `Debug`, or `user_friendly_message()`. If you add a
    /// new variant, extend this list so the audit remains exhaustive.
    ///
    /// Separately, this test also exercises the sanitizing construction
    /// paths (`From<reqwest::Error>`-style flows via the AI client's
    /// `error_sanitizer` helpers) to confirm that when input *does*
    /// contain an `sk-*` secret, it is stripped before wrapping it in
    /// `SubXError::AiService`.
    #[test]
    fn test_no_api_key_leaks_in_any_variant() {
        use crate::services::ai::error_sanitizer::{
            DEFAULT_ERROR_BODY_MAX_LEN, sanitize_url_in_error, truncate_error_body,
        };
        use std::path::PathBuf;

        // 1. Canonical variant audit: benign dummy data must never yield
        //    an `sk-` substring.
        let variants: Vec<SubXError> = vec![
            SubXError::Io(io::Error::other("disk error")),
            SubXError::Config {
                message: "missing key".to_string(),
            },
            SubXError::SubtitleFormat {
                format: "SRT".to_string(),
                message: "bad timestamp".to_string(),
            },
            SubXError::AiService("upstream service failed".to_string()),
            SubXError::Api {
                message: "auth failed".to_string(),
                source: ApiErrorSource::OpenAI,
            },
            SubXError::AudioProcessing {
                message: "codec failure".to_string(),
            },
            SubXError::FileMatching {
                message: "pattern mismatch".to_string(),
            },
            SubXError::FileAlreadyExists("/tmp/example".to_string()),
            SubXError::FileNotFound("/tmp/example".to_string()),
            SubXError::InvalidFileName("bad?name".to_string()),
            SubXError::FileOperationFailed("rename failed".to_string()),
            SubXError::CommandExecution("exit 1".to_string()),
            SubXError::NoInputSpecified,
            SubXError::InvalidPath(PathBuf::from("/tmp/example")),
            SubXError::PathNotFound(PathBuf::from("/tmp/example")),
            SubXError::DirectoryReadError {
                path: PathBuf::from("/tmp/example"),
                source: io::Error::other("denied"),
            },
            SubXError::InvalidSyncConfiguration,
            SubXError::UnsupportedFileType("xyz".to_string()),
            SubXError::Other(anyhow::anyhow!("wrapped")),
        ];

        for err in &variants {
            let display = format!("{}", err);
            let debug = format!("{:?}", err);
            let friendly = err.user_friendly_message();
            for (label, text) in [
                ("Display", &display),
                ("Debug", &debug),
                ("friendly", &friendly),
            ] {
                assert!(
                    !text.contains("sk-"),
                    "{} surface for variant {:?} contains `sk-` prefix: {}",
                    label,
                    err,
                    text,
                );
            }
        }

        // 2. Sanitizing construction paths: API keys injected via the
        //    upstream response body or URL query string must be stripped
        //    before being embedded into `SubXError::AiService`.
        const SECRET: &str = "sk-test-key-12345";
        let upstream_body = format!(
            "{{\"error\": \"invalid\", \"echoed\": \"Bearer {}\"}}",
            SECRET
        );
        let truncated = truncate_error_body(&upstream_body, DEFAULT_ERROR_BODY_MAX_LEN);
        // Helper does not itself mask secrets shorter than the limit; this
        // documents that short bodies pass through unchanged so upstream
        // callers must continue to keep secrets out of request bodies.
        assert!(truncated.contains(SECRET));

        let url_leak = format!(
            "request error: https://api.example.com/v1/chat?api-key={}",
            SECRET
        );
        let cleaned = sanitize_url_in_error(&url_leak);
        assert!(!cleaned.contains("sk-test-key"));
        let wrapped = SubXError::AiService(cleaned);
        assert!(!format!("{}", wrapped).contains("sk-test-key"));
        assert!(!format!("{:?}", wrapped).contains("sk-test-key"));
    }
}

// Convert reqwest error to AI service error
impl From<reqwest::Error> for SubXError {
    fn from(err: reqwest::Error) -> Self {
        let raw = err.to_string();
        // Strip query strings from any embedded URLs, since reqwest's Display
        // implementation includes the full request URL which may carry
        // sensitive credentials (e.g. `?api-key=...`).
        let sanitized = crate::services::ai::error_sanitizer::sanitize_url_in_error(&raw);
        SubXError::AiService(sanitized)
    }
}

// Convert file exploration error to file matching error
impl From<walkdir::Error> for SubXError {
    fn from(err: walkdir::Error) -> Self {
        SubXError::FileMatching {
            message: err.to_string(),
        }
    }
}
// Convert symphonia error to audio processing error
impl From<symphonia::core::errors::Error> for SubXError {
    fn from(err: symphonia::core::errors::Error) -> Self {
        SubXError::audio_processing(err.to_string())
    }
}

// Convert config crate error to configuration error
impl From<config::ConfigError> for SubXError {
    fn from(err: config::ConfigError) -> Self {
        match err {
            config::ConfigError::NotFound(path) => SubXError::Config {
                message: format!("Configuration file not found: {}", path),
            },
            config::ConfigError::Message(msg) => SubXError::Config { message: msg },
            _ => SubXError::Config {
                message: format!("Configuration error: {}", err),
            },
        }
    }
}

impl From<serde_json::Error> for SubXError {
    fn from(err: serde_json::Error) -> Self {
        SubXError::Config {
            message: format!("JSON serialization/deserialization error: {}", err),
        }
    }
}

/// Specialized `Result` type for SubX operations.
pub type SubXResult<T> = Result<T, SubXError>;

impl SubXError {
    /// Create a configuration error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::config("invalid setting");
    /// assert_eq!(err.to_string(), "Configuration error: invalid setting");
    /// ```
    pub fn config<S: Into<String>>(message: S) -> Self {
        SubXError::Config {
            message: message.into(),
        }
    }

    /// Create a subtitle format error for the given format and message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::subtitle_format("SRT", "invalid timestamp");
    /// assert!(err.to_string().contains("SRT"));
    /// ```
    pub fn subtitle_format<S1, S2>(format: S1, message: S2) -> Self
    where
        S1: Into<String>,
        S2: Into<String>,
    {
        SubXError::SubtitleFormat {
            format: format.into(),
            message: message.into(),
        }
    }

    /// Create an audio processing error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::audio_processing("decode failed");
    /// assert_eq!(err.to_string(), "Audio processing error: decode failed");
    /// ```
    pub fn audio_processing<S: Into<String>>(message: S) -> Self {
        SubXError::AudioProcessing {
            message: message.into(),
        }
    }

    /// Create an AI service error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::ai_service("network failure");
    /// assert_eq!(err.to_string(), "AI service error: network failure");
    /// ```
    pub fn ai_service<S: Into<String>>(message: S) -> Self {
        SubXError::AiService(message.into())
    }

    /// Create a file matching error with the given message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let err = SubXError::file_matching("not found");
    /// assert_eq!(err.to_string(), "File matching error: not found");
    /// ```
    pub fn file_matching<S: Into<String>>(message: S) -> Self {
        SubXError::FileMatching {
            message: message.into(),
        }
    }
    /// Create a parallel processing error with the given message.
    pub fn parallel_processing(msg: String) -> Self {
        SubXError::CommandExecution(format!("Parallel processing error: {}", msg))
    }
    /// Create a task execution failure error with task ID and reason.
    pub fn task_execution_failed(task_id: String, reason: String) -> Self {
        SubXError::CommandExecution(format!("Task {} execution failed: {}", task_id, reason))
    }
    /// Create a worker pool exhausted error.
    pub fn worker_pool_exhausted() -> Self {
        SubXError::CommandExecution("Worker pool exhausted".to_string())
    }
    /// Create a task timeout error with task ID and duration.
    pub fn task_timeout(task_id: String, duration: std::time::Duration) -> Self {
        SubXError::CommandExecution(format!(
            "Task {} timed out (limit: {:?})",
            task_id, duration
        ))
    }
    /// Create a dialogue detection failure error with the given message.
    pub fn dialogue_detection_failed<S: Into<String>>(msg: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Dialogue detection failed: {}", msg.into()),
        }
    }
    /// Create an invalid audio format error for the given format.
    pub fn invalid_audio_format<S: Into<String>>(format: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Unsupported audio format: {}", format.into()),
        }
    }
    /// Create an invalid dialogue segment error with the given reason.
    pub fn dialogue_segment_invalid<S: Into<String>>(reason: S) -> Self {
        SubXError::AudioProcessing {
            message: format!("Invalid dialogue segment: {}", reason.into()),
        }
    }
    /// Return the corresponding exit code for this error variant.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// assert_eq!(SubXError::config("x").exit_code(), 2);
    /// ```
    pub fn exit_code(&self) -> i32 {
        match self {
            SubXError::Io(_) => 1,
            SubXError::Config { .. } => 2,
            SubXError::Api { .. } => 3,
            SubXError::AiService(_) => 3,
            SubXError::SubtitleFormat { .. } => 4,
            SubXError::AudioProcessing { .. } => 5,
            SubXError::FileMatching { .. } => 6,
            _ => 1,
        }
    }

    /// Return a user-friendly error message with suggested remedies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// let msg = SubXError::config("missing key").user_friendly_message();
    /// assert!(msg.contains("Configuration error:"));
    /// ```
    pub fn user_friendly_message(&self) -> String {
        match self {
            SubXError::Io(e) => format!("File operation error: {}", e),
            SubXError::Config { message } => format!(
                "Configuration error: {}\nHint: run 'subx-cli config --help' for details",
                message
            ),
            SubXError::Api { message, source } => format!(
                "API error ({:?}): {}\nHint: check network connection and API key settings",
                source, message
            ),
            SubXError::AiService(msg) => format!(
                "AI service error: {}\nHint: check network connection and API key settings",
                msg
            ),
            SubXError::SubtitleFormat { message, .. } => format!(
                "Subtitle processing error: {}\nHint: check file format and encoding",
                message
            ),
            SubXError::AudioProcessing { message } => format!(
                "Audio processing error: {}\nHint: ensure media file integrity and support",
                message
            ),
            SubXError::FileMatching { message } => format!(
                "File matching error: {}\nHint: verify file paths and patterns",
                message
            ),
            SubXError::FileAlreadyExists(path) => format!("File already exists: {}", path),
            SubXError::FileNotFound(path) => format!("File not found: {}", path),
            SubXError::InvalidFileName(name) => format!("Invalid file name: {}", name),
            SubXError::FileOperationFailed(msg) => format!("File operation failed: {}", msg),
            SubXError::CommandExecution(msg) => msg.clone(),
            SubXError::Other(err) => {
                format!("Unknown error: {}\nHint: please report this issue", err)
            }
            _ => format!("Error: {}", self),
        }
    }
}

/// Helper functions for Whisper API and audio processing related errors.
impl SubXError {
    /// Create a Whisper API error.
    ///
    /// # Arguments
    ///
    /// * `message` - The error message describing the Whisper API failure
    ///
    /// # Returns
    ///
    /// A new `SubXError::Api` variant with Whisper as the source
    pub fn whisper_api<T: Into<String>>(message: T) -> Self {
        Self::Api {
            message: message.into(),
            source: ApiErrorSource::Whisper,
        }
    }

    /// Create an audio extraction/transcoding error.
    ///
    /// # Arguments
    ///
    /// * `message` - The error message describing the audio processing failure
    ///
    /// # Returns
    ///
    /// A new `SubXError::AudioProcessing` variant
    pub fn audio_extraction<T: Into<String>>(message: T) -> Self {
        Self::AudioProcessing {
            message: message.into(),
        }
    }
}

/// API error source enumeration.
///
/// Specifies the source of API-related errors to help with error diagnosis
/// and handling.
#[derive(Debug, thiserror::Error)]
pub enum ApiErrorSource {
    /// OpenAI Whisper API
    #[error("OpenAI")]
    OpenAI,
    /// Whisper API
    #[error("Whisper")]
    Whisper,
}

// Support conversion from Box<dyn Error> to SubXError::AudioProcessing
impl From<Box<dyn std::error::Error>> for SubXError {
    fn from(err: Box<dyn std::error::Error>) -> Self {
        SubXError::audio_processing(err.to_string())
    }
}