cargo-quickstart 0.1.4

A cargo subcommand for quickly generating Rust project scaffolds
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
//! Enhanced interactive wizard for project setup

use std::path::PathBuf;

use color_eyre::eyre::Report;
use color_eyre::Result;
use quickstart_lib::{ProjectConfig, ProjectType};

use crate::commands::init::inquire_api::{InquireApi, RealInquire};

/// Run the interactive setup wizard
pub fn run_wizard(path: PathBuf) -> Result<ProjectConfig> {
    let inquire_api = RealInquire;
    run_wizard_with_api(&inquire_api, path)
}

/// Run the interactive setup wizard with dependency injection
/// This function allows for testing with a mock implementation
pub fn run_wizard_with_api<T: InquireApi>(inquire_api: &T, path: PathBuf) -> Result<ProjectConfig> {
    // Check if directory exists and create it if needed
    if !path.exists() {
        let dir_str = path.display().to_string();
        let create_dir = inquire_api.confirm(
            &format!("Directory {dir_str} does not exist. Create it?"),
            true,
        )?;

        if !create_dir {
            return Err(Report::msg("Project creation cancelled"));
        }

        std::fs::create_dir_all(&path)
            .map_err(|e| Report::msg(format!("Failed to create directory: {e}")))?;
    }

    // Step 1: Project name
    let name = get_project_name_with_api(inquire_api)?;

    // Step 2: Project type (binary/library)
    let project_type = get_project_type_with_api(inquire_api)?;

    // Step 3: Rust edition
    let edition = get_rust_edition_with_api(inquire_api)?;

    // Step 4: License
    let license = get_license_with_api(inquire_api)?;

    // Step 5: Git initialization
    let git = get_git_init_with_api(inquire_api)?;

    // Step 6: Optional features
    let features = get_optional_features_with_api(inquire_api)?;

    // Create project config
    let config = ProjectConfig {
        name,
        project_type,
        edition,
        license,
        git,
        path: path.clone(),
        yes: false,
    };

    // Show summary and confirmation
    let mut summary = String::new();
    summary.push_str(&format!("Project name: {}\n", config.name));
    summary.push_str(&format!("Type: {}\n", config.project_type));
    summary.push_str(&format!("Edition: {}\n", config.edition));
    summary.push_str(&format!("License: {}\n", config.license));
    summary.push_str(&format!(
        "Initialize Git: {}\n",
        if config.git { "Yes" } else { "No" }
    ));

    if !features.is_empty() {
        summary.push_str("Additional features:\n");
        for feature in &features {
            summary.push_str(&format!("  - {feature}\n"));
        }
    }

    println!("\nProject Summary:\n{summary}");

    let confirm = inquire_api.confirm("Create project with these settings?", true)?;

    if !confirm {
        return Err(Report::msg("Project creation cancelled by user"));
    }

    Ok(config)
}

/// Gets the project name from the user
#[allow(dead_code)]
pub fn get_project_name() -> Result<String> {
    let inquire_api = RealInquire;
    get_project_name_with_api(&inquire_api)
}

/// Gets the project name from the user with dependency injection
pub fn get_project_name_with_api<T: InquireApi>(inquire_api: &T) -> Result<String> {
    let validator = |input: &str| -> Result<bool, String> {
        if !input.trim().is_empty() && !input.trim().starts_with(|c: char| c.is_ascii_digit()) {
            Ok(true)
        } else {
            Ok(false)
        }
    };

    inquire_api.text_with_validation(
        "Project name:",
        Some("The name of your Rust project (valid crate name)"),
        validator,
        "Project name cannot be empty or start with a digit",
    )
}

/// Gets the project type from the user
#[allow(dead_code)]
pub fn get_project_type() -> Result<ProjectType> {
    let inquire_api = RealInquire;
    get_project_type_with_api(&inquire_api)
}

/// Gets the project type from the user with dependency injection
pub fn get_project_type_with_api<T: InquireApi>(inquire_api: &T) -> Result<ProjectType> {
    let options = ["Binary (application)", "Library"];

    match inquire_api.select("Project type:", &options, None)? {
        0 => Ok(ProjectType::Binary),
        1 => Ok(ProjectType::Library),
        _ => Ok(ProjectType::Binary), // Default to binary if somehow an invalid option is selected
    }
}

/// Gets the Rust edition from the user
#[allow(dead_code)]
pub fn get_rust_edition() -> Result<String> {
    let inquire_api = RealInquire;
    get_rust_edition_with_api(&inquire_api)
}

/// Gets the Rust edition from the user with dependency injection
pub fn get_rust_edition_with_api<T: InquireApi>(inquire_api: &T) -> Result<String> {
    let options = ["2021", "2018", "2015"];

    let idx = inquire_api.select(
        "Rust edition:",
        &options,
        Some("The Rust edition to use for your project"),
    )?;

    Ok(options[idx].to_string())
}

/// Gets the license from the user
#[allow(dead_code)]
pub fn get_license() -> Result<String> {
    let inquire_api = RealInquire;
    get_license_with_api(&inquire_api)
}

/// Gets the license from the user with dependency injection
pub fn get_license_with_api<T: InquireApi>(inquire_api: &T) -> Result<String> {
    let options = [
        "MIT OR Apache-2.0",
        "MIT",
        "Apache-2.0",
        "GPL-3.0",
        "BSD-3-Clause",
        "Unlicense",
        "Custom",
    ];

    let idx = inquire_api.select(
        "License:",
        &options,
        Some("The license to use for your project"),
    )?;

    let selection = options[idx];

    if selection == "Custom" {
        inquire_api.text(
            "Enter custom license identifier:",
            Some("Enter a valid SPDX license identifier"),
        )
    } else {
        Ok(selection.to_string())
    }
}

/// Gets git initialization preference from the user
#[allow(dead_code)]
pub fn get_git_init() -> Result<bool> {
    let inquire_api = RealInquire;
    get_git_init_with_api(&inquire_api)
}

/// Gets git initialization preference from the user with dependency injection
pub fn get_git_init_with_api<T: InquireApi>(inquire_api: &T) -> Result<bool> {
    inquire_api.confirm("Initialize Git repository?", true)
}

/// Gets optional features to include
#[allow(dead_code)]
pub fn get_optional_features() -> Result<Vec<String>> {
    let inquire_api = RealInquire;
    get_optional_features_with_api(&inquire_api)
}

/// Gets optional features to include with dependency injection
pub fn get_optional_features_with_api<T: InquireApi>(inquire_api: &T) -> Result<Vec<String>> {
    let features = [
        "README.md",
        ".gitignore",
        "CONTRIBUTING.md",
        "CI configuration",
        "VS Code configuration",
        "benchmarks",
        "examples",
    ];

    let indices = inquire_api.multiselect(
        "Select optional features:",
        &features,
        &[0, 1], // Default to README and .gitignore
        Some("Select additional files and features to include"),
    )?;

    Ok(indices
        .into_iter()
        .map(|i| features[i].to_string())
        .collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::init::inquire_api::TestInquire;
    use pretty_assertions::assert_eq;
    use tempfile::TempDir;

    #[test]
    fn test_get_project_name_valid() {
        let test_inquire = TestInquire::new();
        test_inquire.add_text("valid-project");

        let result = get_project_name_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(name) = result {
            assert_eq!(name, "valid-project");
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_project_name_invalid() {
        let test_inquire = TestInquire::new();
        test_inquire.add_text("");

        let result = get_project_name_with_api(&test_inquire);

        assert!(result.is_err());
        if let Err(err) = result {
            assert!(err.to_string().contains("Validation failed"));
        } else {
            panic!("Result should be Err but was Ok");
        }
    }

    #[test]
    fn test_get_project_type_binary() {
        let test_inquire = TestInquire::new();
        test_inquire.add_select(0);

        let result = get_project_type_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(project_type) = result {
            assert_eq!(project_type, ProjectType::Binary);
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_project_type_library() {
        let test_inquire = TestInquire::new();
        test_inquire.add_select(1);

        let result = get_project_type_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(project_type) = result {
            assert_eq!(project_type, ProjectType::Library);
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_rust_edition() {
        let test_inquire = TestInquire::new();
        test_inquire.add_select(0);

        let result = get_rust_edition_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(edition) = result {
            assert_eq!(edition, "2021");
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_license_standard() {
        let test_inquire = TestInquire::new();
        test_inquire.add_select(1);

        let result = get_license_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(license) = result {
            assert_eq!(license, "MIT");
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_license_custom() {
        let test_inquire = TestInquire::new();
        test_inquire.add_select(6); // "Custom" option
        test_inquire.add_text("My-Custom-License");

        let result = get_license_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(license) = result {
            assert_eq!(license, "My-Custom-License");
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_get_optional_features() {
        let test_inquire = TestInquire::new();
        test_inquire.add_multiselect(vec![0, 2, 4]); // Selected features at indices 0, 2, and 4

        let result = get_optional_features_with_api(&test_inquire);

        assert!(result.is_ok());
        if let Ok(features) = result {
            assert_eq!(features.len(), 3);
            assert!(features.contains(&"README.md".to_string()));
            assert!(features.contains(&"CONTRIBUTING.md".to_string()));
            assert!(features.contains(&"VS Code configuration".to_string()));
        } else {
            panic!("Result should be Ok but was Err");
        }
    }

    #[test]
    fn test_run_wizard_complete_flow() -> Result<()> {
        // Skip under Miri
        if cfg!(miri) {
            eprintln!("Skipping file system test under Miri");
            return Ok(());
        }

        let test_inquire = TestInquire::new();

        // Set up mock responses for all prompts in order
        // 1. Project name
        test_inquire.add_text("test-project");
        // 2. Project type (Binary)
        test_inquire.add_select(0);
        // 3. Rust edition (2021)
        test_inquire.add_select(0);
        // 4. License (MIT)
        test_inquire.add_select(1);
        // 5. Git init (yes)
        test_inquire.add_confirm(true);
        // 6. Optional features (README + CI)
        test_inquire.add_multiselect(vec![0, 3]);
        // 7. Final confirmation
        test_inquire.add_confirm(true);

        let temp_dir = TempDir::new()?;
        let result = run_wizard_with_api(&test_inquire, temp_dir.path().to_path_buf());

        assert!(result.is_ok());
        if let Ok(config) = result {
            assert_eq!(config.name, "test-project");
            assert_eq!(config.project_type, ProjectType::Binary);
            assert_eq!(config.edition, "2021");
            assert_eq!(config.license, "MIT");
            assert!(config.git);
        } else {
            panic!("Result should be Ok but was Err");
        }
        Ok(())
    }

    #[test]
    fn test_run_wizard_cancel_at_end() -> Result<()> {
        // Skip under Miri
        if cfg!(miri) {
            eprintln!("Skipping file system test under Miri");
            return Ok(());
        }

        let test_inquire = TestInquire::new();

        // Set up all responses but cancel at the end
        test_inquire.add_text("test-project");
        test_inquire.add_select(0);
        test_inquire.add_select(0);
        test_inquire.add_select(1);
        test_inquire.add_confirm(true);
        test_inquire.add_multiselect(vec![0, 3]);
        test_inquire.add_confirm(false); // Cancel at final confirmation

        let temp_dir = TempDir::new()?;
        let result = run_wizard_with_api(&test_inquire, temp_dir.path().to_path_buf());

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(err.to_string(), "Project creation cancelled by user");
        } else {
            panic!("Result should be Err but was Ok");
        }
        Ok(())
    }

    #[test]
    fn test_run_wizard_nonexistent_dir_create() -> Result<()> {
        // Skip under Miri
        if cfg!(miri) {
            eprintln!("Skipping file system test under Miri");
            return Ok(());
        }

        let test_inquire = TestInquire::new();

        // Confirm directory creation
        test_inquire.add_confirm(true);
        // Rest of the wizard prompts
        test_inquire.add_text("test-project");
        test_inquire.add_select(0);
        test_inquire.add_select(0);
        test_inquire.add_select(1);
        test_inquire.add_confirm(true);
        test_inquire.add_multiselect(vec![0]);
        test_inquire.add_confirm(true);

        let temp_dir = TempDir::new()?;
        let nonexistent_dir = temp_dir.path().join("nonexistent");
        let result = run_wizard_with_api(&test_inquire, nonexistent_dir.clone());

        assert!(result.is_ok());
        assert!(nonexistent_dir.exists());
        Ok(())
    }

    #[test]
    fn test_run_wizard_nonexistent_dir_cancel() -> Result<()> {
        // Skip under Miri
        if cfg!(miri) {
            eprintln!("Skipping file system test under Miri");
            return Ok(());
        }

        let test_inquire = TestInquire::new();

        // Decline directory creation
        test_inquire.add_confirm(false);

        let temp_dir = TempDir::new()?;
        let nonexistent_dir = temp_dir.path().join("nonexistent");
        let result = run_wizard_with_api(&test_inquire, nonexistent_dir.clone());

        assert!(result.is_err());
        if let Err(err) = result {
            assert_eq!(err.to_string(), "Project creation cancelled");
        } else {
            panic!("Result should be Err but was Ok");
        }
        assert!(!nonexistent_dir.exists());
        Ok(())
    }
}