mockforge-cli 0.3.0

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
//! Blueprint management CLI commands
//!
//! Blueprints are predefined app archetypes that provide:
//! - Pre-configured personas
//! - Reality defaults optimized for the use case
//! - Sample flows demonstrating common workflows
//! - Playground collections for testing

use clap::Subcommand;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Blueprint metadata structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlueprintMetadata {
    pub manifest_version: String,
    pub name: String,
    pub version: String,
    pub title: String,
    pub description: String,
    pub author: String,
    #[serde(default)]
    pub author_email: Option<String>,
    pub category: String,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub setup: Option<BlueprintSetup>,
    #[serde(default)]
    pub compatibility: Option<BlueprintCompatibility>,
    #[serde(default)]
    pub files: Vec<String>,
    #[serde(default)]
    pub readme: Option<String>,
}

/// Blueprint setup configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlueprintSetup {
    #[serde(default)]
    pub personas: Vec<PersonaInfo>,
    #[serde(default)]
    pub reality: Option<RealityInfo>,
    #[serde(default)]
    pub flows: Vec<FlowInfo>,
    #[serde(default)]
    pub playground: Option<PlaygroundInfo>,
}

/// Persona information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonaInfo {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
}

/// Reality level information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealityInfo {
    pub level: String,
    #[serde(default)]
    pub description: Option<String>,
}

/// Flow information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowInfo {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
}

/// Playground information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaygroundInfo {
    #[serde(default = "default_true")]
    pub enabled: bool,
    pub collection_file: String,
}

fn default_true() -> bool {
    true
}

/// Blueprint compatibility requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlueprintCompatibility {
    #[serde(default = "default_min_version")]
    pub min_version: String,
    #[serde(default)]
    pub max_version: Option<String>,
    #[serde(default)]
    pub required_features: Vec<String>,
    #[serde(default)]
    pub protocols: Vec<String>,
}

fn default_min_version() -> String {
    "0.3.0".to_string()
}

/// Blueprint subcommands
#[derive(Subcommand)]
pub enum BlueprintCommands {
    /// List available blueprints
    List {
        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,

        /// Filter by category
        #[arg(short, long)]
        category: Option<String>,
    },

    /// Create a new project from a blueprint
    Create {
        /// Project name
        name: String,

        /// Blueprint ID to use
        #[arg(short, long)]
        blueprint: String,

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

        /// Overwrite existing directory
        #[arg(long)]
        force: bool,
    },

    /// Show blueprint information
    Info {
        /// Blueprint ID
        blueprint_id: String,
    },
}

/// Get the blueprints directory
fn get_blueprints_dir() -> PathBuf {
    // For now, use blueprints/ in the project root
    // In the future, this could be configurable or use a registry
    PathBuf::from("blueprints")
}

/// List all available blueprints
pub fn list_blueprints(detailed: bool, category: Option<String>) -> anyhow::Result<()> {
    let blueprints_dir = get_blueprints_dir();

    if !blueprints_dir.exists() {
        println!("No blueprints directory found at: {}", blueprints_dir.display());
        return Ok(());
    }

    let mut blueprints = Vec::new();

    // Scan for blueprint directories
    for entry in fs::read_dir(&blueprints_dir)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
            let blueprint_yaml = path.join("blueprint.yaml");
            if blueprint_yaml.exists() {
                if let Ok(metadata) = load_blueprint_metadata(&blueprint_yaml) {
                    // Filter by category if specified
                    if let Some(ref cat) = category {
                        if metadata.category != *cat {
                            continue;
                        }
                    }
                    blueprints.push((path, metadata));
                }
            }
        }
    }

    if blueprints.is_empty() {
        println!("No blueprints found.");
        return Ok(());
    }

    // Sort by name
    blueprints.sort_by(|a, b| a.1.name.cmp(&b.1.name));

    println!("Available Blueprints:\n");

    for (path, metadata) in blueprints {
        if detailed {
            println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            println!("Name:        {}", metadata.name);
            println!("Title:       {}", metadata.title);
            println!("Version:     {}", metadata.version);
            println!("Category:    {}", metadata.category);
            println!("Description: {}", metadata.description.lines().next().unwrap_or(""));
            if !metadata.tags.is_empty() {
                println!("Tags:        {}", metadata.tags.join(", "));
            }
            println!("Path:        {}", path.display());
            println!();
        } else {
            println!("{} ({}) - {}", metadata.name, metadata.category, metadata.title);
        }
    }

    Ok(())
}

/// Create a project from a blueprint
pub fn create_from_blueprint(
    name: String,
    blueprint_id: String,
    output: Option<PathBuf>,
    force: bool,
) -> anyhow::Result<()> {
    let blueprints_dir = get_blueprints_dir();
    let blueprint_path = blueprints_dir.join(&blueprint_id);

    if !blueprint_path.exists() {
        anyhow::bail!("Blueprint '{}' not found at: {}", blueprint_id, blueprint_path.display());
    }

    let blueprint_yaml = blueprint_path.join("blueprint.yaml");
    if !blueprint_yaml.exists() {
        anyhow::bail!("Blueprint metadata not found: {}", blueprint_yaml.display());
    }

    let metadata = load_blueprint_metadata(&blueprint_yaml)?;

    // Determine output directory
    let output_dir = output.unwrap_or_else(|| PathBuf::from(&name));

    if output_dir.exists() && !force {
        anyhow::bail!(
            "Directory '{}' already exists. Use --force to overwrite.",
            output_dir.display()
        );
    }

    // Create output directory
    if output_dir.exists() && force {
        fs::remove_dir_all(&output_dir)?;
    }
    fs::create_dir_all(&output_dir)?;

    println!("Creating project '{}' from blueprint '{}'...", name, blueprint_id);

    // Copy blueprint files
    copy_blueprint_files(&blueprint_path, &output_dir, &metadata)?;

    // Generate project-specific files
    generate_project_files(&output_dir, &name, &metadata)?;

    println!("✅ Project created successfully!");
    println!("\nNext steps:");
    println!("  1. cd {}", output_dir.display());
    println!("  2. Review mockforge.yaml configuration");
    println!("  3. Run: mockforge serve");

    Ok(())
}

/// Show blueprint information
pub fn show_blueprint_info(blueprint_id: String) -> anyhow::Result<()> {
    let blueprints_dir = get_blueprints_dir();
    let blueprint_path = blueprints_dir.join(&blueprint_id);
    let blueprint_yaml = blueprint_path.join("blueprint.yaml");

    if !blueprint_yaml.exists() {
        anyhow::bail!("Blueprint '{}' not found", blueprint_id);
    }

    let metadata = load_blueprint_metadata(&blueprint_yaml)?;

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("Blueprint: {}", metadata.name);
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("\nTitle:       {}", metadata.title);
    println!("Version:     {}", metadata.version);
    println!("Category:    {}", metadata.category);
    println!("Author:      {}", metadata.author);
    if let Some(email) = &metadata.author_email {
        println!("Email:       {}", email);
    }
    println!("\nDescription:");
    for line in metadata.description.lines() {
        println!("  {}", line);
    }

    if !metadata.tags.is_empty() {
        println!("\nTags: {}", metadata.tags.join(", "));
    }

    if let Some(setup) = &metadata.setup {
        if !setup.personas.is_empty() {
            println!("\nPersonas:");
            for persona in &setup.personas {
                println!("{} - {}", persona.id, persona.name);
                if let Some(desc) = &persona.description {
                    println!("    {}", desc);
                }
            }
        }

        if let Some(reality) = &setup.reality {
            println!("\nReality Level: {}", reality.level);
            if let Some(desc) = &reality.description {
                println!("  {}", desc);
            }
        }

        if !setup.flows.is_empty() {
            println!("\nSample Flows:");
            for flow in &setup.flows {
                println!("{} - {}", flow.id, flow.name);
                if let Some(desc) = &flow.description {
                    println!("    {}", desc);
                }
            }
        }
    }

    println!("\nPath: {}", blueprint_path.display());

    Ok(())
}

/// Load blueprint metadata from YAML file
fn load_blueprint_metadata(path: &Path) -> anyhow::Result<BlueprintMetadata> {
    let content = fs::read_to_string(path)?;
    let metadata: BlueprintMetadata = serde_yaml::from_str(&content)?;
    Ok(metadata)
}

/// Copy blueprint files to output directory
fn copy_blueprint_files(
    blueprint_path: &Path,
    output_dir: &Path,
    metadata: &BlueprintMetadata,
) -> anyhow::Result<()> {
    // Copy config.yaml if it exists
    let config_src = blueprint_path.join("config.yaml");
    if config_src.exists() {
        let config_dst = output_dir.join("mockforge.yaml");
        fs::copy(&config_src, &config_dst)?;
        println!("  ✓ Created mockforge.yaml");
    }

    // Copy personas directory
    let personas_src = blueprint_path.join("personas");
    if personas_src.exists() {
        let personas_dst = output_dir.join("personas");
        copy_directory(&personas_src, &personas_dst)?;
        println!("  ✓ Copied personas/");
    }

    // Copy flows directory
    let flows_src = blueprint_path.join("flows");
    if flows_src.exists() {
        let flows_dst = output_dir.join("flows");
        copy_directory(&flows_src, &flows_dst)?;
        println!("  ✓ Copied flows/");
    }

    // Copy playground directory
    let playground_src = blueprint_path.join("playground");
    if playground_src.exists() {
        let playground_dst = output_dir.join("playground");
        copy_directory(&playground_src, &playground_dst)?;
        println!("  ✓ Copied playground/");
    }

    // Copy other files listed in metadata
    for file in &metadata.files {
        if file == "blueprint.yaml" || file == "config.yaml" {
            continue; // Already handled
        }

        let src = blueprint_path.join(file);
        if src.exists() {
            if src.is_file() {
                let dst = output_dir.join(file);
                if let Some(parent) = dst.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::copy(&src, &dst)?;
            } else if src.is_dir() {
                let dst = output_dir.join(file);
                copy_directory(&src, &dst)?;
            }
        }
    }

    Ok(())
}

/// Copy a directory recursively
fn copy_directory(src: &Path, dst: &Path) -> anyhow::Result<()> {
    fs::create_dir_all(dst)?;

    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let path = entry.path();
        let file_name = path.file_name().unwrap();
        let dst_path = dst.join(file_name);

        if path.is_dir() {
            copy_directory(&path, &dst_path)?;
        } else {
            fs::copy(&path, &dst_path)?;
        }
    }

    Ok(())
}

/// Generate project-specific files
fn generate_project_files(
    output_dir: &Path,
    name: &str,
    metadata: &BlueprintMetadata,
) -> anyhow::Result<()> {
    // Generate README if it doesn't exist
    let readme_path = output_dir.join("README.md");
    if !readme_path.exists() {
        let readme_content = generate_readme(name, metadata);
        fs::write(&readme_path, readme_content)?;
        println!("  ✓ Created README.md");
    }

    Ok(())
}

/// Generate README content
fn generate_readme(name: &str, metadata: &BlueprintMetadata) -> String {
    format!(
        r#"# {}

{}

This project was created from the **{}** blueprint.

## Quick Start

```bash
# Start the mock server
mockforge serve

# Or with a specific config
mockforge serve --config mockforge.yaml
```

## What's Included

{}

## Documentation

For more information, visit: https://docs.mockforge.dev
"#,
        name,
        metadata.description,
        metadata.title,
        if let Some(setup) = &metadata.setup {
            let mut sections = Vec::new();

            if !setup.personas.is_empty() {
                sections.push(format!(
                    "### Personas\n\nThis blueprint includes {} predefined personas.",
                    setup.personas.len()
                ));
            }

            if !setup.flows.is_empty() {
                sections.push(format!(
                    "### Sample Flows\n\n{} sample flows demonstrating common workflows.",
                    setup.flows.len()
                ));
            }

            if setup.playground.as_ref().map(|p| p.enabled).unwrap_or(false) {
                sections.push(
                    "### Playground Collection\n\nA playground collection for testing endpoints."
                        .to_string(),
                );
            }

            sections.join("\n\n")
        } else {
            "This blueprint provides a complete setup for your use case.".to_string()
        }
    )
}