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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use super::clean;
use console::style;
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::io::{BufRead, BufReader};
use std::net::TcpListener;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

struct ProcessManager {
    children: Vec<Child>,
    shutdown: Arc<AtomicBool>,
}

impl ProcessManager {
    fn new() -> Self {
        Self {
            children: Vec::new(),
            shutdown: Arc::new(AtomicBool::new(false)),
        }
    }

    fn spawn_with_prefix(
        &mut self,
        command: &str,
        args: &[&str],
        cwd: Option<&Path>,
        prefix: &str,
        color: console::Color,
    ) -> Result<(), String> {
        self.spawn_with_prefix_env(command, args, cwd, prefix, color, &[])
    }

    fn spawn_with_prefix_env(
        &mut self,
        command: &str,
        args: &[&str],
        cwd: Option<&Path>,
        prefix: &str,
        color: console::Color,
        env_vars: &[(&str, &str)],
    ) -> Result<(), String> {
        let mut cmd = Command::new(command);
        cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());

        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        if let Some(dir) = cwd {
            cmd.current_dir(dir);
        }

        let mut child = cmd
            .spawn()
            .map_err(|e| format!("Failed to spawn {command}: {e}"))?;

        let stdout = child.stdout.take().unwrap();
        let stderr = child.stderr.take().unwrap();
        let shutdown_stdout = self.shutdown.clone();
        let shutdown_stderr = self.shutdown.clone();

        let prefix_out = prefix.to_string();
        let prefix_err = prefix.to_string();

        thread::spawn(move || {
            let reader = BufReader::new(stdout);
            for line in reader.lines() {
                if shutdown_stdout.load(Ordering::SeqCst) {
                    break;
                }
                if let Ok(line) = line {
                    println!("{} {}", style(&prefix_out).fg(color).bold(), line);
                }
            }
        });

        thread::spawn(move || {
            let reader = BufReader::new(stderr);
            for line in reader.lines() {
                if shutdown_stderr.load(Ordering::SeqCst) {
                    break;
                }
                if let Ok(line) = line {
                    eprintln!("{} {}", style(&prefix_err).fg(color).bold(), line);
                }
            }
        });

        self.children.push(child);
        Ok(())
    }

    fn shutdown_all(&mut self) {
        self.shutdown.store(true, Ordering::SeqCst);
        for child in &mut self.children {
            let _ = child.kill();
            let _ = child.wait();
        }
    }

    fn any_exited(&mut self) -> bool {
        for child in &mut self.children {
            if let Ok(Some(_)) = child.try_wait() {
                return true;
            }
        }
        false
    }
}

fn get_package_name() -> Result<String, String> {
    let cargo_toml = Path::new("Cargo.toml");
    let content = std::fs::read_to_string(cargo_toml)
        .map_err(|e| format!("Failed to read Cargo.toml: {e}"))?;

    let parsed: toml::Value = content
        .parse()
        .map_err(|e| format!("Failed to parse Cargo.toml: {e}"))?;

    parsed
        .get("package")
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
        .map(|s| s.to_string())
        .ok_or_else(|| "Could not find package name in Cargo.toml".to_string())
}

fn validate_ferro_project(backend_only: bool, frontend_only: bool) -> Result<(), String> {
    let cargo_toml = Path::new("Cargo.toml");
    let frontend_dir = Path::new("frontend");

    if !frontend_only && !cargo_toml.exists() {
        return Err("No Cargo.toml found. Are you in a Ferro project directory?".into());
    }

    if !backend_only && !frontend_dir.exists() {
        return Err("No frontend directory found. Are you in a Ferro project directory?".into());
    }

    Ok(())
}

fn ensure_cargo_watch() -> Result<(), String> {
    let status = Command::new("cargo")
        .args(["watch", "--version"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();

    match status {
        Ok(s) if s.success() => Ok(()),
        _ => {
            println!("{}", style("cargo-watch not found. Installing...").yellow());
            let install = Command::new("cargo")
                .args(["install", "cargo-watch"])
                .status()
                .map_err(|e| format!("Failed to install cargo-watch: {e}"))?;

            if !install.success() {
                return Err("Failed to install cargo-watch".into());
            }
            println!("{}", style("cargo-watch installed successfully.").green());
            Ok(())
        }
    }
}

fn ensure_npm_dependencies() -> Result<(), String> {
    let frontend_path = Path::new("frontend");
    let node_modules = frontend_path.join("node_modules");

    if !node_modules.exists() {
        println!("{}", style("Installing frontend dependencies...").yellow());
        let npm_install = Command::new("npm")
            .args(["install"])
            .current_dir(frontend_path)
            .status()
            .map_err(|e| format!("Failed to run npm install: {e}"))?;

        if !npm_install.success() {
            return Err("Failed to install npm dependencies".into());
        }
        println!(
            "{}",
            style("Frontend dependencies installed successfully.").green()
        );
    }

    Ok(())
}

fn find_available_port(start: u16, max_attempts: u16) -> u16 {
    for offset in 0..max_attempts {
        let port = start + offset;
        if TcpListener::bind(("127.0.0.1", port)).is_ok() {
            return port;
        }
    }
    start
}

pub fn run(
    port: u16,
    frontend_port: u16,
    backend_only: bool,
    frontend_only: bool,
    skip_types: bool,
) {
    // Load .env file from current directory
    let _ = dotenvy::dotenv();

    // Resolve backend host and port from env vars (matching ServerConfig defaults)
    let backend_host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());

    // Resolve ports: CLI args take precedence, then env vars, then defaults
    let backend_port = if port != 8080 {
        // CLI argument was explicitly provided (different from default)
        port
    } else {
        // Use env var or default (8080)
        std::env::var("SERVER_PORT")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(8080)
    };

    let requested_vite_port = if frontend_port != 5173 {
        // CLI argument was explicitly provided
        frontend_port
    } else {
        // Use env var or default
        std::env::var("VITE_PORT")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(frontend_port)
    };

    let vite_port = find_available_port(requested_vite_port, 10);
    if vite_port != requested_vite_port {
        println!(
            "{} Port {} in use, using {} instead",
            style("[frontend]").cyan().bold(),
            requested_vite_port,
            vite_port
        );
    }

    // Set VITE_DEV_SERVER so InertiaConfig picks up the resolved port
    std::env::set_var("VITE_DEV_SERVER", format!("http://localhost:{vite_port}"));

    // Auto-cleanup old build artifacts (silent, non-blocking)
    // Configurable via CARGO_SWEEP_DAYS (default: 7, set to 0 to disable)
    let sweep_days: u32 = std::env::var("CARGO_SWEEP_DAYS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(7);

    if sweep_days > 0 {
        if let Some(cleaned) = clean::run_silent(sweep_days) {
            println!("{} {}", style("â™»").cyan(), cleaned);
        }
    }

    println!();
    println!(
        "{}",
        style("Starting Ferro development servers...").cyan().bold()
    );
    println!();

    // Validate project
    if let Err(e) = validate_ferro_project(backend_only, frontend_only) {
        eprintln!("{} {}", style("Error:").red().bold(), e);
        std::process::exit(1);
    }

    // Generate TypeScript types on startup (unless skipped or frontend-only)
    if !skip_types && !frontend_only {
        let project_path = Path::new(".");
        let output_path = project_path.join("frontend/src/types/inertia-props.ts");

        println!("{}", style("Generating TypeScript types...").cyan());
        match super::generate_types::generate_types_to_file(project_path, &output_path) {
            Ok(0) => {
                println!(
                    "{}",
                    style("No InertiaProps structs found (skipping type generation)").dim()
                );
            }
            Ok(count) => {
                println!(
                    "{} Generated {} type(s) to {}",
                    style("✓").green(),
                    count,
                    output_path.display()
                );
            }
            Err(e) => {
                // Don't fail, just warn - types are a nice-to-have
                eprintln!(
                    "{} Failed to generate types: {} (continuing anyway)",
                    style("Warning:").yellow(),
                    e
                );
            }
        }
        println!();
    }

    // Ensure cargo-watch is installed (only if running backend)
    if !frontend_only {
        if let Err(e) = ensure_cargo_watch() {
            eprintln!("{} {}", style("Error:").red().bold(), e);
            std::process::exit(1);
        }
    }

    // Ensure npm dependencies are installed (only if running frontend)
    if !backend_only {
        if let Err(e) = ensure_npm_dependencies() {
            eprintln!("{} {}", style("Error:").red().bold(), e);
            std::process::exit(1);
        }
    }

    let mut manager = ProcessManager::new();
    let shutdown = manager.shutdown.clone();

    // Set up Ctrl+C handler
    ctrlc::set_handler(move || {
        println!();
        println!("{}", style("Shutting down servers...").yellow());
        shutdown.store(true, Ordering::SeqCst);
    })
    .expect("Error setting Ctrl-C handler");

    // Start backend with cargo-watch
    if !frontend_only {
        let package_name = match get_package_name() {
            Ok(name) => name,
            Err(e) => {
                eprintln!("{} {}", style("Error:").red().bold(), e);
                std::process::exit(1);
            }
        };

        println!(
            "{} Backend server on http://{}:{}",
            style("[backend]").magenta().bold(),
            backend_host,
            backend_port
        );

        let run_cmd = format!("run --bin {package_name}");
        if let Err(e) = manager.spawn_with_prefix(
            "cargo",
            &["watch", "-x", &run_cmd],
            None,
            "[backend] ",
            console::Color::Magenta,
        ) {
            eprintln!("{} {}", style("Error:").red().bold(), e);
            std::process::exit(1);
        }
    }

    // Start frontend with npm/vite
    if !backend_only {
        println!(
            "{} Frontend server on http://127.0.0.1:{}",
            style("[frontend]").cyan().bold(),
            vite_port
        );

        let frontend_path = Path::new("frontend");
        let vite_port_str = vite_port.to_string();

        if let Err(e) = manager.spawn_with_prefix_env(
            "npm",
            &["run", "dev", "--", "--port", &vite_port_str, "--strictPort"],
            Some(frontend_path),
            "[frontend]",
            console::Color::Cyan,
            &[],
        ) {
            eprintln!("{} {}", style("Error:").red().bold(), e);
            manager.shutdown_all();
            std::process::exit(1);
        }
    }

    // Start file watcher for TypeScript type regeneration
    if !skip_types && !frontend_only {
        let shutdown_watcher = manager.shutdown.clone();
        thread::spawn(move || {
            start_type_watcher(shutdown_watcher);
        });
    }

    println!();
    println!("{}", style("Press Ctrl+C to stop all servers").dim());
    println!();

    // Wait for shutdown signal or process exit
    while !manager.shutdown.load(Ordering::SeqCst) {
        thread::sleep(std::time::Duration::from_millis(100));

        // Check if any child process has exited
        if manager.any_exited() {
            manager.shutdown.store(true, Ordering::SeqCst);
            break;
        }
    }

    manager.shutdown_all();
    println!("{}", style("Servers stopped.").green());
}

/// File watcher that regenerates TypeScript types when Rust files change
fn start_type_watcher(shutdown: Arc<AtomicBool>) {
    let (tx, rx) = channel();
    let src_path = Path::new("src");

    let watcher_result = RecommendedWatcher::new(
        move |res| {
            if let Ok(event) = res {
                let _ = tx.send(event);
            }
        },
        Config::default().with_poll_interval(Duration::from_secs(2)),
    );

    let mut watcher = match watcher_result {
        Ok(w) => w,
        Err(e) => {
            eprintln!(
                "{} Failed to start type watcher: {}",
                style("[types]").yellow(),
                e
            );
            return;
        }
    };

    if let Err(e) = watcher.watch(src_path, RecursiveMode::Recursive) {
        eprintln!(
            "{} Failed to watch src directory: {}",
            style("[types]").yellow(),
            e
        );
        return;
    }

    println!(
        "{} Watching for Rust file changes to regenerate types",
        style("[types]").blue()
    );

    let project_path = Path::new(".");
    let output_path = project_path.join("frontend/src/types/inertia-props.ts");

    // Debounce timer to avoid regenerating too frequently
    let mut last_regen = std::time::Instant::now();
    let debounce_duration = Duration::from_millis(500);

    loop {
        if shutdown.load(Ordering::SeqCst) {
            break;
        }

        // Use recv_timeout to periodically check shutdown
        match rx.recv_timeout(Duration::from_millis(100)) {
            Ok(event) => {
                // Check if it's a Rust file change
                let is_rust_change = event
                    .paths
                    .iter()
                    .any(|p| p.extension().map(|e| e == "rs").unwrap_or(false));

                if is_rust_change && last_regen.elapsed() > debounce_duration {
                    last_regen = std::time::Instant::now();

                    match super::generate_types::generate_types_to_file(project_path, &output_path)
                    {
                        Ok(count) if count > 0 => {
                            println!("{} Regenerated {} type(s)", style("[types]").blue(), count);
                        }
                        Ok(_) => {} // No types found, stay quiet
                        Err(e) => {
                            eprintln!("{} Failed to regenerate: {}", style("[types]").yellow(), e);
                        }
                    }
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
        }
    }
}