mockforge-cli 0.3.104

CLI interface for MockForge
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
//! Recorder commands for stub mapping conversion

use clap::Subcommand;
use mockforge_recorder::{models::Protocol, RecorderDatabase, StubFormat, StubMappingConverter};
use std::path::PathBuf;
use tracing::info;

#[derive(Subcommand)]
pub enum RecorderCommands {
    /// Convert recorded requests to stub mappings (fixtures)
    ///
    /// Examples:
    ///   mockforge recorder convert --recording-id abc123 --output fixtures/user-api.yaml
    ///   mockforge recorder convert --input recordings.db --output fixtures/ --format yaml
    Convert {
        /// Recording ID to convert (single conversion)
        #[arg(long)]
        recording_id: Option<String>,

        /// Input database file path (for batch conversion)
        #[arg(short, long)]
        input: Option<PathBuf>,

        /// Output file or directory path
        #[arg(short, long)]
        output: PathBuf,

        /// Output format (yaml or json)
        #[arg(short, long, default_value = "yaml")]
        format: String,

        /// Detect and replace dynamic values (UUIDs, timestamps) with template variables
        #[arg(long, default_value = "true")]
        detect_dynamic_values: bool,

        /// Deduplicate similar recordings (batch mode only)
        #[arg(long)]
        deduplicate: bool,

        /// Filter by protocol (http, grpc, websocket, graphql)
        #[arg(long)]
        protocol: Option<String>,

        /// Filter by HTTP method
        #[arg(long)]
        method: Option<String>,

        /// Filter by path pattern
        #[arg(long)]
        path: Option<String>,

        /// Limit number of recordings to convert (batch mode)
        #[arg(short, long, default_value = "100")]
        limit: usize,
    },
}

pub async fn handle_recorder_command(command: RecorderCommands) -> anyhow::Result<()> {
    match command {
        RecorderCommands::Convert {
            recording_id,
            input,
            output,
            format,
            detect_dynamic_values,
            deduplicate,
            protocol,
            method,
            path,
            limit,
        } => {
            handle_convert(
                recording_id,
                input,
                output,
                format,
                detect_dynamic_values,
                deduplicate,
                protocol,
                method,
                path,
                limit,
            )
            .await
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn handle_convert(
    recording_id: Option<String>,
    input: Option<PathBuf>,
    output: PathBuf,
    format: String,
    detect_dynamic_values: bool,
    deduplicate: bool,
    protocol: Option<String>,
    method: Option<String>,
    path: Option<String>,
    limit: usize,
) -> anyhow::Result<()> {
    let stub_format = match format.to_lowercase().as_str() {
        "json" => StubFormat::Json,
        _ => StubFormat::Yaml,
    };

    let converter = StubMappingConverter::new(detect_dynamic_values);

    if let Some(id) = recording_id {
        // Single recording conversion
        println!("🔄 Converting recording {} to stub mapping...", id);

        // Default database path if not provided
        let db_path = input.unwrap_or_else(|| PathBuf::from("./mockforge-recordings.db"));
        let db = RecorderDatabase::new(&db_path).await?;

        let exchange = db
            .get_exchange(&id)
            .await?
            .ok_or_else(|| anyhow::anyhow!("Recording {} not found", id))?;

        let stub = converter.convert(&exchange)?;
        let content = converter.to_string(&stub, stub_format)?;

        // Write to file
        tokio::fs::write(&output, content).await?;
        println!("✅ Stub mapping written to: {}", output.display());
    } else {
        // Batch conversion
        let db_path = input
            .ok_or_else(|| anyhow::anyhow!("Either --recording-id or --input must be specified"))?;

        println!("🔄 Converting recordings from database: {}", db_path.display());
        println!("📁 Output directory: {}", output.display());

        let db = RecorderDatabase::new(&db_path).await?;

        // Query recordings with filters
        use mockforge_recorder::{query::execute_query, QueryFilter};
        let mut filter = QueryFilter {
            limit: Some(limit as i32),
            ..Default::default()
        };

        if let Some(ref proto) = protocol {
            // Parse protocol string to Protocol enum
            let protocol_enum = match proto.to_lowercase().as_str() {
                "http" => Protocol::Http,
                "grpc" => Protocol::Grpc,
                "websocket" => Protocol::WebSocket,
                "graphql" => Protocol::GraphQL,
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid protocol: {}. Must be one of: http, grpc, websocket, graphql",
                        proto
                    ));
                }
            };
            filter.protocol = Some(protocol_enum);
        }
        if let Some(ref m) = method {
            filter.method = Some(m.clone());
        }
        if let Some(ref p) = path {
            filter.path = Some(p.clone());
        }
        let query_result = execute_query(&db, filter).await?;

        println!("📊 Found {} recordings to convert", query_result.total);

        // Create output directory if it doesn't exist
        if output.is_dir() || !output.exists() {
            tokio::fs::create_dir_all(&output).await?;
        }

        let mut converted = 0;
        let mut errors = 0;
        let mut seen_identifiers = std::collections::HashSet::new();

        for exchange in query_result.exchanges {
            let exchange_id = exchange.request.id.clone();

            match converter.convert(&exchange) {
                Ok(stub) => {
                    // Check deduplication
                    if deduplicate && seen_identifiers.contains(&stub.identifier) {
                        continue;
                    }
                    seen_identifiers.insert(stub.identifier.clone());

                    let content = converter.to_string(&stub, stub_format)?;

                    // Generate filename from identifier
                    let extension = match stub_format {
                        StubFormat::Yaml => "yaml",
                        StubFormat::Json => "json",
                    };
                    let filename = format!("{}.{}", stub.identifier, extension);
                    let file_path = if output.is_dir() {
                        output.join(&filename)
                    } else {
                        output.clone()
                    };

                    tokio::fs::write(&file_path, content).await?;
                    converted += 1;

                    if converted % 10 == 0 {
                        info!("Converted {} recordings...", converted);
                    }
                }
                Err(e) => {
                    eprintln!("⚠️  Failed to convert {}: {}", exchange_id, e);
                    errors += 1;
                }
            }
        }

        println!("\n✅ Conversion complete!");
        println!("   Converted: {}", converted);
        println!("   Errors: {}", errors);
        println!("   Output: {}", output.display());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_recorder_commands_convert_variant() {
        let cmd = RecorderCommands::Convert {
            recording_id: Some("abc123".to_string()),
            input: Some(PathBuf::from("input.db")),
            output: PathBuf::from("output/fixtures"),
            format: "yaml".to_string(),
            detect_dynamic_values: true,
            deduplicate: false,
            protocol: Some("http".to_string()),
            method: Some("GET".to_string()),
            path: Some("/api/users".to_string()),
            limit: 100,
        };

        // Verify the command can be constructed
        match cmd {
            RecorderCommands::Convert {
                recording_id,
                input,
                output,
                format,
                detect_dynamic_values,
                deduplicate,
                protocol,
                method,
                path,
                limit,
            } => {
                assert_eq!(recording_id, Some("abc123".to_string()));
                assert_eq!(input, Some(PathBuf::from("input.db")));
                assert_eq!(output, PathBuf::from("output/fixtures"));
                assert_eq!(format, "yaml");
                assert!(detect_dynamic_values);
                assert!(!deduplicate);
                assert_eq!(protocol, Some("http".to_string()));
                assert_eq!(method, Some("GET".to_string()));
                assert_eq!(path, Some("/api/users".to_string()));
                assert_eq!(limit, 100);
            }
        }
    }

    #[test]
    fn test_recorder_commands_convert_minimal() {
        let cmd = RecorderCommands::Convert {
            recording_id: None,
            input: None,
            output: PathBuf::from("output"),
            format: "json".to_string(),
            detect_dynamic_values: false,
            deduplicate: true,
            protocol: None,
            method: None,
            path: None,
            limit: 50,
        };

        match cmd {
            RecorderCommands::Convert {
                recording_id,
                input,
                format,
                detect_dynamic_values,
                deduplicate,
                protocol,
                method,
                path,
                limit,
                ..
            } => {
                assert!(recording_id.is_none());
                assert!(input.is_none());
                assert_eq!(format, "json");
                assert!(!detect_dynamic_values);
                assert!(deduplicate);
                assert!(protocol.is_none());
                assert!(method.is_none());
                assert!(path.is_none());
                assert_eq!(limit, 50);
            }
        }
    }

    #[test]
    fn test_format_parsing() {
        // Test format string conversion (mimics the logic in handle_convert)
        let formats = vec![
            ("json", "json"),
            ("JSON", "json"),
            ("Json", "json"),
            ("yaml", "yaml"),
            ("YAML", "yaml"),
            ("Yaml", "yaml"),
            ("other", "yaml"), // defaults to yaml
        ];

        for (input, expected) in formats {
            let result = match input.to_lowercase().as_str() {
                "json" => "json",
                _ => "yaml",
            };
            assert_eq!(result, expected, "Format '{}' should map to '{}'", input, expected);
        }
    }

    #[test]
    fn test_protocol_parsing() {
        // Test protocol string conversion (mimics the logic in handle_convert)
        let valid_protocols = vec![
            ("http", Protocol::Http),
            ("HTTP", Protocol::Http),
            ("grpc", Protocol::Grpc),
            ("GRPC", Protocol::Grpc),
            ("websocket", Protocol::WebSocket),
            ("WebSocket", Protocol::WebSocket),
            ("graphql", Protocol::GraphQL),
            ("GraphQL", Protocol::GraphQL),
        ];

        for (input, expected) in valid_protocols {
            let result = match input.to_lowercase().as_str() {
                "http" => Some(Protocol::Http),
                "grpc" => Some(Protocol::Grpc),
                "websocket" => Some(Protocol::WebSocket),
                "graphql" => Some(Protocol::GraphQL),
                _ => None,
            };
            assert_eq!(result, Some(expected), "Protocol '{}' should parse correctly", input);
        }
    }

    #[test]
    fn test_invalid_protocol_parsing() {
        let invalid_protocols = vec!["invalid", "tcp", "udp", "mqtt", "amqp"];

        for proto in invalid_protocols {
            let result = match proto.to_lowercase().as_str() {
                "http" => Some(Protocol::Http),
                "grpc" => Some(Protocol::Grpc),
                "websocket" => Some(Protocol::WebSocket),
                "graphql" => Some(Protocol::GraphQL),
                _ => None,
            };
            assert!(result.is_none(), "Protocol '{}' should be invalid", proto);
        }
    }

    #[test]
    fn test_output_path_handling() {
        // Test various output path scenarios
        let paths = vec![
            PathBuf::from("fixtures/"),
            PathBuf::from("./output"),
            PathBuf::from("/absolute/path"),
            PathBuf::from("relative/path/file.yaml"),
        ];

        for path in paths {
            // Just verify paths can be created
            let cmd = RecorderCommands::Convert {
                recording_id: None,
                input: None,
                output: path.clone(),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: None,
                path: None,
                limit: 100,
            };

            match cmd {
                RecorderCommands::Convert { output, .. } => {
                    assert_eq!(output, path);
                }
            }
        }
    }

    #[test]
    fn test_http_methods() {
        let methods = vec!["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"];

        for method in methods {
            let cmd = RecorderCommands::Convert {
                recording_id: None,
                input: None,
                output: PathBuf::from("output"),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: Some(method.to_string()),
                path: None,
                limit: 100,
            };

            match cmd {
                RecorderCommands::Convert { method: m, .. } => {
                    assert_eq!(m, Some(method.to_string()));
                }
            }
        }
    }

    #[test]
    fn test_path_filter_patterns() {
        let path_patterns = vec![
            "/api/users",
            "/api/users/*",
            "/api/v1/items/**",
            "/health",
            "/api/search?q=*",
        ];

        for pattern in path_patterns {
            let cmd = RecorderCommands::Convert {
                recording_id: None,
                input: None,
                output: PathBuf::from("output"),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: None,
                path: Some(pattern.to_string()),
                limit: 100,
            };

            match cmd {
                RecorderCommands::Convert { path, .. } => {
                    assert_eq!(path, Some(pattern.to_string()));
                }
            }
        }
    }

    #[test]
    fn test_limit_values() {
        let limits = vec![1, 10, 100, 1000, 10000];

        for limit_val in limits {
            let cmd = RecorderCommands::Convert {
                recording_id: None,
                input: None,
                output: PathBuf::from("output"),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: None,
                path: None,
                limit: limit_val,
            };

            match cmd {
                RecorderCommands::Convert { limit, .. } => {
                    assert_eq!(limit, limit_val);
                }
            }
        }
    }

    #[test]
    fn test_recording_id_formats() {
        // Test various recording ID formats
        let ids = vec![
            "abc123".to_string(),
            "uuid-like-id-12345".to_string(),
            "123456".to_string(),
            "rec_001".to_string(),
            "a".repeat(100), // long ID
        ];

        for id in ids {
            let cmd = RecorderCommands::Convert {
                recording_id: Some(id.clone()),
                input: None,
                output: PathBuf::from("output.yaml"),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: None,
                path: None,
                limit: 100,
            };

            match cmd {
                RecorderCommands::Convert { recording_id, .. } => {
                    assert_eq!(recording_id, Some(id));
                }
            }
        }
    }

    #[test]
    fn test_input_database_paths() {
        let db_paths = vec![
            PathBuf::from("recordings.db"),
            PathBuf::from("./data/mockforge-recordings.db"),
            PathBuf::from("/var/lib/mockforge/recordings.db"),
        ];

        for db_path in db_paths {
            let cmd = RecorderCommands::Convert {
                recording_id: None,
                input: Some(db_path.clone()),
                output: PathBuf::from("output"),
                format: "yaml".to_string(),
                detect_dynamic_values: true,
                deduplicate: false,
                protocol: None,
                method: None,
                path: None,
                limit: 100,
            };

            match cmd {
                RecorderCommands::Convert { input, .. } => {
                    assert_eq!(input, Some(db_path));
                }
            }
        }
    }
}