mockforge-cli 0.3.108

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
//! MOD (Mock-Oriented Development) CLI commands
//!
//! Provides commands for MOD workflow:
//! - Initialize MOD projects
//! - Validate contracts
//! - Review mock vs. implementation
//! - Generate project templates

use anyhow::{Context, Result};
use clap::Subcommand;
use std::path::{Path, PathBuf};

/// MOD subcommands
#[derive(Subcommand, Debug)]
pub enum ModCommands {
    /// Initialize a new MOD project
    ///
    /// Creates a MOD project structure with contracts, mocks, scenarios, and personas directories.
    ///
    /// Examples:
    ///   mockforge mod init
    ///   mockforge mod init --template small-team
    ///   mockforge mod init --template microservices --name my-api
    Init {
        /// Project name (defaults to current directory name)
        #[arg(short, long)]
        name: Option<String>,

        /// Template to use (solo, small-team, large-team, monorepo, microservices, frontend)
        #[arg(short, long, default_value = "solo")]
        template: String,

        /// Output directory (defaults to current directory)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Validate contract against implementation
    ///
    /// Validates that an API implementation matches its contract specification.
    ///
    /// Examples:
    ///   mockforge mod validate --contract contracts/api.yaml --target http://localhost:8080
    Validate {
        /// Contract file path (OpenAPI or gRPC)
        #[arg(short, long)]
        contract: PathBuf,

        /// Target API URL to validate
        #[arg(short, long)]
        target: String,

        /// Fail on warnings
        #[arg(long)]
        strict: bool,
    },

    /// Review mock vs. implementation
    ///
    /// Compares mock responses with actual implementation to find discrepancies.
    ///
    /// Examples:
    ///   mockforge mod review --contract contracts/api.yaml --mock http://localhost:3000 --implementation http://localhost:8080
    Review {
        /// Contract file path
        #[arg(short, long)]
        contract: PathBuf,

        /// Mock server URL
        #[arg(short, long)]
        mock: String,

        /// Implementation URL
        #[arg(short, long)]
        implementation: String,

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

    /// Generate mock from contract
    ///
    /// Generates mock server configuration from API contract.
    ///
    /// Examples:
    ///   mockforge mod generate --from-openapi contracts/api.yaml --output mocks/
    Generate {
        /// Source contract file (OpenAPI, gRPC, or GraphQL)
        #[arg(long)]
        from_openapi: Option<PathBuf>,

        #[arg(long)]
        from_grpc: Option<PathBuf>,

        #[arg(long)]
        from_graphql: Option<PathBuf>,

        /// Output directory for generated mocks
        #[arg(short, long, default_value = "mocks")]
        output: PathBuf,

        /// Reality level (1-5)
        #[arg(long, default_value = "2")]
        reality_level: u8,
    },

    /// List available MOD templates
    ///
    /// Shows all available project templates for MOD.
    Templates {
        /// Show detailed template information
        #[arg(short, long)]
        detailed: bool,
    },
}

/// Handle MOD commands
pub async fn handle_mod_command(command: ModCommands) -> Result<()> {
    match command {
        ModCommands::Init {
            name,
            template,
            output,
        } => handle_mod_init(name, template, output).await,
        ModCommands::Validate {
            contract,
            target,
            strict,
        } => handle_mod_validate(contract, target, strict).await,
        ModCommands::Review {
            contract,
            mock,
            implementation,
            format,
        } => handle_mod_review(contract, mock, implementation, format).await,
        ModCommands::Generate {
            from_openapi,
            from_grpc,
            from_graphql,
            output,
            reality_level,
        } => {
            handle_mod_generate(from_openapi, from_grpc, from_graphql, output, reality_level).await
        }
        ModCommands::Templates { detailed } => handle_mod_templates(detailed).await,
    }
}

/// Initialize a MOD project
async fn handle_mod_init(
    name: Option<String>,
    template: String,
    output: Option<PathBuf>,
) -> Result<()> {
    let project_name = name.unwrap_or_else(|| {
        std::env::current_dir()
            .ok()
            .and_then(|p| p.file_name().and_then(|n| n.to_str().map(String::from)))
            .unwrap_or_else(|| "my-mod-project".to_string())
    });

    let output_dir =
        output.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

    println!("🚀 Initializing MOD project: {}", project_name);
    println!("   Template: {}", template);
    println!("   Output: {}", output_dir.display());

    // Create directory structure based on template
    create_mod_structure(&output_dir, &template, &project_name).await?;

    // Generate mockforge.yaml
    generate_mockforge_config(&output_dir, &template, &project_name).await?;

    // Generate README
    generate_mod_readme(&output_dir, &project_name, &template).await?;

    println!("\n✅ MOD project initialized successfully!");
    println!("\n📁 Project structure:");
    print_project_structure(&output_dir, &template);

    println!("\n📚 Next steps:");
    println!("   1. Define your API contracts in contracts/");
    println!("   2. Generate mocks: mockforge mod generate --from-openapi contracts/api.yaml");
    println!("   3. Start mock server: mockforge serve --config mockforge.yaml");
    println!("   4. Read the MOD guide: docs/MOD_GUIDE.md");

    Ok(())
}

/// Create MOD directory structure
async fn create_mod_structure(base_dir: &Path, template: &str, _project_name: &str) -> Result<()> {
    let dirs = match template {
        "solo" => vec!["contracts", "mocks", "scenarios", "personas"],
        "small-team" => vec![
            "contracts/v1",
            "contracts/v2",
            "mocks/endpoints",
            "mocks/scenarios",
            "scenarios/happy-paths",
            "scenarios/error-paths",
            "personas/users",
            "tests/contract-tests",
            "tests/integration-tests",
        ],
        "large-team" => vec![
            "contracts/users-service",
            "contracts/orders-service",
            "mocks/users-service",
            "mocks/orders-service",
            "scenarios/cross-service",
            "personas/users",
            "personas/orders",
            "tests/contract-tests",
            "tests/integration-tests",
            "tests/e2e-tests",
            "docs",
        ],
        "monorepo" => vec![
            "services/users-service/contracts",
            "services/users-service/mocks",
            "services/orders-service/contracts",
            "services/orders-service/mocks",
            "shared/contracts",
            "shared/personas",
            "shared/scenarios",
        ],
        "microservices" => vec![
            "contracts/users-service",
            "contracts/products-service",
            "contracts/orders-service",
            "mocks/users-service",
            "mocks/products-service",
            "mocks/orders-service",
            "scenarios/cross-service",
            "personas",
            "tests",
        ],
        "frontend" => vec![
            "contracts",
            "mocks/local",
            "mocks/scenarios",
            "personas",
            "tests/component-tests",
            "tests/integration-tests",
        ],
        _ => {
            return Err(anyhow::anyhow!("Unknown template: {}", template));
        }
    };

    for dir in &dirs {
        let dir_path = base_dir.join(dir);
        tokio::fs::create_dir_all(&dir_path)
            .await
            .with_context(|| format!("Failed to create directory: {}", dir_path.display()))?;
    }

    // Create .gitkeep files in empty directories
    for dir in &dirs {
        let gitkeep = base_dir.join(dir).join(".gitkeep");
        if !gitkeep.exists() {
            tokio::fs::write(&gitkeep, "").await.ok();
        }
    }

    Ok(())
}

/// Generate mockforge.yaml configuration
async fn generate_mockforge_config(
    base_dir: &Path,
    template: &str,
    project_name: &str,
) -> Result<()> {
    let config = match template {
        "solo" => format!(
            r#"# MockForge Configuration for {project_name}
# MOD (Mock-Oriented Development) Project

workspaces:
  - name: {project_name}
    port: 3000
    reality:
      level: 2
      personas:
        enabled: true

# Contract paths
contracts:
  - contracts/*.yaml
  - contracts/*.yml

# Mock paths
mocks:
  - mocks/**/*.yaml
  - mocks/**/*.json

# Scenario paths
scenarios:
  - scenarios/**/*.yaml
"#,
            project_name = project_name
        ),
        "small-team" => format!(
            r#"# MockForge Configuration for {project_name}
# MOD (Mock-Oriented Development) Project - Small Team

workspaces:
  - name: {project_name}
    port: 3000
    reality:
      level: 3
      personas:
        enabled: true
      latency:
        enabled: true

# Contract paths
contracts:
  - contracts/v1/*.yaml
  - contracts/v2/*.yaml

# Mock paths
mocks:
  - mocks/**/*.yaml

# Scenario paths
scenarios:
  - scenarios/**/*.yaml
"#,
            project_name = project_name
        ),
        _ => format!(
            r#"# MockForge Configuration for {project_name}
# MOD (Mock-Oriented Development) Project

workspaces:
  - name: {project_name}
    port: 3000
    reality:
      level: 2
      personas:
        enabled: true

# Contract paths
contracts:
  - contracts/**/*.yaml

# Mock paths
mocks:
  - mocks/**/*.yaml

# Scenario paths
scenarios:
  - scenarios/**/*.yaml
"#,
            project_name = project_name
        ),
    };

    let config_path = base_dir.join("mockforge.yaml");
    tokio::fs::write(&config_path, config)
        .await
        .with_context(|| format!("Failed to write config file: {}", config_path.display()))?;

    Ok(())
}

/// Generate MOD README
async fn generate_mod_readme(base_dir: &Path, project_name: &str, template: &str) -> Result<()> {
    let readme = format!(
        r#"# {project_name}

MOD (Mock-Oriented Development) Project

## Template: {template}

## Quick Start

1. Define your API contracts in `contracts/`
2. Generate mocks: `mockforge mod generate --from-openapi contracts/api.yaml`
3. Start mock server: `mockforge serve --config mockforge.yaml`
4. Develop against mocks!

## Project Structure

- `contracts/` - API contract definitions (OpenAPI, gRPC, GraphQL)
- `mocks/` - Mock server configurations
- `scenarios/` - Test scenarios and user journeys
- `personas/` - Persona definitions for consistent data

## MOD Workflow

1. **Design** - Define API contracts
2. **Mock** - Generate mocks from contracts
3. **Develop** - Build against mocks
4. **Validate** - Validate implementation against contracts
5. **Review** - Compare mock vs. implementation

## Resources

- [MOD Philosophy](docs/MOD_PHILOSOPHY.md)
- [MOD Guide](docs/MOD_GUIDE.md)
- [MOD Patterns](docs/MOD_PATTERNS.md)

## Commands

```bash
# Initialize project (already done)
mockforge mod init --template {template}

# Generate mock from contract
mockforge mod generate --from-openapi contracts/api.yaml

# Validate implementation
mockforge mod validate --contract contracts/api.yaml --target http://localhost:8080

# Review mock vs. implementation
mockforge mod review --contract contracts/api.yaml --mock http://localhost:3000 --implementation http://localhost:8080
```
"#,
        project_name = project_name,
        template = template
    );

    let readme_path = base_dir.join("README.md");
    tokio::fs::write(&readme_path, readme)
        .await
        .with_context(|| format!("Failed to write README: {}", readme_path.display()))?;

    Ok(())
}

/// Print project structure
fn print_project_structure(_base_dir: &PathBuf, template: &str) {
    let structure = match template {
        "solo" => {
            r#"
my-project/
├── mockforge.yaml
├── README.md
├── contracts/
├── mocks/
├── scenarios/
└── personas/
"#
        }
        "small-team" => {
            r#"
my-project/
├── mockforge.yaml
├── README.md
├── contracts/
│   ├── v1/
│   └── v2/
├── mocks/
│   ├── endpoints/
│   └── scenarios/
├── scenarios/
│   ├── happy-paths/
│   └── error-paths/
├── personas/
│   └── users/
└── tests/
    ├── contract-tests/
    └── integration-tests/
"#
        }
        _ => {
            r#"
my-project/
├── mockforge.yaml
├── README.md
├── contracts/
├── mocks/
├── scenarios/
└── personas/
"#
        }
    };

    println!("{}", structure);
}

/// Validate contract against implementation
async fn handle_mod_validate(contract: PathBuf, target: String, _strict: bool) -> Result<()> {
    println!("🔍 Validating contract against implementation...");
    println!("   Contract: {}", contract.display());
    println!("   Target: {}", target);

    // Check if contract file exists
    if !contract.exists() {
        return Err(anyhow::anyhow!("Contract file not found: {}", contract.display()));
    }

    // Read contract
    let contract_content = tokio::fs::read_to_string(&contract).await?;

    // Detect contract type
    let contract_type = if contract_content.contains("openapi")
        || contract_content.contains("swagger")
    {
        "openapi"
    } else if contract_content.contains("syntax") && contract_content.contains("proto") {
        "grpc"
    } else if contract_content.contains("type Query") || contract_content.contains("type Mutation")
    {
        "graphql"
    } else {
        return Err(anyhow::anyhow!("Unknown contract type. Supported: OpenAPI, gRPC, GraphQL"));
    };

    println!("   Type: {}", contract_type);

    // For now, provide guidance
    println!("\n💡 Contract validation:");
    println!("   1. Ensure target API is running: {}", target);
    println!("   2. Use mockforge validate command for full validation");
    println!("   3. Check contract syntax is valid");
    println!("   4. Verify all endpoints match contract");

    println!("\n✅ Validation check complete!");
    println!("   Note: Full validation requires running 'mockforge validate' command");

    Ok(())
}

/// Review mock vs. implementation
async fn handle_mod_review(
    contract: PathBuf,
    mock: String,
    implementation: String,
    _format: String,
) -> Result<()> {
    println!("📊 Reviewing mock vs. implementation...");
    println!("   Contract: {}", contract.display());
    println!("   Mock: {}", mock);
    println!("   Implementation: {}", implementation);

    // Check if contract file exists
    if !contract.exists() {
        return Err(anyhow::anyhow!("Contract file not found: {}", contract.display()));
    }

    // For now, provide guidance
    println!("\n💡 Mock vs. Implementation Review:");
    println!("   1. Compare response schemas");
    println!("   2. Check status codes match");
    println!("   3. Verify error responses");
    println!("   4. Test edge cases");
    println!("   5. Validate data consistency");

    println!("\n✅ Review complete!");
    println!("   Note: Full comparison requires API testing tools");

    Ok(())
}

/// Generate mock from contract
async fn handle_mod_generate(
    from_openapi: Option<PathBuf>,
    from_grpc: Option<PathBuf>,
    from_graphql: Option<PathBuf>,
    output: PathBuf,
    reality_level: u8,
) -> Result<()> {
    // Determine contract type before moving values
    let contract_type = if from_openapi.is_some() {
        "openapi"
    } else if from_grpc.is_some() {
        "grpc"
    } else if from_graphql.is_some() {
        "graphql"
    } else {
        return Err(anyhow::anyhow!("Must specify --from-openapi, --from-grpc, or --from-graphql"));
    };

    let source = from_openapi.or(from_grpc).or(from_graphql).ok_or_else(|| {
        anyhow::anyhow!("Must specify --from-openapi, --from-grpc, or --from-graphql")
    })?;

    println!("🎨 Generating mock from contract...");
    println!("   Source: {}", source.display());
    println!("   Type: {}", contract_type);
    println!("   Output: {}", output.display());
    println!("   Reality Level: {}", reality_level);

    // Check if source file exists
    if !source.exists() {
        return Err(anyhow::anyhow!("Contract file not found: {}", source.display()));
    }

    // Create output directory
    tokio::fs::create_dir_all(&output).await?;

    // Use existing generate command
    println!("\n💡 Generating mock configuration...");
    println!(
        "   Use 'mockforge generate --from-openapi {} --output {}' for full generation",
        source.display(),
        output.display()
    );

    println!("\n✅ Mock generation initiated!");
    println!("   Check {} for generated mock files", output.display());

    Ok(())
}

/// List available MOD templates
async fn handle_mod_templates(detailed: bool) -> Result<()> {
    println!("📋 Available MOD Templates:\n");

    let templates = vec![
        ("solo", "Solo Developer", "Simple structure for individual projects"),
        ("small-team", "Small Team (2-5)", "Organized structure for small teams"),
        ("large-team", "Large Team (6+)", "Service-based structure for large teams"),
        ("monorepo", "Monorepo", "Structure for monorepo projects"),
        ("microservices", "Microservices", "Multi-service structure"),
        ("frontend", "Frontend-Focused", "Structure for frontend teams"),
    ];

    for (id, name, description) in templates {
        if detailed {
            println!("📦 {}", name);
            println!("   ID: {}", id);
            println!("   Description: {}", description);
            println!();
        } else {
            println!("{} ({})", name, id);
        }
    }

    if !detailed {
        println!("\n💡 Use --detailed for more information");
    }

    Ok(())
}