mockforge-cli 0.3.118

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
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
//! Schema-driven mock generation commands
//!
//! This module provides CLI commands for importing API specifications
//! (OpenAPI/AsyncAPI/Insomnia) and automatically generating comprehensive mock endpoints.

use crate::insomnia_import::import_insomnia_export;
use clap::Subcommand;
use colored::Colorize;
use mockforge_import::import::asyncapi_import::{import_asyncapi_spec, AsyncApiImportResult};
use mockforge_import::import::openapi_import::{import_openapi_spec, OpenApiImportResult};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Subcommand)]
pub enum ImportCommands {
    /// Import OpenAPI 3.x specification and generate mock endpoints
    ///
    /// Examples:
    ///   mockforge import openapi ./specs/api.yaml
    ///   mockforge import openapi ./specs/api.json --output mocks.json
    ///   mockforge import openapi https://api.example.com/openapi.json
    #[command(verbatim_doc_comment)]
    Openapi {
        /// Path or URL to OpenAPI specification file (JSON or YAML)
        spec_path: String,

        /// Base URL for the API (overrides servers in spec)
        #[arg(short, long)]
        base_url: Option<String>,

        /// Output file for generated mocks (JSON format)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Show detailed coverage report
        #[arg(short = 'V', long)]
        verbose: bool,

        /// Generate mocks for all status codes (not just 2xx)
        #[arg(long)]
        all_responses: bool,
    },

    /// Import AsyncAPI 2.x/3.x specification and generate event-driven mocks
    ///
    /// Examples:
    ///   mockforge import asyncapi ./specs/events.yaml
    ///   mockforge import asyncapi ./specs/mqtt.json --protocol mqtt
    #[command(verbatim_doc_comment)]
    Asyncapi {
        /// Path or URL to AsyncAPI specification file (JSON or YAML)
        spec_path: String,

        /// Base URL for the server (overrides servers in spec)
        #[arg(short, long)]
        base_url: Option<String>,

        /// Output file for generated channel configurations (JSON format)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Filter channels by protocol (websocket, mqtt, kafka, amqp)
        #[arg(short, long)]
        protocol: Option<String>,

        /// Show detailed coverage report
        #[arg(short = 'V', long)]
        verbose: bool,
    },

    /// Import Insomnia export and generate mock endpoints
    ///
    /// Examples:
    ///   mockforge import insomnia ./insomnia-export.json
    ///   mockforge import insomnia ./insomnia-export.json --output mocks.json
    ///   mockforge import insomnia ./insomnia-export.json --environment "Production"
    #[command(verbatim_doc_comment)]
    Insomnia {
        /// Path to Insomnia export file (JSON)
        export_path: PathBuf,

        /// Output file for generated mocks (JSON format)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Environment name to use for variable resolution
        #[arg(short, long)]
        environment: Option<String>,

        /// Show detailed import information
        #[arg(short = 'V', long)]
        verbose: bool,
    },

    /// Show coverage statistics for imported specifications
    ///
    /// Examples:
    ///   mockforge import coverage ./specs/api.yaml
    #[command(verbatim_doc_comment)]
    Coverage {
        /// Path to specification file
        spec_path: String,

        /// Specification type (openapi, asyncapi, or auto-detect)
        #[arg(short = 't', long, default_value = "auto")]
        spec_type: String,
    },
}

/// Handle import commands
pub async fn handle_import_command(
    command: ImportCommands,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match command {
        ImportCommands::Openapi {
            spec_path,
            base_url,
            output,
            verbose,
            all_responses: _all_responses,
        } => {
            handle_openapi_import(&spec_path, base_url.as_deref(), output.as_deref(), verbose).await
        }
        ImportCommands::Asyncapi {
            spec_path,
            base_url,
            output,
            protocol,
            verbose,
        } => {
            handle_asyncapi_import(
                &spec_path,
                base_url.as_deref(),
                output.as_deref(),
                protocol.as_deref(),
                verbose,
            )
            .await
        }
        ImportCommands::Insomnia {
            export_path,
            output,
            environment,
            verbose,
        } => {
            handle_insomnia_import(&export_path, output.as_deref(), environment.as_deref(), verbose)
                .await
        }
        ImportCommands::Coverage {
            spec_path,
            spec_type,
        } => handle_coverage_report(&spec_path, &spec_type).await,
    }
}

/// Handle OpenAPI import
async fn handle_openapi_import(
    spec_path: &str,
    base_url: Option<&str>,
    output: Option<&Path>,
    verbose: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("{}", "📋 Importing OpenAPI Specification...".cyan().bold());
    println!();

    // Load specification content
    let content = load_spec_content(spec_path).await?;

    // Convert YAML to JSON if needed
    let json_content = if spec_path.ends_with(".yaml") || spec_path.ends_with(".yml") {
        let yaml_value: serde_json::Value =
            serde_yaml::from_str(&content).map_err(|e| format!("Failed to parse YAML: {}", e))?;
        serde_json::to_string(&yaml_value)?
    } else {
        content
    };

    // Import the spec
    let result = import_openapi_spec(&json_content, base_url)
        .map_err(|e| format!("Failed to import OpenAPI spec: {}", e))?;

    // Display results
    display_openapi_import_results(&result, verbose);

    // Save to output file if specified
    if let Some(output_path) = output {
        save_openapi_routes(&result, output_path)?;
        println!();
        println!(
            "{}",
            format!("✅ Saved {} routes to {}", result.routes.len(), output_path.display())
                .green()
                .bold()
        );
    }

    Ok(())
}

/// Handle AsyncAPI import
async fn handle_asyncapi_import(
    spec_path: &str,
    base_url: Option<&str>,
    output: Option<&Path>,
    protocol_filter: Option<&str>,
    verbose: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("{}", "📋 Importing AsyncAPI Specification...".cyan().bold());
    println!();

    // Load specification content
    let content = load_spec_content(spec_path).await?;

    // Import the spec
    let mut result = import_asyncapi_spec(&content, base_url)
        .map_err(|e| format!("Failed to import AsyncAPI spec: {}", e))?;

    // Filter by protocol if specified
    if let Some(protocol) = protocol_filter {
        result.channels.retain(|ch| {
            format!("{:?}", ch.protocol).to_lowercase().contains(&protocol.to_lowercase())
        });
    }

    // Display results
    display_asyncapi_import_results(&result, verbose);

    // Save to output file if specified
    if let Some(output_path) = output {
        save_asyncapi_channels(&result.channels, output_path)?;
        println!();
        println!(
            "{}",
            format!("✅ Saved {} channels to {}", result.channels.len(), output_path.display())
                .green()
                .bold()
        );
    }

    Ok(())
}

/// Handle Insomnia export import
async fn handle_insomnia_import(
    export_path: &Path,
    output: Option<&Path>,
    environment: Option<&str>,
    verbose: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("{}", "📋 Importing Insomnia Export...".cyan().bold());
    println!();

    let content = fs::read_to_string(export_path)
        .map_err(|e| format!("Failed to read Insomnia export: {}", e))?;

    let result = import_insomnia_export(&content, environment)
        .map_err(|e| format!("Failed to import Insomnia export: {}", e))?;

    // Display results
    println!("{}", "📖 Import Results:".bold());
    println!("  Routes imported: {}", result.routes.len().to_string().green());
    println!("  Variables resolved: {}", result.variables.len().to_string().cyan());

    if !result.warnings.is_empty() {
        println!();
        println!("{}", "⚠️  Warnings:".yellow().bold());
        for warning in &result.warnings {
            println!("  - {}", warning.yellow());
        }
    }

    if verbose {
        println!();
        println!("{}", "📍 Imported Routes:".bold());
        for route in &result.routes {
            println!("  {} {}{}", route.method.cyan(), route.path, route.response.status);
        }

        if !result.variables.is_empty() {
            println!();
            println!("{}", "🔑 Resolved Variables:".bold());
            for (key, value) in &result.variables {
                println!("  {} = {}", key.cyan(), value);
            }
        }
    }

    // Save to output file if specified
    if let Some(output_path) = output {
        let routes_json = serde_json::to_string_pretty(&result.routes)
            .map_err(|e| format!("Failed to serialize routes: {}", e))?;
        fs::write(output_path, routes_json)
            .map_err(|e| format!("Failed to write output file: {}", e))?;
        println!();
        println!(
            "{}",
            format!("✅ Saved {} routes to {}", result.routes.len(), output_path.display())
                .green()
                .bold()
        );
    }

    Ok(())
}

/// Handle coverage report generation
async fn handle_coverage_report(
    spec_path: &str,
    spec_type: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("{}", "📊 Generating Coverage Report...".cyan().bold());
    println!();

    let content = load_spec_content(spec_path).await?;

    // Auto-detect spec type if needed
    let detected_type = if spec_type == "auto" {
        detect_spec_type(&content)?
    } else {
        spec_type.to_string()
    };

    // Convert YAML to JSON if needed
    let json_content = if spec_path.ends_with(".yaml") || spec_path.ends_with(".yml") {
        let yaml_value: serde_json::Value =
            serde_yaml::from_str(&content).map_err(|e| format!("Failed to parse YAML: {}", e))?;
        serde_json::to_string(&yaml_value)?
    } else {
        content.clone()
    };

    match detected_type.as_str() {
        "openapi" => {
            let result = import_openapi_spec(&json_content, None)
                .map_err(|e| format!("Failed to parse OpenAPI spec: {}", e))?;
            display_openapi_coverage(&result);
        }
        "asyncapi" => {
            let result = import_asyncapi_spec(&content, None)
                .map_err(|e| format!("Failed to parse AsyncAPI spec: {}", e))?;
            display_asyncapi_coverage(&result);
        }
        _ => {
            return Err(format!("Unknown specification type: {}", detected_type).into());
        }
    }

    Ok(())
}

/// Load specification content from file or URL
async fn load_spec_content(
    spec_path: &str,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    if spec_path.starts_with("http://") || spec_path.starts_with("https://") {
        // Fetch from URL
        println!("📥 Fetching specification from URL: {}", spec_path);
        let response = reqwest::get(spec_path).await?;
        let content = response.text().await?;
        Ok(content)
    } else {
        // Load from file
        println!("📂 Loading specification from file: {}", spec_path);
        let content = fs::read_to_string(spec_path)
            .map_err(|e| format!("Failed to read file {}: {}", spec_path, e))?;
        Ok(content)
    }
}

/// Detect specification type from content
fn detect_spec_type(content: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    // Try parsing as JSON
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(content) {
        if json.get("openapi").is_some() {
            return Ok("openapi".to_string());
        } else if json.get("asyncapi").is_some() {
            return Ok("asyncapi".to_string());
        }
    }

    // Try parsing as YAML
    if let Ok(yaml) = serde_yaml::from_str::<serde_json::Value>(content) {
        if yaml.get("openapi").is_some() {
            return Ok("openapi".to_string());
        } else if yaml.get("asyncapi").is_some() {
            return Ok("asyncapi".to_string());
        }
    }

    Err("Unable to detect specification type. File must be valid OpenAPI or AsyncAPI spec.".into())
}

/// Display OpenAPI import results
fn display_openapi_import_results(result: &OpenApiImportResult, verbose: bool) {
    println!("{}", "📖 Specification Info:".bold());
    println!("  Title: {}", result.spec_info.title.cyan());
    println!("  Version: {}", result.spec_info.version.cyan());
    if let Some(desc) = &result.spec_info.description {
        println!("  Description: {}", desc);
    }
    println!("  OpenAPI Version: {}", result.spec_info.openapi_version);

    if !result.spec_info.servers.is_empty() {
        println!("\n{}", "🌐 Servers:".bold());
        for server in &result.spec_info.servers {
            println!("{}", server.green());
        }
    }

    println!();
    println!("{}", "✨ Generated Routes:".bold());
    println!("  Total Routes: {}", result.routes.len().to_string().green().bold());

    // Count by method
    let mut method_counts = std::collections::HashMap::new();
    for route in &result.routes {
        *method_counts.entry(&route.method).or_insert(0) += 1;
    }

    println!("\n{}", "  By Method:".bold());
    for (method, count) in method_counts.iter() {
        let method_colored = match method.as_str() {
            "GET" => method.blue(),
            "POST" => method.green(),
            "PUT" => method.yellow(),
            "DELETE" => method.red(),
            "PATCH" => method.magenta(),
            _ => method.normal(),
        };
        println!("    {}: {}", method_colored.bold(), count);
    }

    // Display warnings if any
    if !result.warnings.is_empty() {
        println!();
        println!("{}", format!("⚠️  {} Warnings:", result.warnings.len()).yellow().bold());
        for warning in &result.warnings {
            println!("{}", warning.yellow());
        }
    }

    // Verbose output: list all routes
    if verbose {
        println!();
        println!("{}", "📋 Route Details:".bold());
        for (idx, route) in result.routes.iter().enumerate() {
            let method_colored = match route.method.as_str() {
                "GET" => route.method.as_str().blue(),
                "POST" => route.method.as_str().green(),
                "PUT" => route.method.as_str().yellow(),
                "DELETE" => route.method.as_str().red(),
                "PATCH" => route.method.as_str().magenta(),
                _ => route.method.as_str().normal(),
            };
            println!(
                "  {}: {} {}{} {}",
                (idx + 1).to_string().dimmed(),
                method_colored.bold(),
                route.path.cyan(),
                route.response.status.to_string().green(),
                if route.body.is_some() {
                    "(with request body)".dimmed().to_string()
                } else {
                    "".to_string()
                }
            );
        }
    }
}

/// Display AsyncAPI import results
fn display_asyncapi_import_results(result: &AsyncApiImportResult, verbose: bool) {
    println!("{}", "📖 Specification Info:".bold());
    println!("  Title: {}", result.spec_info.title.cyan());
    println!("  Version: {}", result.spec_info.version.cyan());
    if let Some(desc) = &result.spec_info.description {
        println!("  Description: {}", desc);
    }
    println!("  AsyncAPI Version: {}", result.spec_info.asyncapi_version);

    if !result.spec_info.servers.is_empty() {
        println!("\n{}", "🌐 Servers:".bold());
        for server in &result.spec_info.servers {
            println!("{}", server.green());
        }
    }

    println!();
    println!("{}", "✨ Generated Channels:".bold());
    println!("  Total Channels: {}", result.channels.len().to_string().green().bold());

    // Count by protocol
    let mut protocol_counts = std::collections::HashMap::new();
    for channel in &result.channels {
        *protocol_counts.entry(format!("{:?}", channel.protocol)).or_insert(0) += 1;
    }

    println!("\n{}", "  By Protocol:".bold());
    for (protocol, count) in protocol_counts.iter() {
        println!("    {}: {}", protocol.cyan().bold(), count);
    }

    // Display warnings if any
    if !result.warnings.is_empty() {
        println!();
        println!("{}", format!("⚠️  {} Warnings:", result.warnings.len()).yellow().bold());
        for warning in &result.warnings {
            println!("{}", warning.yellow());
        }
    }

    // Verbose output: list all channels
    if verbose {
        println!();
        println!("{}", "📋 Channel Details:".bold());
        for (idx, channel) in result.channels.iter().enumerate() {
            println!(
                "  {}: {} {} ({})",
                (idx + 1).to_string().dimmed(),
                format!("{:?}", channel.protocol).cyan().bold(),
                channel.path.green(),
                channel.name.dimmed()
            );
            if let Some(desc) = &channel.description {
                println!("     Description: {}", desc);
            }
            println!("     Operations: {}", channel.operations.len());
        }
    }
}

/// Display OpenAPI coverage statistics
fn display_openapi_coverage(result: &OpenApiImportResult) {
    println!("{}", "📊 Coverage Statistics:".bold());
    println!();

    let total_routes = result.routes.len();
    let routes_with_bodies = result.routes.iter().filter(|r| r.body.is_some()).count();
    let routes_with_responses = result.routes.len(); // All routes have responses

    println!("  Total Endpoints: {}", total_routes.to_string().green().bold());
    println!(
        "  Endpoints with Mock Responses: {} ({}%)",
        routes_with_responses.to_string().green(),
        calculate_percentage(routes_with_responses, total_routes)
    );
    println!(
        "  Endpoints with Request Bodies: {} ({}%)",
        routes_with_bodies.to_string().green(),
        calculate_percentage(routes_with_bodies, total_routes)
    );

    // Coverage by HTTP method
    let mut method_coverage = std::collections::HashMap::new();
    for route in &result.routes {
        *method_coverage.entry(&route.method).or_insert(0) += 1;
    }

    println!();
    println!("{}", "  Coverage by HTTP Method:".bold());
    for (method, count) in method_coverage.iter() {
        let percentage = calculate_percentage(*count, total_routes);
        println!("    {}: {} ({}%)", method.cyan().bold(), count, percentage);
    }

    // Overall coverage score
    let coverage_score = 100; // We generate mocks for all endpoints
    println!();
    println!("{}", format!("✅ Overall Coverage: {}%", coverage_score).green().bold());
}

/// Display AsyncAPI coverage statistics
fn display_asyncapi_coverage(result: &AsyncApiImportResult) {
    println!("{}", "📊 Coverage Statistics:".bold());
    println!();

    let total_channels = result.channels.len();
    let channels_with_schemas = result
        .channels
        .iter()
        .filter(|ch| ch.operations.iter().any(|op| op.message_schema.is_some()))
        .count();
    let channels_with_examples = result
        .channels
        .iter()
        .filter(|ch| ch.operations.iter().any(|op| op.example_message.is_some()))
        .count();

    println!("  Total Channels: {}", total_channels.to_string().green().bold());
    println!(
        "  Channels with Message Schemas: {} ({}%)",
        channels_with_schemas.to_string().green(),
        calculate_percentage(channels_with_schemas, total_channels)
    );
    println!(
        "  Channels with Example Messages: {} ({}%)",
        channels_with_examples.to_string().green(),
        calculate_percentage(channels_with_examples, total_channels)
    );

    // Coverage by protocol
    let mut protocol_coverage = std::collections::HashMap::new();
    for channel in &result.channels {
        *protocol_coverage.entry(format!("{:?}", channel.protocol)).or_insert(0) += 1;
    }

    println!();
    println!("{}", "  Coverage by Protocol:".bold());
    for (protocol, count) in protocol_coverage.iter() {
        let percentage = calculate_percentage(*count, total_channels);
        println!("    {}: {} ({}%)", protocol.cyan().bold(), count, percentage);
    }

    // Overall coverage score
    let coverage_score = if total_channels > 0 {
        ((channels_with_schemas as f64 / total_channels as f64) * 100.0).round() as u32
    } else {
        0
    };
    println!();
    println!("{}", format!("✅ Overall Coverage: {}%", coverage_score).green().bold());
}

/// Calculate percentage
fn calculate_percentage(count: usize, total: usize) -> u32 {
    if total == 0 {
        0
    } else {
        ((count as f64 / total as f64) * 100.0).round() as u32
    }
}

/// Save OpenAPI routes to JSON file
fn save_openapi_routes(
    result: &OpenApiImportResult,
    output_path: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let json = serde_json::to_string_pretty(&result.routes)?;
    fs::write(output_path, json)?;
    Ok(())
}

/// Save AsyncAPI channels to JSON file
fn save_asyncapi_channels(
    channels: &[mockforge_import::import::asyncapi_import::MockForgeChannel],
    output_path: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let json = serde_json::to_string_pretty(&channels)?;
    fs::write(output_path, json)?;
    Ok(())
}