ferro-cli 0.2.6

CLI for scaffolding Ferro web applications
Documentation
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
use console::style;
use dialoguer::{theme::ColorfulTheme, Input};
use std::fs;
use std::path::Path;
use std::process::Command;

use crate::templates;

pub fn run(name: Option<String>, no_interaction: bool, no_git: bool) {
    println!();
    println!("{}", style("Welcome to Ferro!").cyan().bold());
    println!();

    let project_name = get_project_name(name, no_interaction);
    let description = get_description(no_interaction);
    let author = get_author(no_interaction);

    let package_name = to_snake_case(&project_name);

    println!();
    println!(
        "{}",
        style(format!("Creating project '{project_name}'...")).dim()
    );

    if let Err(e) = create_project(&project_name, &package_name, &description, &author, no_git) {
        eprintln!("{} {}", style("Error:").red().bold(), e);
        std::process::exit(1);
    }

    println!("{} Generated project structure", style("✓").green());

    if !no_git {
        println!("{} Initialized git repository", style("✓").green());
    }

    println!("{} Ready to go!", style("✓").green());
    println!();
    println!("Next steps:");
    println!("  {} {}", style("cd").cyan(), project_name);
    println!("  {}", style("ferro serve").cyan());
    println!();
    println!(
        "Backend will be at {}",
        style("http://localhost:8080").underlined()
    );
    println!(
        "Frontend dev server at {}",
        style("http://localhost:5173").underlined()
    );
    println!();
}

fn get_project_name(name: Option<String>, no_interaction: bool) -> String {
    if let Some(n) = name {
        return n;
    }

    if no_interaction {
        return "my-ferro-app".to_string();
    }

    // Refuse to prompt when stdin is not a TTY — dialoguer would panic otherwise.
    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        eprintln!(
            "{} project name required when not running in an interactive terminal.\n  Usage: ferro new <name>",
            style("Error:").red().bold()
        );
        std::process::exit(1);
    }

    Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Project name")
        .default("my-ferro-app".to_string())
        .interact_text()
        .unwrap()
}

fn get_description(no_interaction: bool) -> String {
    if no_interaction {
        return "A web application built with Ferro".to_string();
    }

    Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Description")
        .default("A web application built with Ferro".to_string())
        .interact_text()
        .unwrap()
}

fn get_author(no_interaction: bool) -> String {
    if no_interaction {
        return String::new();
    }

    let default_author = get_git_author().unwrap_or_default();

    Input::with_theme(&ColorfulTheme::default())
        .with_prompt("Author")
        .default(default_author)
        .allow_empty(true)
        .interact_text()
        .unwrap()
}

fn get_git_author() -> Option<String> {
    let name = Command::new("git")
        .args(["config", "user.name"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())?;

    let email = Command::new("git")
        .args(["config", "user.email"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())?;

    Some(format!("{name} <{email}>"))
}

fn to_snake_case(s: &str) -> String {
    s.replace('-', "_").to_lowercase()
}

fn to_title_case(s: &str) -> String {
    s.replace(['-', '_'], " ")
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn create_project(
    project_name: &str,
    package_name: &str,
    description: &str,
    author: &str,
    no_git: bool,
) -> Result<(), String> {
    let project_path = Path::new(project_name);

    if project_path.exists() {
        return Err(format!("Directory '{project_name}' already exists"));
    }

    // Create directory structure
    create_directories(project_path)?;

    // Write backend files
    write_backend_files(project_path, package_name, description, author)?;

    // Write README at project root
    let project_title = to_title_case(project_name);
    write_file(
        project_path,
        "README.md",
        &templates::readme(project_name, &project_title, description),
    )?;

    // Write frontend files
    write_frontend_files(project_path, project_name)?;

    // Initialize git repository
    if !no_git {
        Command::new("git")
            .args(["init"])
            .current_dir(project_path)
            .output()
            .map_err(|e| format!("Failed to initialize git repository: {e}"))?;
    }

    Ok(())
}

fn create_directories(project_path: &Path) -> Result<(), String> {
    let backend_dirs = [
        "src/controllers",
        "src/config",
        "src/middleware",
        "src/actions",
        "src/models",
        "src/migrations",
        "src/events",
        "src/listeners",
        "src/jobs",
        "src/notifications",
        "src/tasks",
        "src/seeders",
        "src/factories",
        "storage/app/public",
        "storage/logs",
        "lang/en",
    ];

    let frontend_dirs = [
        "frontend/src/pages",
        "frontend/src/pages/auth",
        "frontend/src/types",
        "frontend/src/layouts",
        "frontend/src/styles",
        "public/assets",
    ];

    for dir in backend_dirs.iter().chain(frontend_dirs.iter()) {
        fs::create_dir_all(project_path.join(dir))
            .map_err(|e| format!("Failed to create directory {dir}: {e}"))?;
    }

    Ok(())
}

fn write_backend_files(
    project_path: &Path,
    package_name: &str,
    description: &str,
    author: &str,
) -> Result<(), String> {
    // Root files
    write_file(
        project_path,
        "Cargo.toml",
        &templates::cargo_toml(package_name, description, author),
    )?;
    write_file(project_path, ".gitignore", templates::gitignore())?;
    write_file(project_path, ".env", &templates::env(package_name))?;
    write_file(project_path, ".env.example", templates::env_example())?;

    // Main source files
    write_file(
        project_path,
        "src/main.rs",
        &templates::main_rs(package_name),
    )?;
    write_file(project_path, "src/routes.rs", templates::routes_rs())?;
    write_file(project_path, "src/bootstrap.rs", templates::bootstrap())?;
    write_file(project_path, "src/schedule.rs", templates::schedule_rs())?;

    // Controllers
    write_file(
        project_path,
        "src/controllers/mod.rs",
        templates::controllers_mod(),
    )?;
    write_file(
        project_path,
        "src/controllers/home.rs",
        templates::home_controller(),
    )?;
    write_file(
        project_path,
        "src/controllers/auth.rs",
        templates::auth_controller(),
    )?;
    write_file(
        project_path,
        "src/controllers/dashboard.rs",
        templates::dashboard_controller(),
    )?;
    write_file(
        project_path,
        "src/controllers/profile.rs",
        templates::profile_controller(),
    )?;
    write_file(
        project_path,
        "src/controllers/settings.rs",
        templates::settings_controller(),
    )?;

    // Config
    write_file(project_path, "src/config/mod.rs", templates::config_mod())?;
    write_file(
        project_path,
        "src/config/database.rs",
        templates::config_database(),
    )?;
    write_file(project_path, "src/config/mail.rs", templates::config_mail())?;

    // Middleware
    write_file(
        project_path,
        "src/middleware/mod.rs",
        templates::middleware_mod(),
    )?;
    write_file(
        project_path,
        "src/middleware/logging.rs",
        templates::middleware_logging(),
    )?;
    write_file(
        project_path,
        "src/middleware/authenticate.rs",
        templates::authenticate_middleware(),
    )?;

    // Actions
    write_file(project_path, "src/actions/mod.rs", templates::actions_mod())?;
    write_file(
        project_path,
        "src/actions/example_action.rs",
        templates::example_action(),
    )?;

    // Models
    write_file(project_path, "src/models/mod.rs", templates::models_mod())?;
    write_file(project_path, "src/models/user.rs", templates::user_model())?;
    write_file(
        project_path,
        "src/models/password_reset_tokens.rs",
        templates::password_reset_tokens_model(),
    )?;

    // Migrations
    write_file(
        project_path,
        "src/migrations/mod.rs",
        templates::migrations_mod(),
    )?;
    write_file(
        project_path,
        "src/migrations/m20240101_000001_create_users_table.rs",
        templates::create_users_migration(),
    )?;
    write_file(
        project_path,
        "src/migrations/m20240101_000002_create_sessions_table.rs",
        templates::create_sessions_migration(),
    )?;
    write_file(
        project_path,
        "src/migrations/m20240101_000003_create_password_reset_tokens_table.rs",
        templates::create_password_reset_tokens_migration(),
    )?;

    // Events, Listeners, Jobs, Notifications, Tasks
    write_file(project_path, "src/events/mod.rs", templates::events_mod())?;
    write_file(
        project_path,
        "src/listeners/mod.rs",
        templates::listeners_mod(),
    )?;
    write_file(project_path, "src/jobs/mod.rs", templates::jobs_mod())?;
    write_file(
        project_path,
        "src/notifications/mod.rs",
        templates::notifications_mod(),
    )?;
    write_file(project_path, "src/tasks/mod.rs", templates::tasks_mod())?;
    write_file(project_path, "src/seeders/mod.rs", templates::seeders_mod())?;
    write_file(
        project_path,
        "src/factories/mod.rs",
        templates::factories_mod(),
    )?;

    // Storage gitkeep files
    write_file(project_path, "storage/app/.gitkeep", "")?;
    write_file(project_path, "storage/logs/.gitkeep", "")?;

    // Language files
    write_file(
        project_path,
        "lang/en/validation.json",
        templates::lang_validation_json(),
    )?;
    write_file(project_path, "lang/en/app.json", templates::lang_app_json())?;

    Ok(())
}

fn write_frontend_files(project_path: &Path, project_name: &str) -> Result<(), String> {
    let title = to_title_case(project_name);

    // Root frontend files
    write_file(
        project_path,
        "frontend/package.json",
        &templates::package_json(project_name),
    )?;
    write_file(
        project_path,
        "frontend/vite.config.ts",
        templates::vite_config(),
    )?;
    write_file(
        project_path,
        "frontend/tsconfig.json",
        templates::tsconfig(),
    )?;
    write_file(
        project_path,
        "frontend/index.html",
        &templates::index_html(&title),
    )?;

    // Frontend source files
    write_file(project_path, "frontend/src/main.tsx", templates::main_tsx())?;
    write_file(
        project_path,
        "frontend/src/types/inertia-props.ts",
        templates::inertia_props_types(),
    )?;
    write_file(
        project_path,
        "frontend/src/styles/globals.css",
        templates::globals_css(),
    )?;

    // Layouts
    write_file(
        project_path,
        "frontend/src/layouts/AppLayout.tsx",
        templates::app_layout(),
    )?;
    write_file(
        project_path,
        "frontend/src/layouts/AuthLayout.tsx",
        templates::auth_layout(),
    )?;
    write_file(
        project_path,
        "frontend/src/layouts/index.ts",
        templates::layouts_index(),
    )?;

    // Pages
    write_file(
        project_path,
        "frontend/src/pages/Home.tsx",
        templates::home_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/Dashboard.tsx",
        templates::dashboard_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/Profile.tsx",
        templates::profile_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/Settings.tsx",
        templates::settings_page(),
    )?;

    // Auth pages
    write_file(
        project_path,
        "frontend/src/pages/auth/Login.tsx",
        templates::login_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/auth/Register.tsx",
        templates::register_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/auth/ForgotPassword.tsx",
        templates::forgot_password_page(),
    )?;
    write_file(
        project_path,
        "frontend/src/pages/auth/ResetPassword.tsx",
        templates::reset_password_page(),
    )?;

    Ok(())
}

fn write_file(project_path: &Path, relative_path: &str, content: &str) -> Result<(), String> {
    let full_path = project_path.join(relative_path);
    fs::write(&full_path, content).map_err(|e| format!("Failed to write {relative_path}: {e}"))
}