rok-cli 0.3.9

Developer CLI for rok-based Axum applications
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
//! `rok dev` and `rok env:check` — dev-mode server and env validation.

use std::{fs, path::Path, process::Command};

use console::style;

// ── rok dev ───────────────────────────────────────────────────────────────────

pub fn dev() -> anyhow::Result<()> {
    println!(
        "{} Starting dev server (cargo watch)...",
        style("rok dev").green().bold()
    );
    println!("  Watching src/ — restart on change");
    println!("  Ctrl+C to stop\n");

    let status = Command::new("cargo")
        .args(["watch", "--watch", "src/", "-x", "run"])
        .status();

    match status {
        Ok(s) if s.success() => Ok(()),
        Ok(_) => anyhow::bail!("cargo watch exited with error"),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            anyhow::bail!("cargo-watch not found. Install it with:\n  cargo install cargo-watch")
        }
        Err(e) => Err(e.into()),
    }
}

// ── rok serve ─────────────────────────────────────────────────────────────────

pub fn serve(port: Option<u16>, release: bool) -> anyhow::Result<()> {
    let _ = dotenvy::dotenv();

    let mut env: Vec<(String, String)> = Vec::new();
    if let Some(p) = port {
        env.push(("LISTEN_ADDR".to_string(), format!("0.0.0.0:{p}")));
        println!(
            "{} Listening on port {p}",
            style("rok serve").green().bold()
        );
    }

    let cargo_cmd = if release { "run --release" } else { "run" };

    // Try cargo-watch first
    let watch_test = Command::new("cargo").args(["watch", "--version"]).output();
    let use_watch = watch_test.map(|o| o.status.success()).unwrap_or(false);

    if use_watch {
        println!(
            "{} Starting with cargo-watch (auto-reload on change)...",
            style("rok serve").green().bold()
        );
        println!("  Ctrl+C to stop\n");

        let mut cmd = Command::new("cargo");
        cmd.args(["watch", "--watch", "src/", "-x", cargo_cmd]);
        for (k, v) in &env {
            cmd.env(k, v);
        }
        let status = cmd.status()?;
        if !status.success() {
            anyhow::bail!("cargo watch exited with error");
        }
    } else {
        println!(
            "{} Starting server (install cargo-watch for auto-reload)...",
            style("rok serve").green().bold()
        );
        println!("  Tip: cargo install cargo-watch\n");

        let mut args = vec!["run"];
        if release {
            args.push("--release");
        }
        let mut cmd = Command::new("cargo");
        cmd.args(&args);
        for (k, v) in &env {
            cmd.env(k, v);
        }
        let status = cmd.status()?;
        if !status.success() {
            anyhow::bail!("cargo run exited with error");
        }
    }

    Ok(())
}

// ── rok env:check ─────────────────────────────────────────────────────────────

pub fn env_check() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();

    println!(
        "{} Scanning config files for required env vars...\n",
        style("env:check").green().bold()
    );

    let config_dir = Path::new("src/config");
    if !config_dir.exists() {
        anyhow::bail!("src/config/ not found — is this a rok project?");
    }

    let mut keys: Vec<String> = Vec::new();
    for entry in fs::read_dir(config_dir)? {
        let entry = entry?;
        if entry.path().extension().and_then(|s| s.to_str()) != Some("rs") {
            continue;
        }
        if entry
            .file_name()
            .to_str()
            .map(|n| n == "mod.rs")
            .unwrap_or(false)
        {
            continue;
        }

        let source = fs::read_to_string(entry.path())?;
        collect_env_keys(&source, &mut keys);
    }

    if keys.is_empty() {
        println!("  No #[env(...)] attributes found in src/config/");
        return Ok(());
    }

    keys.sort();
    keys.dedup();

    let mut pass = 0usize;
    let mut fail = 0usize;

    for key in &keys {
        match std::env::var(key) {
            Ok(val) if !val.is_empty() => {
                let preview = if val.len() > 20 {
                    format!("{}", &val[..20])
                } else {
                    val.clone()
                };
                println!(
                    "  {} {:<30} = {}",
                    style("").green(),
                    key,
                    style(preview).dim()
                );
                pass += 1;
            }
            _ => {
                println!("  {} {}", style("").red(), style(key).red().bold());
                fail += 1;
            }
        }
    }

    println!();
    if fail == 0 {
        println!("{} All {} env vars set.", style("").green().bold(), pass);
    } else {
        println!(
            "{} {pass} set, {} missing — add them to your .env file.",
            style("!").yellow().bold(),
            style(fail).red().bold()
        );
    }

    Ok(())
}

fn collect_env_keys(source: &str, keys: &mut Vec<String>) {
    // Scan for #[env("KEY")] and #[env("KEY", default = ...)] patterns
    let chars = source.char_indices().peekable();
    let marker = "#[env(\"";

    for (i, _) in chars {
        if source[i..].starts_with(marker) {
            let start = i + marker.len();
            if let Some(end) = source[start..].find('"') {
                let key = &source[start..start + end];
                if !key.is_empty() {
                    keys.push(key.to_string());
                }
            }
        }
    }
}

// ── .rok/config.toml ─────────────────────────────────────────────────────────

#[allow(dead_code)]
#[derive(Debug, Default)]
pub struct RokConfig {
    pub default_id: Option<String>,
    pub default_auth: bool,
    pub soft_delete: bool,
    pub with_tests: bool,
    pub with_factory: bool,
}

#[allow(dead_code)]
impl RokConfig {
    pub fn load() -> Self {
        let path = Path::new(".rok/config.toml");
        if !path.exists() {
            return Self::default();
        }

        let Ok(content) = fs::read_to_string(path) else {
            return Self::default();
        };

        let mut cfg = RokConfig::default();
        for line in content.lines() {
            let line = line.trim();
            if let Some(val) = line.strip_prefix("default_id") {
                cfg.default_id = extract_toml_string(val);
            } else if line.starts_with("default_auth") {
                cfg.default_auth = extract_toml_bool(line);
            } else if line.starts_with("soft_delete") {
                cfg.soft_delete = extract_toml_bool(line);
            } else if line.starts_with("with_tests") {
                cfg.with_tests = extract_toml_bool(line);
            } else if line.starts_with("with_factory") {
                cfg.with_factory = extract_toml_bool(line);
            }
        }
        cfg
    }
}

#[allow(dead_code)]
fn extract_toml_string(rest: &str) -> Option<String> {
    let rest = rest.trim().trim_start_matches('=').trim();
    if rest.starts_with('"') && rest.ends_with('"') {
        Some(rest[1..rest.len() - 1].to_string())
    } else {
        None
    }
}

#[allow(dead_code)]
fn extract_toml_bool(line: &str) -> bool {
    line.contains("true")
}

/// `rok config:show` — print all environment variables from .env, masking secrets.
pub fn config_show(as_json: bool) -> anyhow::Result<()> {
    use console::style;

    dotenvy::dotenv().ok();

    let env_path = std::path::Path::new(".env");
    let pairs: Vec<(String, String)> = if env_path.exists() {
        let content = fs::read_to_string(env_path)?;
        content
            .lines()
            .filter(|l| !l.trim_start().starts_with('#') && l.contains('='))
            .map(|l| {
                let mut parts = l.splitn(2, '=');
                let key = parts.next().unwrap_or("").trim().to_string();
                let raw = parts.next().unwrap_or("").to_string();
                let val = if is_secret(&key) {
                    mask_value(&raw)
                } else {
                    raw
                };
                (key, val)
            })
            .filter(|(k, _)| !k.is_empty())
            .collect()
    } else {
        Vec::new()
    };

    if pairs.is_empty() {
        if as_json {
            println!("{{}}");
        } else {
            println!("{}", style("No .env file found.").yellow());
            println!("Create a .env file in the project root to configure your application.");
        }
        return Ok(());
    }

    if as_json {
        let map: serde_json::Map<String, serde_json::Value> = pairs
            .into_iter()
            .map(|(k, v)| (k, serde_json::Value::String(v)))
            .collect();
        println!("{}", serde_json::to_string_pretty(&map)?);
    } else {
        println!("{}", style("Environment Configuration").green().bold());
        println!();
        for (key, val) in &pairs {
            println!("  {:<35} {}", style(key).cyan(), val);
        }
        println!();
        println!(
            "  {} {} variable(s)  •  secrets masked",
            style("").green(),
            pairs.len()
        );
    }

    Ok(())
}

/// `rok env:generate` — write a .env from .env.example or generate sensible defaults.
pub fn env_generate(force: bool) -> anyhow::Result<()> {
    use console::style;

    let env_path = Path::new(".env");
    if env_path.exists() && !force {
        anyhow::bail!(
            ".env already exists. Use --force to overwrite, or delete it manually."
        );
    }

    // If .env.example exists, use it as a template
    let example_path = Path::new(".env.example");
    if example_path.exists() {
        let template = fs::read_to_string(example_path)?;
        fs::write(env_path, &template)?;
        println!(
            "{} Generated .env from .env.example",
            style("env:generate").green().bold()
        );
        println!("  {} line(s) written", template.lines().count());
        return Ok(());
    }

    // Fallback: generate a minimal .env with common rok defaults
    let defaults = concat!(
        "APP_NAME=rok-app\n",
        "APP_ENV=development\n",
        "APP_DEBUG=true\n",
        "APP_URL=http://localhost:8080\n",
        "APP_KEY=\n",
        "\n",
        "DATABASE_URL=postgres://user:password@localhost/mydb\n",
        "\n",
        "JWT_SECRET=\n",
        "JWT_ACCESS_TTL=3600\n",
        "JWT_REFRESH_TTL=604800\n",
        "\n",
        "REDIS_URL=redis://localhost:6379\n",
        "\n",
        "MAIL_DRIVER=smtp\n",
        "MAIL_FROM_ADDRESS=hello@example.com\n",
        "MAIL_FROM_NAME=rok-app\n",
    );

    fs::write(env_path, defaults)?;
    println!(
        "{} Generated default .env",
        style("env:generate").green().bold()
    );
    println!(
        "  {} Fill in APP_KEY, DATABASE_URL, JWT_SECRET, and other required values.",
        style("").yellow()
    );

    Ok(())
}

const SECRET_SUBSTRINGS: &[&str] = &[
    "PASSWORD",
    "SECRET",
    "KEY",
    "TOKEN",
    "PASS",
    "AUTH",
    "HASH",
    "CREDENTIAL",
    "CERT",
    "PRIVATE",
];

fn is_secret(key: &str) -> bool {
    let upper = key.to_uppercase();
    SECRET_SUBSTRINGS.iter().any(|s| upper.contains(s))
}

fn mask_value(val: &str) -> String {
    if val.is_empty() {
        return String::new();
    }
    if val.len() <= 4 {
        return "****".to_string();
    }
    format!("{}{}", &val[..2], &val[val.len() - 2..])
}

pub fn init_rok_config() -> anyhow::Result<()> {
    let dir = Path::new(".rok");
    let path = dir.join("config.toml");

    if path.exists() {
        println!(
            "{} .rok/config.toml already exists.",
            style("skip").yellow()
        );
        return Ok(());
    }

    fs::create_dir_all(dir)?;
    fs::write(
        &path,
        r#"# rok project configuration
# These values are used as defaults by code generators.

# default_id = "ulid"   # ulid | cuid2 | uuid_v7 | snowflake | nanoid
default_auth    = false
soft_delete     = false
with_tests      = true
with_factory    = true
"#,
    )?;
    println!("{} Created .rok/config.toml", style("").green().bold());
    Ok(())
}

/// `rok optimize` — cache configuration and routes for production.
pub fn optimize() -> anyhow::Result<()> {
    use console::style;

    println!("{} Caching configuration for production...", style("optimize").green().bold());

    let cache_dir = Path::new(".rok/cache");
    std::fs::create_dir_all(cache_dir)?;

    // Write a simple marker file indicating optimize has run
    std::fs::write(
        cache_dir.join("optimized.lock"),
        format!("optimized_at={}\n", chrono::Utc::now().to_rfc3339()),
    )?;

    println!("  {} Configuration cached at .rok/cache/", style("").green());
    println!("  {} Run {} to clear the cache.", style("Tip:").dim(), style("rok optimize:clear").cyan());

    Ok(())
}

/// `rok optimize:clear` — remove the production cache.
pub fn optimize_clear() -> anyhow::Result<()> {
    use console::style;

    let cache_dir = Path::new(".rok/cache");
    if cache_dir.exists() {
        std::fs::remove_dir_all(cache_dir)?;
        println!("{} Production cache cleared.", style("optimize:clear").green().bold());
    } else {
        println!("{} No cache to clear.", style("optimize:clear").yellow().bold());
    }
    Ok(())
}