subx-cli 1.7.4

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
use crate::{Result, cli::Commands, cli::OutputMode, config::ConfigService};
use std::sync::Arc;

/// Central command dispatcher to avoid code duplication.
///
/// This module provides a unified way to dispatch commands,
/// eliminating duplication between CLI and library API paths.
///
/// # Design Principles
///
/// - **Single Responsibility**: Each command dispatcher handles exactly one command type
/// - **Consistency**: Both CLI and App API use the same command execution logic
/// - **Error Handling**: Unified error handling across all command paths
/// - **Testability**: Easy to test individual command dispatch without full CLI setup
///
/// # Architecture
///
/// The dispatcher acts as a bridge between:
/// - CLI argument parsing (from `clap`)
/// - Command execution logic (in `commands` module)
/// - Configuration dependency injection
///
/// This eliminates the previous duplication where both `cli::run_with_config()`
/// and `App::handle_command()` had identical match statements.
///
/// # Examples
///
/// ```rust
/// use subx_cli::commands::dispatcher::dispatch_command;
/// use subx_cli::cli::{Commands, MatchArgs};
/// use subx_cli::config::TestConfigService;
/// use std::sync::Arc;
///
/// # async fn example() -> subx_cli::Result<()> {
/// let config_service = Arc::new(TestConfigService::with_defaults());
/// let match_args = MatchArgs {
///     path: Some("/path/to/files".into()),
///     input_paths: vec![],
///     dry_run: true,
///     confidence: 80,
///     recursive: false,
///     backup: false,
///     copy: false,
///     move_files: false,
///     no_extract: false,
/// };
///
/// dispatch_command(Commands::Match(match_args), config_service).await?;
/// # Ok(())
/// # }
/// ```
pub async fn dispatch_command(
    command: Commands,
    config_service: Arc<dyn ConfigService>,
) -> Result<()> {
    dispatch_command_with_mode(command, config_service, OutputMode::Text).await
}

/// Dispatch a command using an owned `Arc<dyn ConfigService>` and an
/// explicit [`OutputMode`].
///
/// This is the entry point used by the CLI runtime. The `output_mode`
/// parameter is currently used to thread the renderer through to each
/// per-command handler (a follow-up task wires it into the per-command
/// payload emission). Today, the dispatcher itself does not branch on
/// the mode — the global mode installed via
/// [`crate::cli::output::install_active_mode`] already governs UI
/// helpers — but the parameter is plumbed for forward compatibility so
/// per-command sub-agents have a stable contract to consume.
pub async fn dispatch_command_with_mode(
    command: Commands,
    config_service: Arc<dyn ConfigService>,
    output_mode: OutputMode,
) -> Result<()> {
    match command {
        Commands::Match(args) => {
            crate::commands::match_command::execute_with_config(args, config_service).await
        }
        Commands::Convert(args) => {
            crate::commands::convert_command::execute_with_config(args, config_service).await
        }
        Commands::Sync(args) => {
            crate::commands::sync_command::execute_with_config(args, config_service).await
        }
        Commands::Config(args) => {
            crate::commands::config_command::execute_with_config(args, config_service).await
        }
        Commands::GenerateCompletion(args) => run_generate_completion(args, output_mode),
        Commands::Cache(args) => {
            crate::commands::cache_command::execute_with_config(args, config_service).await
        }
        Commands::Translate(args) => {
            crate::commands::translate_command::execute_with_config(args, config_service).await
        }
        Commands::DetectEncoding(args) => {
            crate::commands::detect_encoding_command::detect_encoding_command_with_config(
                args,
                config_service.as_ref(),
            )?;
            Ok(())
        }
    }
}

/// Dispatch command with borrowed config service reference.
///
/// This version is used by the CLI interface where we have a borrowed reference
/// to the configuration service rather than an owned Arc. The
/// `output_mode` parameter is plumbed for per-command renderer
/// integration (see [`dispatch_command_with_mode`]).
pub async fn dispatch_command_with_ref(
    command: Commands,
    config_service: &dyn ConfigService,
    output_mode: OutputMode,
) -> Result<()> {
    match command {
        Commands::Match(args) => {
            args.validate()
                .map_err(crate::error::SubXError::CommandExecution)?;
            crate::commands::match_command::execute(args, config_service).await
        }
        Commands::Convert(args) => {
            crate::commands::convert_command::execute(args, config_service).await
        }
        Commands::Sync(args) => crate::commands::sync_command::execute(args, config_service).await,
        Commands::Config(args) => {
            crate::commands::config_command::execute(args, config_service).await
        }
        Commands::GenerateCompletion(args) => run_generate_completion(args, output_mode),
        Commands::Cache(args) => crate::commands::cache_command::execute(args).await,
        Commands::Translate(args) => {
            crate::commands::translate_command::execute(args, config_service).await
        }
        Commands::DetectEncoding(args) => {
            crate::commands::detect_encoding_command::detect_encoding_command_with_config(
                args,
                config_service,
            )?;
            Ok(())
        }
    }
}

/// Execute the `generate-completion` subcommand, rejecting JSON output
/// mode because the produced shell-completion script cannot be wrapped
/// in the JSON envelope contract.
///
/// In [`OutputMode::Text`] this prints the script to stdout and returns
/// `Ok(())`. In [`OutputMode::Json`] it returns
/// [`crate::error::SubXError::OutputModeUnsupported`] so `main.rs` can
/// emit the standard error envelope and exit with code 1.
fn run_generate_completion(
    args: crate::cli::GenerateCompletionArgs,
    output_mode: OutputMode,
) -> Result<()> {
    if output_mode.is_json() {
        return Err(crate::error::SubXError::OutputModeUnsupported {
            command: "generate-completion".to_string(),
        });
    }
    let mut cmd = <crate::cli::Cli as clap::CommandFactory>::command();
    let cmd_name = cmd.get_name().to_string();
    let mut stdout = std::io::stdout();
    clap_complete::generate(args.shell, &mut cmd, cmd_name, &mut stdout);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{
        CacheAction, CacheArgs, ClearArgs, ClearType, ConfigAction, ConfigArgs, ConvertArgs,
        DetectEncodingArgs, GenerateCompletionArgs, MatchArgs, OutputSubtitleFormat, StatusArgs,
        SyncArgs,
    };
    use crate::config::TestConfigService;
    use clap_complete::Shell;

    // Helper to check that errors are expected filesystem/config errors in a test environment
    fn is_expected_test_error(e: &crate::error::SubXError) -> bool {
        let msg = format!("{e:?}");
        msg.contains("NotFound")
            || msg.contains("No subtitle files found")
            || msg.contains("No video files found")
            || msg.contains("Config")
            || msg.contains("no such file")
            || msg.contains("cannot find")
            || msg.contains("No input")
            || msg.contains("No files")
            || msg.contains("FileNotFound")
            || msg.contains("IoError")
            || msg.contains("PathNotFound")
            || msg.contains("InvalidInput")
            || msg.contains("CommandExecution")
            || msg.contains("NoInputSpecified")
    }

    fn make_match_args_dry_run() -> MatchArgs {
        MatchArgs {
            path: Some("/nonexistent_subx_test_path".into()),
            input_paths: vec![],
            dry_run: true,
            confidence: 80,
            recursive: false,
            backup: false,
            copy: false,
            move_files: false,
            no_extract: false,
        }
    }

    fn make_convert_args() -> ConvertArgs {
        ConvertArgs {
            input: Some("/nonexistent_subx_test_path".into()),
            input_paths: vec![],
            recursive: false,
            format: Some(OutputSubtitleFormat::Srt),
            output: None,
            keep_original: false,
            encoding: "utf-8".to_string(),
            no_extract: false,
        }
    }

    fn make_sync_args() -> SyncArgs {
        SyncArgs {
            positional_paths: vec![],
            video: None,
            subtitle: None,
            input_paths: vec![],
            recursive: false,
            offset: Some(1.0),
            method: None,
            window: 30,
            vad_sensitivity: None,
            output: None,
            verbose: false,
            dry_run: true,
            force: false,
            batch: None,
            no_extract: false,
        }
    }

    fn make_config_args_list() -> ConfigArgs {
        ConfigArgs {
            action: ConfigAction::List,
        }
    }

    fn make_generate_completion_args() -> GenerateCompletionArgs {
        GenerateCompletionArgs { shell: Shell::Bash }
    }

    fn make_cache_status_args() -> CacheArgs {
        CacheArgs {
            action: CacheAction::Status(StatusArgs { json: false }),
        }
    }

    fn make_cache_clear_args() -> CacheArgs {
        CacheArgs {
            action: CacheAction::Clear(ClearArgs {
                r#type: ClearType::All,
            }),
        }
    }

    fn make_detect_encoding_args() -> DetectEncodingArgs {
        DetectEncodingArgs {
            verbose: false,
            input_paths: vec![],
            recursive: false,
            file_paths: vec![],
            no_extract: false,
        }
    }

    // ── dispatch_command (Arc<dyn ConfigService>) ─────────────────────────────

    #[tokio::test]
    async fn test_dispatch_match_command() {
        let config_service = Arc::new(TestConfigService::with_ai_settings(
            "test_provider",
            "test_model",
        ));
        let result =
            dispatch_command(Commands::Match(make_match_args_dry_run()), config_service).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_convert_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        // The result may fail due to missing files; we only verify no panic occurs.
        let _result =
            dispatch_command(Commands::Convert(make_convert_args()), config_service).await;
    }

    #[tokio::test]
    async fn test_dispatch_sync_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let result = dispatch_command(Commands::Sync(make_sync_args()), config_service).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_config_list_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let result =
            dispatch_command(Commands::Config(make_config_args_list()), config_service).await;
        // Config list should either succeed or produce an expected config error
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_generate_completion_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        // GenerateCompletion writes to stdout and returns Ok
        let result = dispatch_command(
            Commands::GenerateCompletion(make_generate_completion_args()),
            config_service,
        )
        .await;
        assert!(
            result.is_ok(),
            "GenerateCompletion should succeed: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_dispatch_cache_status_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let _result =
            dispatch_command(Commands::Cache(make_cache_status_args()), config_service).await;
    }

    #[tokio::test]
    async fn test_dispatch_cache_clear_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let _result =
            dispatch_command(Commands::Cache(make_cache_clear_args()), config_service).await;
    }

    #[tokio::test]
    async fn test_dispatch_detect_encoding_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let result = dispatch_command(
            Commands::DetectEncoding(make_detect_encoding_args()),
            config_service,
        )
        .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    // ── dispatch_command_with_ref (&dyn ConfigService) ────────────────────────

    #[tokio::test]
    async fn test_dispatch_with_ref_match_command() {
        let config_service = TestConfigService::with_ai_settings("test_provider", "test_model");
        let result = dispatch_command_with_ref(
            Commands::Match(make_match_args_dry_run()),
            &config_service,
            OutputMode::Text,
        )
        .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_match_validation_error() {
        // copy + move together must fail with a CommandExecution validation error
        let config_service = TestConfigService::with_defaults();
        let args = MatchArgs {
            path: Some("/nonexistent_subx_test_path".into()),
            input_paths: vec![],
            dry_run: true,
            confidence: 80,
            recursive: false,
            backup: false,
            copy: true,
            move_files: true,
            no_extract: false,
        };
        let result =
            dispatch_command_with_ref(Commands::Match(args), &config_service, OutputMode::Text)
                .await;
        assert!(result.is_err(), "Expected validation error for copy+move");
        let msg = format!("{:?}", result.unwrap_err());
        assert!(
            msg.contains("CommandExecution") || msg.contains("copy") || msg.contains("move"),
            "Error should mention the conflicting flags: {msg}"
        );
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_convert_command() {
        let config_service = TestConfigService::with_defaults();
        let _result = dispatch_command_with_ref(
            Commands::Convert(make_convert_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_sync_command() {
        let config_service = TestConfigService::with_defaults();
        let result = dispatch_command_with_ref(
            Commands::Sync(make_sync_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_config_list_command() {
        let config_service = TestConfigService::with_defaults();
        let result = dispatch_command_with_ref(
            Commands::Config(make_config_args_list()),
            &config_service,
            OutputMode::Text,
        )
        .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_generate_completion_command() {
        let config_service = TestConfigService::with_defaults();
        let result = dispatch_command_with_ref(
            Commands::GenerateCompletion(make_generate_completion_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
        assert!(
            result.is_ok(),
            "GenerateCompletion should succeed: {result:?}"
        );
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_cache_status_command() {
        let config_service = TestConfigService::with_defaults();
        let _result = dispatch_command_with_ref(
            Commands::Cache(make_cache_status_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_cache_clear_command() {
        let config_service = TestConfigService::with_defaults();
        let _result = dispatch_command_with_ref(
            Commands::Cache(make_cache_clear_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
    }

    #[tokio::test]
    async fn test_dispatch_with_ref_detect_encoding_command() {
        let config_service = TestConfigService::with_defaults();
        let result = dispatch_command_with_ref(
            Commands::DetectEncoding(make_detect_encoding_args()),
            &config_service,
            OutputMode::Text,
        )
        .await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    // ── Configuration is forwarded to subcommands ─────────────────────────────

    #[tokio::test]
    async fn test_dispatch_config_get_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let args = ConfigArgs {
            action: ConfigAction::Get {
                key: "ai.provider".to_string(),
            },
        };
        let result = dispatch_command(Commands::Config(args), config_service).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_config_set_command() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let args = ConfigArgs {
            action: ConfigAction::Set {
                key: "ai.provider".to_string(),
                value: "openai".to_string(),
            },
        };
        let result = dispatch_command(Commands::Config(args), config_service).await;
        match result {
            Ok(_) => {}
            Err(e) => assert!(is_expected_test_error(&e), "Unexpected error: {e:?}"),
        }
    }

    #[tokio::test]
    async fn test_dispatch_generate_completion_zsh() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let result = dispatch_command(
            Commands::GenerateCompletion(GenerateCompletionArgs { shell: Shell::Zsh }),
            config_service,
        )
        .await;
        assert!(result.is_ok(), "Zsh completion should succeed: {result:?}");
    }

    #[tokio::test]
    async fn test_dispatch_generate_completion_fish() {
        let config_service = Arc::new(TestConfigService::with_defaults());
        let result = dispatch_command(
            Commands::GenerateCompletion(GenerateCompletionArgs { shell: Shell::Fish }),
            config_service,
        )
        .await;
        assert!(result.is_ok(), "Fish completion should succeed: {result:?}");
    }
}