larakiln 0.4.0

Port Laravel PHP apps to a new Laravel runtime (Laravel Rust today) and check nothing was lost: audit, plan, codegen, route parity
//! `/port-next`: the first unticked PORTING.md item, with where to read and where to write.
//! Free reads whole files from here; Pro's `larakiln pack` would cut them down to the item.

use std::fs;
use std::path::{Path, PathBuf};

use regex::Regex;
use serde_json::Value;

use crate::feasibility;

pub fn run(porting: &Path, inventory: &Path, rust: Option<&Path>) -> Result<(), String> {
    let md = fs::read_to_string(porting).map_err(|e| format!("{}: {e} (run `larakiln manifest` first)", porting.display()))?;
    let inv = feasibility::load(inventory)?;
    print!("{}", render(&md, &inv, rust));
    Ok(())
}

/// Item and section by id, from any inventory list.
fn find<'a>(inv: &'a Value, id: &str) -> Option<(&'a str, &'a Value)> {
    inv.as_object()?.iter().find_map(|(k, v)| v.as_array()?.iter().find(|i| i["id"] == id).map(|i| (k.as_str(), i)))
}

/// PHP file (relative to the app) and what to look at in it.
fn php_source(section: &str, item: &Value) -> Option<String> {
    if section == "routes" {
        let action = item["action"].as_str().unwrap_or("Closure");
        if action == "Closure" {
            let api = item["middleware"].as_array().is_some_and(|m| m.iter().any(|x| x == "api"));
            let uri = item["uri"].as_str().unwrap_or("");
            return Some(format!("`routes/{}.php`: the closure for `{uri}`", if api { "api" } else { "web" }));
        }
        let (class, method) = action.split_once('@').unwrap_or((action, "__invoke"));
        let file = class.strip_prefix("App\\").map(|c| format!("app/{}.php", c.replace('\\', "/")))?;
        return Some(format!("`{file}`: method `{method}`"));
    }
    if section == "packages" {
        return Some(format!("`composer.json`: `{}`, and where the app uses it", item["name"].as_str().unwrap_or("?")));
    }
    item["file"].as_str().map(|f| format!("`{f}`"))
}

fn reference(section: &str, inertia: bool) -> &'static str {
    match section {
        "models" | "policies" => "`references/models-eloquent.md`",
        "requests" => "`references/validation.md`",
        "views" => "`references/blade-to-jinja.md`",
        "data_risks" => "`references/auth-sessions.md`",
        "packages" => "`references/packages.md`",
        "middleware" => "`references/config-env.md`",
        "jobs" | "mail" | "notifications" | "events" | "listeners" | "observers" | "commands" | "schedule" => "`references/queues-mail-events.md`",
        "tests" => "the testing docs from docs-path.sh",
        _ if inertia => "`references/routing-handlers.md` and `references/inertia.md`",
        _ => "`references/routing-handlers.md`",
    }
}

/// `file:line` of each `larakiln: <id>` marker, and the PORT-TODO lines in that item's block.
fn stubs(rust: &Path, id: &str) -> Vec<(String, Vec<String>)> {
    let mut files = Vec::new();
    collect(&rust.join("src"), &mut files);
    collect(&rust.join("resources/views"), &mut files);
    files.sort();
    let mut found = Vec::new();
    for f in files {
        let Ok(text) = fs::read_to_string(&f) else { continue };
        let lines: Vec<&str> = text.lines().collect();
        let Some(start) = lines.iter().position(|l| marker(l).is_some_and(|m| m == id)) else { continue };
        // One block may carry several markers in a row (codegen merges input structs with the same rules).
        let body = (start + 1..lines.len()).find(|&n| marker(lines[n]).is_none()).unwrap_or(lines.len());
        let end = lines.iter().skip(body).position(|l| marker(l).is_some()).map_or(lines.len(), |n| body + n);
        let rel = f.strip_prefix(rust).unwrap_or(&f).display().to_string();
        let todos = (start..end).filter(|&n| lines[n].contains("PORT-TODO")).map(|n| format!("{rel}:{}: {}", n + 1, short(lines[n].trim()))).collect();
        found.push((format!("{rel}:{}", start + 1), todos));
    }
    found
}

/// One line of context, not a minified stylesheet: the TODO itself plus some code around it.
fn short(line: &str) -> String {
    if line.chars().count() <= 160 {
        return line.to_string();
    }
    let at = line.find("PORT-TODO").unwrap_or(0);
    let start = line[..at].char_indices().rev().nth(60).map_or(0, |(i, _)| i);
    let tail: String = line[start..].chars().take(160).collect();
    format!("…{tail}…")
}

/// The id in `/// larakiln: <id> (…)`, `// larakiln: <id>` or `{# larakiln: <id> #}`.
fn marker(line: &str) -> Option<&str> {
    let rest = line.trim().trim_start_matches(['/', '{', '#', ' ']).strip_prefix("larakiln: ")?;
    Some(rest.trim_end_matches("#}").trim().split(" (").next().unwrap_or(rest))
}

fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
    for e in fs::read_dir(dir).into_iter().flatten().flatten() {
        let p = e.path();
        if p.is_dir() {
            collect(&p, out);
        } else if p.extension().is_some_and(|x| x == "rs" || x == "html") {
            out.push(p);
        }
    }
}

fn render(md: &str, inv: &Value, rust: Option<&Path>) -> String {
    let item_re = Regex::new(r"(?m)^\s*- \[([ xX])\] `([^`]+)`(.*)$").unwrap();
    let items: Vec<_> = item_re.captures_iter(md).collect();
    let done = items.iter().filter(|c| &c[1] != " ").count();
    let Some(next) = items.iter().find(|c| &c[1] == " ") else {
        return format!("All {done} items in PORTING.md are done. Run /port-verify (`larakiln route-parity`) and the ported tests.\n");
    };
    let id = &next[2];
    let at = next.get(0).unwrap().start();
    let phase = md[..at].lines().rev().find(|l| l.starts_with("## ")).unwrap_or("## ?").trim_start_matches("## ");

    let mut out = format!("# Next: `{id}`\n\nProgress {done}/{} · phase {phase}\n\n", items.len());
    let note = next[3].trim().trim_start_matches('·').trim();
    if !note.is_empty() {
        out += &format!("Note: {note}\n\n");
    }
    let Some((section, item)) = find(inv, id) else {
        return out + "Not in the inventory: re-run `larakiln audit` and `larakiln manifest`.\n";
    };
    let app = inv["app"]["path"].as_str().unwrap_or("<php-app>");
    out += &format!("- **PHP (read only):** {} in `{app}`\n", php_source(section, item).unwrap_or_else(|| "no source file (decide from the note above)".into()));
    let inertia = inv["app"]["frontend"].as_str().is_some_and(|f| f.starts_with("inertia"));
    out += &format!("- **Reference:** {}, then `references/php-to-rust-traps.md`\n", reference(section, inertia));
    match rust {
        None => out += "- **Rust:** pass `--rust <rust-app>` to find the generated stub\n",
        Some(dir) => {
            let found = stubs(dir, id);
            if found.is_empty() {
                out += if ["models", "requests", "views", "routes"].contains(&section) {
                    "- **Rust:** no generated stub; run `larakiln codegen` first, or write it by hand\n"
                } else {
                    "- **Rust:** not generated; write it by hand\n"
                };
            }
            for (at, todos) in found {
                out += &format!("- **Rust:** `{at}` ({} PORT-TODO)\n", todos.len());
                for t in todos {
                    out += &format!("  - `{t}`\n");
                }
            }
        }
    }
    out += "\n**Done when:** `cargo build` passes, this item has no PORT-TODO left, and its ported tests pass. Then tick its box in PORTING.md.\n";
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn picks_first_unticked_and_finds_its_stub() {
        let md = "## 2. Models and policies\n\n- [x] `model:User`\n\n## 5. Routes and handlers\n\n### ChirpController\n\n- [ ] `route:PUT:/chirps/{chirp}` · `update`\n- [ ] `route:GET:/chirps` · `index`\n\n## Blocked (1)\n\n- `pkg:livewire/livewire`: no\n";
        let inv = json!({"app": {"path": "/php"}, "routes": [
            {"id": "route:PUT:/chirps/{chirp}", "action": "App\\Http\\Controllers\\ChirpController@update", "uri": "/chirps/{chirp}"}
        ]});
        let rust = std::env::temp_dir().join(format!("larakiln-next-{}", std::process::id()));
        fs::create_dir_all(rust.join("src/http/handlers")).unwrap();
        fs::write(
            rust.join("src/http/handlers/chirps.rs"),
            "/// larakiln: route:GET:/chirps (ChirpController@index)\npub async fn index() { todo!(\"PORT-TODO: a\") }\n/// larakiln: route:PUT:/chirps/{chirp} (ChirpController@update)\npub async fn update() {\n    todo!(\"PORT-TODO: b\")\n}\n",
        )
        .unwrap();
        let out = render(md, &inv, Some(&rust));
        fs::remove_dir_all(&rust).unwrap();

        assert!(out.contains("# Next: `route:PUT:/chirps/{chirp}`") && out.contains("Progress 1/3 · phase 5. Routes and handlers"), "{out}");
        assert!(out.contains("`app/Http/Controllers/ChirpController.php`: method `update`"), "{out}");
        assert!(out.contains("`src/http/handlers/chirps.rs:3` (1 PORT-TODO)") && out.contains("chirps.rs:5: todo!(\"PORT-TODO: b\")") && !out.contains("PORT-TODO: a"), "{out}");
        assert!(render("- [x] `a`\n", &inv, None).starts_with("All 1 items"));
        assert_eq!(marker("{# larakiln: view:chirps.index #}"), Some("view:chirps.index"));
        assert_eq!(marker("// larakiln: model:Chirp"), Some("model:Chirp"));
        let long = format!("{}{{# PORT-TODO: x #}}{}", "a".repeat(500), "b".repeat(500));
        assert!(short(&long).contains("PORT-TODO: x") && short(&long).chars().count() < 200);
    }
}