Skip to main content

larust_convert/
assets.rs

1//! Copies the source Laravel app's static asset files - `public/` and the
2//! pre-build `resources/css`/`resources/js` source - into the converted
3//! project verbatim. Every converted Blade template already references
4//! these exact paths (`/images/...`, `/css/app.css`, `/favicon.ico`, ...)
5//! unchanged (an asset path is a plain string literal, never PHP/Blade
6//! syntax `blade::expr` would translate), and Larust serves `public/`
7//! directly at the URL root (`ServeDir` in `larust-core`'s `Application`)
8//! the same way Laravel's own webserver docroot does - so without this
9//! phase, every converted page renders unstyled and imageless even though
10//! its own HTML is otherwise correct.
11
12use anyhow::{Context, Result};
13use std::path::Path;
14
15#[derive(Debug, Default, PartialEq, Eq)]
16pub struct AssetSummary {
17    pub public_files: usize,
18    pub resource_files: usize,
19}
20
21impl AssetSummary {
22    pub fn total(&self) -> usize {
23        self.public_files + self.resource_files
24    }
25}
26
27/// `public/index.php` - Laravel's own PHP front controller - is the one
28/// top-level entry deliberately skipped; everything else under `public/`
29/// (images, already-built CSS/JS, favicons, `robots.txt`, vendored
30/// third-party assets, ...) is copied through unchanged. `resources/css`
31/// and `resources/js` (Laravel's own pre-build asset *source*, as opposed
32/// to `public/`'s already-built output) land at those *exact same*
33/// paths in the converted project - never rehomed under Larust's own
34/// `resources/assets/` scaffold convention, unlike a fresh `xr new` app
35/// with no existing frontend build config to preserve. This is load-
36/// bearing, not cosmetic: `vite.config.js` (copied verbatim by
37/// `xr::convert::copy_node_tooling` - see that function's own doc
38/// comment) still names `resources/css/app.min.css`/`resources/js/
39/// app.min.js` in its own `input` array, unchanged, and Vite's build
40/// manifest is keyed by those exact strings - the same strings
41/// `blade::scan`'s `@vite(...)` → `@code larust_support::vitex::tags(&
42/// [...])` translation hardcodes verbatim from the original template.
43/// Moving the source files anywhere else would silently break every one
44/// of those lookups. Either source directory being absent is not an
45/// error - plenty of real Laravel apps have no `resources/css`/
46/// `resources/js` at all (Blade-only, no frontend build step).
47pub fn convert(laravel_root: &Path, out_root: &Path) -> Result<AssetSummary> {
48    let mut summary = AssetSummary::default();
49
50    let source_public = laravel_root.join("public");
51    if source_public.is_dir() {
52        summary.public_files = copy_dir(&source_public, &out_root.join("public"), &["index.php"])?;
53    }
54
55    for name in ["css", "js"] {
56        let source = laravel_root.join("resources").join(name);
57        if source.is_dir() {
58            summary.resource_files +=
59                copy_dir(&source, &out_root.join("resources").join(name), &[])?;
60        }
61    }
62
63    Ok(summary)
64}
65
66/// Copies `package.json`, `vite.config.js`/`.ts`, and `postcss.config.js`
67/// verbatim, and `tailwind.config.js`/`.ts` with one deliberate text
68/// substitution - so `npm install && npm run dev`/`npm run build` work
69/// in the converted project exactly as they did in the original Laravel
70/// app, giving `@vitex`'s own dev/production detection (`public/hot`,
71/// `public/build/manifest.json` - see `larust_support::vitex`'s own doc
72/// comment) something real to find.
73///
74/// `vite.config.js` is copied **completely unchanged**, on purpose - its
75/// own `input` array is what Vite's build manifest keys come from, and
76/// those exact strings are also what `blade::scan`'s `@vite(...)` →
77/// `@vitex` translation hardcoded verbatim from the original template
78/// (see `convert`'s own doc comment above). Editing either side of that
79/// pairing without the other breaks every asset lookup silently.
80///
81/// `tailwind.config.js` is different: its `content` glob only tells
82/// Tailwind's own JIT engine which files to scan for class names, read
83/// by nothing else in this pipeline - but the source app's own glob
84/// (real source: `"./resources/**/*.blade.php"`) would now match zero
85/// files, since the converted templates live under `.blade.xr` and no
86/// `.blade.php` file exists in the new project at all. Every literal
87/// `.blade.php` gets rewritten to `.blade.xr` so Tailwind actually finds
88/// the real, converted templates.
89pub fn copy_node_tooling(laravel_root: &Path, out_root: &Path) -> Result<Vec<String>> {
90    let mut copied = Vec::new();
91    for name in [
92        "package.json",
93        "vite.config.js",
94        "vite.config.ts",
95        "postcss.config.js",
96    ] {
97        let source = laravel_root.join(name);
98        if source.is_file() {
99            std::fs::copy(&source, out_root.join(name))
100                .with_context(|| format!("copying {name}"))?;
101            copied.push(name.to_string());
102        }
103    }
104    for name in ["tailwind.config.js", "tailwind.config.ts"] {
105        let source = laravel_root.join(name);
106        if source.is_file() {
107            let content = std::fs::read_to_string(&source)
108                .with_context(|| format!("reading {}", source.display()))?;
109            std::fs::write(
110                out_root.join(name),
111                content.replace(".blade.php", ".blade.xr"),
112            )
113            .with_context(|| format!("writing {name}"))?;
114            copied.push(name.to_string());
115        }
116    }
117    Ok(copied)
118}
119
120/// Recursively copies `source`'s contents into `dest` (creating `dest` and
121/// any intermediate directories as needed), skipping any *top-level* entry
122/// (a direct child of `source`) whose file name matches one in
123/// `skip_top_level` - used for `public/index.php` only; nothing nested
124/// deeper is ever skipped (recursive calls always pass `&[]`). Returns the
125/// number of files actually copied. Symlinks are silently skipped - not
126/// observed in any real Laravel `public/` directory this has run against,
127/// and copying them safely (resolve vs. preserve) needs a real decision
128/// this doesn't attempt to guess.
129fn copy_dir(source: &Path, dest: &Path, skip_top_level: &[&str]) -> Result<usize> {
130    std::fs::create_dir_all(dest).with_context(|| format!("creating {}", dest.display()))?;
131    let mut count = 0;
132    for entry in
133        std::fs::read_dir(source).with_context(|| format!("reading {}", source.display()))?
134    {
135        let entry = entry?;
136        let file_name = entry.file_name();
137        if skip_top_level
138            .iter()
139            .any(|skip| file_name == std::ffi::OsStr::new(skip))
140        {
141            continue;
142        }
143        let source_path = entry.path();
144        let dest_path = dest.join(&file_name);
145        let file_type = entry.file_type()?;
146        if file_type.is_dir() {
147            count += copy_dir(&source_path, &dest_path, &[])?;
148        } else if file_type.is_file() {
149            std::fs::copy(&source_path, &dest_path).with_context(|| {
150                format!(
151                    "copying {} to {}",
152                    source_path.display(),
153                    dest_path.display()
154                )
155            })?;
156            count += 1;
157        }
158    }
159    Ok(count)
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn write(path: &Path, content: &str) {
167        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
168        std::fs::write(path, content).unwrap();
169    }
170
171    #[test]
172    fn copies_public_recursively_skipping_only_the_top_level_index_php() {
173        let dir = tempfile::tempdir().unwrap();
174        let laravel_root = dir.path().join("laravel");
175        let out_root = dir.path().join("out");
176        write(&laravel_root.join("public/index.php"), "<?php");
177        write(&laravel_root.join("public/favicon.ico"), "ico-bytes");
178        write(&laravel_root.join("public/images/logo.svg"), "<svg></svg>");
179
180        let summary = convert(&laravel_root, &out_root).unwrap();
181
182        assert_eq!(summary.public_files, 2);
183        assert!(!out_root.join("public/index.php").exists());
184        assert_eq!(
185            std::fs::read_to_string(out_root.join("public/favicon.ico")).unwrap(),
186            "ico-bytes"
187        );
188        assert_eq!(
189            std::fs::read_to_string(out_root.join("public/images/logo.svg")).unwrap(),
190            "<svg></svg>"
191        );
192    }
193
194    #[test]
195    fn copies_resources_css_and_js_to_the_same_paths_vite_config_expects() {
196        // Real source: `vite.config.js`'s own `input` array names
197        // `resources/css/app.min.css`/`resources/js/app.min.js` verbatim
198        // - copied here unchanged, not rehomed under `resources/assets/`,
199        // so `vite.config.js` (copied as-is) still finds its own source
200        // files and the build manifest keys still match what `@vitex`
201        // requests.
202        let dir = tempfile::tempdir().unwrap();
203        let laravel_root = dir.path().join("laravel");
204        let out_root = dir.path().join("out");
205        write(&laravel_root.join("resources/css/app.css"), "body{}");
206        write(&laravel_root.join("resources/js/app.js"), "console.log(1)");
207
208        let summary = convert(&laravel_root, &out_root).unwrap();
209
210        assert_eq!(summary.resource_files, 2);
211        assert_eq!(
212            std::fs::read_to_string(out_root.join("resources/css/app.css")).unwrap(),
213            "body{}"
214        );
215        assert_eq!(
216            std::fs::read_to_string(out_root.join("resources/js/app.js")).unwrap(),
217            "console.log(1)"
218        );
219    }
220
221    #[test]
222    fn a_missing_public_or_resources_css_js_directory_is_not_an_error() {
223        let dir = tempfile::tempdir().unwrap();
224        let laravel_root = dir.path().join("laravel");
225        std::fs::create_dir_all(&laravel_root).unwrap();
226        let out_root = dir.path().join("out");
227
228        let summary = convert(&laravel_root, &out_root).unwrap();
229
230        assert_eq!(summary, AssetSummary::default());
231    }
232
233    #[test]
234    fn copies_package_json_and_vite_config_completely_unchanged() {
235        let dir = tempfile::tempdir().unwrap();
236        let laravel_root = dir.path().join("laravel");
237        let out_root = dir.path().join("out");
238        std::fs::create_dir_all(&out_root).unwrap();
239        write(
240            &laravel_root.join("package.json"),
241            r#"{"scripts": {"dev": "vite"}}"#,
242        );
243        write(
244            &laravel_root.join("vite.config.js"),
245            "export default { plugins: [] };",
246        );
247        write(
248            &laravel_root.join("postcss.config.js"),
249            "export default { plugins: {} };",
250        );
251
252        let copied = copy_node_tooling(&laravel_root, &out_root).unwrap();
253
254        assert_eq!(
255            copied,
256            vec!["package.json", "vite.config.js", "postcss.config.js"]
257        );
258        assert_eq!(
259            std::fs::read_to_string(out_root.join("vite.config.js")).unwrap(),
260            "export default { plugins: [] };"
261        );
262    }
263
264    #[test]
265    fn tailwind_config_gets_its_blade_php_glob_rewritten_to_blade_xr() {
266        // Real source: `tailwind.config.js`'s own `content: ["./resources/
267        // **/*.blade.php", ...]` - the converted templates live under
268        // `.blade.xr`, so the original glob would match nothing.
269        let dir = tempfile::tempdir().unwrap();
270        let laravel_root = dir.path().join("laravel");
271        let out_root = dir.path().join("out");
272        std::fs::create_dir_all(&out_root).unwrap();
273        write(
274            &laravel_root.join("tailwind.config.js"),
275            "export default { content: [\"./resources/**/*.blade.php\", \"./resources/**/*.js\"] };",
276        );
277
278        let copied = copy_node_tooling(&laravel_root, &out_root).unwrap();
279
280        assert_eq!(copied, vec!["tailwind.config.js"]);
281        let content = std::fs::read_to_string(out_root.join("tailwind.config.js")).unwrap();
282        assert!(content.contains("./resources/**/*.blade.xr"));
283        assert!(!content.contains(".blade.php"));
284        assert!(content.contains("./resources/**/*.js"));
285    }
286
287    #[test]
288    fn missing_node_tooling_files_are_not_an_error() {
289        let dir = tempfile::tempdir().unwrap();
290        let laravel_root = dir.path().join("laravel");
291        std::fs::create_dir_all(&laravel_root).unwrap();
292        let out_root = dir.path().join("out");
293        std::fs::create_dir_all(&out_root).unwrap();
294
295        let copied = copy_node_tooling(&laravel_root, &out_root).unwrap();
296
297        assert!(copied.is_empty());
298    }
299
300    #[test]
301    fn a_nested_index_php_inside_public_is_not_skipped() {
302        // The skip list only applies to `public/index.php` at the true
303        // top level - `skip_top_level` is never propagated into recursive
304        // calls, so a same-named file nested deeper (e.g. a vendored
305        // third-party demo page) is treated as ordinary content.
306        let dir = tempfile::tempdir().unwrap();
307        let laravel_root = dir.path().join("laravel");
308        let out_root = dir.path().join("out");
309        write(
310            &laravel_root.join("public/vendor/widget/index.php"),
311            "<?php // demo",
312        );
313
314        let summary = convert(&laravel_root, &out_root).unwrap();
315
316        assert_eq!(summary.public_files, 1);
317        assert!(out_root.join("public/vendor/widget/index.php").exists());
318    }
319}