Skip to main content

larust_convert/
env.rs

1//! Source Laravel app's `.env` → the new Larust app's `.env`. A plain
2//! `KEY=VALUE` text format on both sides, so - unlike `config.rs`'s PHP
3//! source - this needs no real parser, just line-oriented splitting.
4//!
5//! **Nothing is silently dropped.** A key whose name (and meaning) is
6//! identical on both sides is copied straight through - this now includes
7//! `DB_CONNECTION`/`DB_HOST`/`DB_PORT`/`DB_DATABASE`/`DB_USERNAME`/
8//! `DB_PASSWORD`/`DB_CHARSET`, since Larust's own `config/database.rs`
9//! reads the identical Laravel env var names (see
10//! `resolve_database_connection`). A handful of keys still need real
11//! translation (`MAIL_MAILER` → `MAIL_DRIVER`) because Larust's own `.env`
12//! shape differs there - and even then, only when the source value is
13//! something Larust can actually use (see each translation's own doc
14//! comment for what happens otherwise). Everything else - `APP_KEY`,
15//! custom package config, feature flags, anything this module has never
16//! heard of - is carried over verbatim under its original key, matching
17//! this crate's existing "never silently drop, only ever silently invent"
18//! convention (`composer.rs`'s own doc comment states the same policy for
19//! packages).
20
21/// A `KEY -> value` pair this module recognized and translated to its
22/// Larust equivalent, plus everything it didn't (carried over as-is), plus
23/// human-readable notes for anything it recognized but couldn't safely
24/// translate - see [`convert`].
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct EnvConversion {
27    /// Larust key -> value, in `config_template::FIELDS`'s own order -
28    /// only for keys this function actually recognized. A caller rewriting
29    /// a scaffold-shaped `.env` can look each of these up by its own
30    /// `KEY=` line prefix and substitute the real value in place of the
31    /// scaffold's generic literal.
32    pub recognized: Vec<(String, String)>,
33    /// Original key -> value, for every other line in the source `.env` -
34    /// untouched, including Laravel-only keys with no Larust equivalent at
35    /// all (`APP_KEY`, custom package/service keys, feature flags).
36    pub carried_over: Vec<(String, String)>,
37    /// One entry per value this module recognized but declined to
38    /// translate because Larust can't actually use it (an unsupported
39    /// `MAIL_MAILER`/`DB_CONNECTION` value) - meant to be folded into
40    /// `ConversionReport.not_attempted` by the caller.
41    pub notes: Vec<String>,
42}
43
44/// Laravel env var name -> the identical Larust one, for every field where
45/// the two frameworks already agree (see `config_template::FIELDS`'s own
46/// `env_var` values) - no translation needed, just a straight copy.
47const DIRECT_PASSTHROUGH: &[&str] = &[
48    "APP_NAME",
49    "APP_ENV",
50    "APP_DEBUG",
51    "APP_URL",
52    "MAIL_HOST",
53    "MAIL_PORT",
54    "MAIL_USERNAME",
55    "MAIL_PASSWORD",
56    "MAIL_ENCRYPTION",
57    "MAIL_FROM_ADDRESS",
58];
59
60/// `Config::mail_driver`'s own actually-supported values (see its doc
61/// comment in `larust_core::config`) - a source `MAIL_MAILER`/`MAIL_DRIVER`
62/// outside this set can't be carried over as a working value, only noted.
63const SUPPORTED_MAIL_DRIVERS: &[&str] = &["log", "smtp"];
64
65/// Translates a source Laravel `.env` file's contents into what the new
66/// app's `.env` should carry - see [`EnvConversion`] for the three
67/// buckets. Pure and I/O-free (the caller reads/writes the actual files;
68/// see `larust-cli/src/convert.rs`'s `convert_env`), matching this crate's
69/// own `config::convert`/`config::render_body` shape.
70pub fn convert(source: &str) -> EnvConversion {
71    let mut result = EnvConversion::default();
72    let mut db_fields: DbFields = DbFields::default();
73    let mut seen = std::collections::HashSet::new();
74
75    for (key, value) in parse_lines(source) {
76        // dotenvy (and Laravel's own .env loader) both keep the first
77        // assignment when a key repeats - matched here so the translated
78        // file reflects what actually gets read at runtime, not whatever
79        // a later duplicate line happened to say.
80        if !seen.insert(key.clone()) {
81            continue;
82        }
83
84        if DIRECT_PASSTHROUGH.contains(&key.as_str()) {
85            warn_if_interpolated(&key, &value, &mut result.notes);
86            result.recognized.push((key, value));
87            continue;
88        }
89
90        match key.as_str() {
91            "MAIL_MAILER" | "MAIL_DRIVER" => {
92                if SUPPORTED_MAIL_DRIVERS.contains(&value.as_str()) {
93                    result.recognized.push(("MAIL_DRIVER".to_string(), value));
94                } else {
95                    result.notes.push(format!(
96                        "{key}={value} - Larust only supports log/smtp; mail settings were not carried over, review manually"
97                    ));
98                }
99            }
100            // Laravel's own scaffold convention (see `Config::mail_from_name`'s
101            // own doc comment) - `${APP_NAME}` here doesn't mean "carry this
102            // literal text over," it means "use the app name," which is
103            // exactly what leaving `MAIL_FROM_NAME` unset already does in
104            // Larust (`config_template`'s generated code falls back to
105            // `app_name` when it's empty). Carrying the literal `${APP_NAME}`
106            // text over would be actively wrong besides: `dotenvy` only
107            // resolves `${VAR}` against a variable *already seen earlier* in
108            // the same file (or the process environment), and this rewritten
109            // `.env` doesn't control that ordering relative to `APP_NAME`.
110            "MAIL_FROM_NAME" if is_app_name_interpolation(&value) => {}
111            "MAIL_FROM_NAME" => {
112                warn_if_interpolated(&key, &value, &mut result.notes);
113                result.recognized.push((key, value));
114            }
115            "DB_CONNECTION" => db_fields.connection = Some(value),
116            "DB_DATABASE" => db_fields.database = Some(value),
117            "DB_HOST" => db_fields.host = Some(value),
118            "DB_PORT" => db_fields.port = Some(value),
119            "DB_USERNAME" => db_fields.username = Some(value),
120            "DB_PASSWORD" => db_fields.password = Some(value),
121            "DB_CHARSET" => db_fields.charset = Some(value),
122            _ => {
123                warn_if_interpolated(&key, &value, &mut result.notes);
124                result.carried_over.push((key, value));
125            }
126        }
127    }
128
129    resolve_database_connection(db_fields, &mut result);
130    result
131}
132
133/// Every `DB_*` key held aside during the main scan above - all need to
134/// be seen together (and specifically need `DB_CONNECTION` resolved
135/// first) before deciding whether each one is a real, usable Larust
136/// setting (`recognized`) or dead config for a connection Larust can't
137/// use (`carried_over`) - see [`resolve_database_connection`].
138#[derive(Default)]
139struct DbFields {
140    connection: Option<String>,
141    database: Option<String>,
142    host: Option<String>,
143    port: Option<String>,
144    username: Option<String>,
145    password: Option<String>,
146    charset: Option<String>,
147}
148
149/// True for `${APP_NAME}`/`$APP_NAME` (with or without the surrounding
150/// quotes `parse_lines` already stripped) - Laravel's own stock
151/// `MAIL_FROM_NAME` scaffold default.
152fn is_app_name_interpolation(value: &str) -> bool {
153    value == "${APP_NAME}" || value == "$APP_NAME"
154}
155
156/// A value using `${VAR}` interpolation depends on `VAR` being defined
157/// *earlier* in the file it's read from (see `dotenvy::parse`'s own
158/// `apply_substitution`, which falls back to an empty string otherwise) -
159/// a real risk once carried into a differently-ordered rewritten `.env`.
160/// The one interpolation this module actually understands and handles
161/// correctly is `MAIL_FROM_NAME=${APP_NAME}` (see its own match arm,
162/// above); anything else gets carried over as asked (never silently
163/// dropped) but flagged so a human checks it resolves to what they expect.
164fn warn_if_interpolated(key: &str, value: &str, notes: &mut Vec<String>) {
165    if value.contains("${") {
166        notes.push(format!(
167            "{key}={value} - contains a \"${{...}}\" reference, which only resolves \
168             if that variable is defined earlier in the .env file; verify this by hand"
169        ));
170    }
171}
172
173/// Scans a source `.env` file for a bare `DB_CONNECTION` value, without
174/// running the rest of [`convert`]'s translation. Used by `larust-cli`'s
175/// `convert_migrations` step to pick `migrations::TargetDriver` - that step
176/// runs before `convert_env`'s own full pass over the `.env` file (it needs
177/// to, since `convert_models` reads `convert_migrations`'s already-written
178/// `.sql` output), so it can't simply reuse a [`EnvConversion`] this
179/// function's sibling hasn't produced yet. Returns `None` when the source
180/// `.env` has no `DB_CONNECTION` line at all - Laravel 11+'s own default in
181/// that case is `sqlite` (see `resolve_database_connection`'s identical
182/// treatment), which is also `TargetDriver`'s own fallback.
183pub fn db_connection(source: &str) -> Option<String> {
184    parse_lines(source)
185        .into_iter()
186        .find(|(key, _)| key == "DB_CONNECTION")
187        .map(|(_, value)| value)
188}
189
190/// Every connection Larust's own `config/database.rs` names -
191/// `larust_orm::config::Driver`'s full set, as Laravel spells them in
192/// `DB_CONNECTION`.
193const SUPPORTED_DB_CONNECTIONS: &[&str] = &["sqlite", "mysql", "mariadb", "pgsql"];
194
195/// `DB_CONNECTION`/`DB_DATABASE` need to be seen together before a
196/// decision can be made (an sqlite connection with no `DB_DATABASE` still
197/// needs the scaffold's own default path) - held aside during the main
198/// scan above, resolved here once both are known.
199///
200/// Unlike this function's own predecessor (`resolve_database_url`), there
201/// is no `DATABASE_URL` to synthesize any more - Larust's generated
202/// `config/database.rs` (see `larust_cli::config_template::
203/// render_database_config_rs`) reads `DB_CONNECTION`/`DB_HOST`/`DB_PORT`/
204/// `DB_DATABASE`/`DB_USERNAME`/`DB_PASSWORD`/`DB_CHARSET` directly and
205/// assembles the connection URL itself at runtime, the same env var names
206/// Laravel already uses - so this only needs to decide *whether* to
207/// recognize `DB_CONNECTION`/`DB_DATABASE` at all, not reshape them.
208fn resolve_database_connection(fields: DbFields, result: &mut EnvConversion) {
209    // Recent Laravel (11+) defaults to sqlite with no DB_CONNECTION line
210    // at all - treat "unset" the same as "sqlite" rather than silently
211    // dropping a real DB_DATABASE path.
212    let connection = fields
213        .connection
214        .clone()
215        .unwrap_or_else(|| "sqlite".to_string());
216
217    let every_field = [
218        ("DB_CONNECTION", fields.connection),
219        ("DB_DATABASE", fields.database),
220        ("DB_HOST", fields.host),
221        ("DB_PORT", fields.port),
222        ("DB_USERNAME", fields.username),
223        ("DB_PASSWORD", fields.password),
224        ("DB_CHARSET", fields.charset),
225    ];
226
227    if !SUPPORTED_DB_CONNECTIONS.contains(&connection.as_str()) {
228        // `sqlsrv` is a real, named connection in Larust's own generated
229        // config (see `larust_orm::config::Driver::Sqlsrv`), but still not
230        // connectable through this framework's ORM at all - no `sqlx`
231        // driver exists for it (see `larust-mssql` for the separate,
232        // CRUD-only path that does work). Anything else is genuinely
233        // unrecognized. Either way, every `DB_*` field present is still
234        // carried over verbatim below (never silently dropped, matching
235        // every other unrecognized key), just flagged as dead config.
236        let reason = if connection == "sqlsrv" {
237            "Larust's ORM has no SQL Server driver - see the larust-mssql crate for a \
238             separate, CRUD-only integration path; database credentials were carried over \
239             verbatim but won't be read by config/database.rs"
240        } else {
241            "not a connection Larust recognizes; database credentials were carried over \
242             verbatim but won't be read by config/database.rs"
243        };
244        result
245            .notes
246            .push(format!("DB_CONNECTION={connection} - {reason}"));
247        for (key, value) in every_field {
248            if let Some(value) = value {
249                warn_if_interpolated(key, &value, &mut result.notes);
250                result.carried_over.push((key.to_string(), value));
251            }
252        }
253        return;
254    }
255
256    for (key, value) in every_field {
257        if let Some(value) = value {
258            warn_if_interpolated(key, &value, &mut result.notes);
259            result.recognized.push((key.to_string(), value));
260        }
261    }
262}
263
264/// Merges a [`EnvConversion`] into the scaffold's own `.env` template text
265/// (the same one `scaffold::new_app_from_workspace` already wrote to
266/// `out_root/.env` before conversion runs), producing the new app's real
267/// `.env`. Pure text transform - the caller (`larust-cli`'s `convert_env`)
268/// owns reading/writing the actual files.
269///
270/// The scaffold template has three kinds of lines relevant here:
271/// - a **live** `KEY=value` line (`APP_ENV`, `DB_CONNECTION`, ...) - its
272///   value gets replaced if `conversion.recognized` has that key,
273///   otherwise it's left exactly as scaffolded;
274/// - a **commented-out** `# KEY=value` line (`# MAIL_HOST=...`, since the
275///   scaffold leaves optional mail fields off by default) - uncommented
276///   and given the real value if recognized, otherwise left as a comment;
277/// - **no line at all** for a key the scaffold never mentions (only
278///   `APP_NAME` today - the scaffold relies entirely on `config/app.rs`'s
279///   own generated default for it) - appended after the scan, so a real
280///   value is never silently lost just because the template had nowhere
281///   to put it.
282///
283/// Every `carried_over` entry (unrecognized keys - Laravel-only or custom)
284/// is appended verbatim in one clearly labeled section at the end, never
285/// interleaved with the framework's own keys.
286pub fn rewrite(template: &str, conversion: &EnvConversion) -> String {
287    let mut applied: std::collections::HashSet<&str> = std::collections::HashSet::new();
288    let mut out = String::with_capacity(template.len());
289
290    for line in template.lines() {
291        let trimmed = line.trim_start();
292        let candidate = trimmed.strip_prefix('#').map_or(trimmed, str::trim_start);
293        let key = candidate
294            .split_once('=')
295            .map(|(k, _)| k.trim())
296            .filter(|k| is_env_key_shape(k));
297
298        let replacement = key.and_then(|k| {
299            conversion
300                .recognized
301                .iter()
302                .find(|(rk, _)| rk == k)
303                .map(|(rk, v)| (rk.as_str(), v.as_str()))
304        });
305
306        match replacement {
307            Some((k, v)) => {
308                applied.insert(k);
309                out.push_str(k);
310                out.push('=');
311                out.push_str(v);
312                out.push('\n');
313            }
314            None => {
315                out.push_str(line);
316                out.push('\n');
317            }
318        }
319    }
320
321    let missing: Vec<&(String, String)> = conversion
322        .recognized
323        .iter()
324        .filter(|(k, _)| !applied.contains(k.as_str()))
325        .collect();
326    if !missing.is_empty() {
327        for (k, v) in &missing {
328            out.push_str(k);
329            out.push('=');
330            out.push_str(v);
331            out.push('\n');
332        }
333    }
334
335    if !conversion.carried_over.is_empty() {
336        out.push_str("\n# --- Copied from the original Laravel .env (not read by Larust yet, kept for reference) ---\n");
337        for (k, v) in &conversion.carried_over {
338            out.push_str(k);
339            out.push('=');
340            out.push_str(v);
341            out.push('\n');
342        }
343    }
344
345    out
346}
347
348/// Guards `rewrite`'s per-line key extraction against a prose comment that
349/// happens to contain a literal `=` (none of the scaffold's own comments
350/// do today, but this keeps the line-scan honest rather than relying on
351/// that never changing) - a real env var key is `UPPER_SNAKE_CASE`.
352fn is_env_key_shape(key: &str) -> bool {
353    !key.is_empty()
354        && key
355            .bytes()
356            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
357}
358
359/// Splits `source` into `(key, value)` pairs - blank lines and `#`-comment
360/// lines skipped, one layer of surrounding `"`/`'` quotes stripped from the
361/// value (Laravel's own `.env` convention; `dotenvy` reads the same
362/// shape, so this mirrors what actually lands in `std::env` at runtime).
363fn parse_lines(source: &str) -> Vec<(String, String)> {
364    source
365        .lines()
366        .filter_map(|line| {
367            let line = line.trim();
368            if line.is_empty() || line.starts_with('#') {
369                return None;
370            }
371            let (key, value) = line.split_once('=')?;
372            Some((key.trim().to_string(), unquote(value.trim())))
373        })
374        .collect()
375}
376
377fn unquote(value: &str) -> String {
378    let bytes = value.as_bytes();
379    if bytes.len() >= 2
380        && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
381            || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''))
382    {
383        value[1..value.len() - 1].to_string()
384    } else {
385        value.to_string()
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    fn recognized<'a>(conversion: &'a EnvConversion, key: &str) -> Option<&'a str> {
394        conversion
395            .recognized
396            .iter()
397            .find(|(k, _)| k == key)
398            .map(|(_, v)| v.as_str())
399    }
400
401    #[test]
402    fn direct_passthrough_keys_carry_their_value_unchanged() {
403        let conversion = convert("APP_NAME=MyApp\nAPP_ENV=production\n");
404        assert_eq!(recognized(&conversion, "APP_NAME"), Some("MyApp"));
405        assert_eq!(recognized(&conversion, "APP_ENV"), Some("production"));
406    }
407
408    #[test]
409    fn quoted_values_are_unquoted() {
410        let conversion = convert(r#"APP_NAME="My App""#);
411        assert_eq!(recognized(&conversion, "APP_NAME"), Some("My App"));
412    }
413
414    #[test]
415    fn comments_and_blank_lines_are_skipped() {
416        let conversion = convert("# a comment\n\nAPP_NAME=MyApp\n");
417        assert_eq!(recognized(&conversion, "APP_NAME"), Some("MyApp"));
418        assert!(conversion.carried_over.is_empty());
419    }
420
421    #[test]
422    fn a_repeated_key_keeps_its_first_value() {
423        let conversion = convert("APP_NAME=First\nAPP_NAME=Second\n");
424        assert_eq!(recognized(&conversion, "APP_NAME"), Some("First"));
425    }
426
427    #[test]
428    fn mail_mailer_with_a_supported_driver_translates_to_mail_driver() {
429        let conversion = convert("MAIL_MAILER=log\n");
430        assert_eq!(recognized(&conversion, "MAIL_DRIVER"), Some("log"));
431        assert!(conversion.notes.is_empty());
432    }
433
434    #[test]
435    fn mail_mailer_with_an_unsupported_driver_is_noted_not_translated() {
436        let conversion = convert("MAIL_MAILER=ses\n");
437        assert_eq!(recognized(&conversion, "MAIL_DRIVER"), None);
438        assert_eq!(conversion.notes.len(), 1);
439        assert!(conversion.notes[0].contains("MAIL_MAILER=ses"));
440    }
441
442    #[test]
443    fn db_connection_sqlite_with_a_custom_path_is_recognized_verbatim() {
444        let conversion = convert("DB_CONNECTION=sqlite\nDB_DATABASE=database/custom.sqlite\n");
445        assert_eq!(recognized(&conversion, "DB_CONNECTION"), Some("sqlite"));
446        assert_eq!(
447            recognized(&conversion, "DB_DATABASE"),
448            Some("database/custom.sqlite")
449        );
450    }
451
452    #[test]
453    fn db_connection_sqlite_with_no_database_recognizes_only_the_connection() {
454        // No `DB_DATABASE` line - nothing to recognize for it;
455        // `config/database.rs`'s own `env_or` default applies at runtime.
456        let conversion = convert("DB_CONNECTION=sqlite\n");
457        assert_eq!(recognized(&conversion, "DB_CONNECTION"), Some("sqlite"));
458        assert_eq!(recognized(&conversion, "DB_DATABASE"), None);
459    }
460
461    #[test]
462    fn no_db_connection_line_at_all_is_treated_as_sqlite_and_recognizes_the_database_path() {
463        let conversion = convert("DB_DATABASE=database/database.sqlite\n");
464        // DB_CONNECTION itself was never present in the source file, so
465        // there's nothing to recognize *for that key* - the scaffold's own
466        // `DB_CONNECTION=sqlite` default line already says the same thing.
467        assert_eq!(recognized(&conversion, "DB_CONNECTION"), None);
468        assert_eq!(
469            recognized(&conversion, "DB_DATABASE"),
470            Some("database/database.sqlite")
471        );
472        assert!(conversion.notes.is_empty());
473    }
474
475    #[test]
476    fn db_connection_helper_reads_the_bare_value_without_full_conversion() {
477        assert_eq!(
478            db_connection("DB_CONNECTION=pgsql\nDB_DATABASE=myapp\n"),
479            Some("pgsql".to_string())
480        );
481        assert_eq!(db_connection("DB_DATABASE=myapp\n"), None);
482    }
483
484    #[test]
485    fn db_connection_mysql_is_recognized_and_passed_through() {
486        let conversion = convert(
487            "DB_CONNECTION=mysql\nDB_DATABASE=myapp\nDB_USERNAME=root\nDB_PASSWORD=secret\n",
488        );
489        assert_eq!(recognized(&conversion, "DB_CONNECTION"), Some("mysql"));
490        assert_eq!(recognized(&conversion, "DB_DATABASE"), Some("myapp"));
491        assert_eq!(recognized(&conversion, "DB_USERNAME"), Some("root"));
492        assert_eq!(recognized(&conversion, "DB_PASSWORD"), Some("secret"));
493        assert!(conversion.notes.is_empty());
494        assert!(conversion.carried_over.is_empty());
495    }
496
497    #[test]
498    fn db_connection_mariadb_and_pgsql_are_also_recognized() {
499        for driver in ["mariadb", "pgsql"] {
500            let conversion = convert(&format!("DB_CONNECTION={driver}\n"));
501            assert_eq!(recognized(&conversion, "DB_CONNECTION"), Some(driver));
502            assert!(conversion.notes.is_empty());
503        }
504    }
505
506    #[test]
507    fn db_connection_sqlsrv_is_noted_since_larusts_orm_still_cant_connect_to_it() {
508        let conversion = convert("DB_CONNECTION=sqlsrv\nDB_DATABASE=myapp\n");
509        assert_eq!(recognized(&conversion, "DB_CONNECTION"), None);
510        assert_eq!(conversion.notes.len(), 1);
511        assert!(conversion.notes[0].contains("DB_CONNECTION=sqlsrv"));
512        assert!(conversion.notes[0].contains("larust-mssql"));
513    }
514
515    #[test]
516    fn db_connection_with_an_unrecognized_driver_is_noted_not_translated() {
517        let conversion = convert("DB_CONNECTION=oracle\nDB_USERNAME=root\n");
518        assert_eq!(recognized(&conversion, "DB_CONNECTION"), None);
519        assert_eq!(conversion.notes.len(), 1);
520        assert!(conversion.notes[0].contains("DB_CONNECTION=oracle"));
521        assert!(conversion
522            .carried_over
523            .contains(&("DB_USERNAME".to_string(), "root".to_string())));
524    }
525
526    #[test]
527    fn mail_from_name_matching_laravels_app_name_interpolation_is_dropped_not_carried_literally() {
528        // Larust's own equivalent of "${APP_NAME}" is leaving MAIL_FROM_NAME
529        // unset entirely (config_template's generated code falls back to
530        // app_name when it's empty) - carrying the literal text over would
531        // be wrong, not just unnecessary (dotenvy only resolves ${VAR}
532        // against something already defined earlier in the same file).
533        let conversion = convert(r#"MAIL_FROM_NAME="${APP_NAME}""#);
534        assert_eq!(recognized(&conversion, "MAIL_FROM_NAME"), None);
535        assert!(conversion.carried_over.is_empty());
536        assert!(conversion.notes.is_empty());
537    }
538
539    #[test]
540    fn a_real_custom_mail_from_name_is_carried_over_normally() {
541        let conversion = convert("MAIL_FROM_NAME=Acme Support\n");
542        assert_eq!(
543            recognized(&conversion, "MAIL_FROM_NAME"),
544            Some("Acme Support")
545        );
546    }
547
548    #[test]
549    fn an_unrelated_dollar_brace_interpolation_is_carried_over_and_flagged() {
550        let conversion = convert("CACHE_PREFIX=${APP_NAME}_cache\n");
551        assert_eq!(
552            conversion
553                .carried_over
554                .iter()
555                .find(|(k, _)| k == "CACHE_PREFIX")
556                .map(|(_, v)| v.as_str()),
557            Some("${APP_NAME}_cache")
558        );
559        assert_eq!(conversion.notes.len(), 1);
560        assert!(conversion.notes[0].contains("CACHE_PREFIX"));
561    }
562
563    #[test]
564    fn an_unrecognized_custom_key_is_carried_over_verbatim() {
565        let conversion = convert("STRIPE_KEY=sk_test_abc123\n");
566        assert!(conversion
567            .carried_over
568            .contains(&("STRIPE_KEY".to_string(), "sk_test_abc123".to_string())));
569    }
570
571    /// A trimmed but representative slice of `scaffold.rs`'s real `.env`
572    /// template - a live key (`APP_ENV`), a live key with an explanatory
573    /// comment above it (`APP_URL`), and commented-out optional keys
574    /// (`# MAIL_HOST=...`, `# DB_HOST=...`) - covering all three shapes
575    /// `rewrite` handles.
576    const TEMPLATE: &str = "APP_ENV=local\n\
577         DB_CONNECTION=sqlite\n\
578         # DB_HOST=127.0.0.1\n\
579         # DB_DATABASE=larust\n\
580         # Base URL used by url()/asset() to build absolute URLs from a relative path.\n\
581         APP_URL=http://localhost\n\
582         # Set this to \"smtp\" and fill in the fields below to send for real.\n\
583         MAIL_DRIVER=log\n\
584         # MAIL_HOST=smtp.example.com\n\
585         # MAIL_PORT=587\n";
586
587    #[test]
588    fn rewrite_replaces_a_live_keys_value_in_place() {
589        let conversion = convert("APP_ENV=production\n");
590        let result = rewrite(TEMPLATE, &conversion);
591        assert!(result.contains("APP_ENV=production"));
592        assert!(!result.contains("APP_ENV=local"));
593    }
594
595    #[test]
596    fn rewrite_leaves_a_live_key_untouched_when_nothing_recognized_it() {
597        let conversion = convert("STRIPE_KEY=sk_test\n");
598        let result = rewrite(TEMPLATE, &conversion);
599        assert!(result.contains("APP_ENV=local"));
600    }
601
602    #[test]
603    fn rewrite_uncomments_an_optional_key_and_fills_in_the_real_value() {
604        let conversion = convert("MAIL_MAILER=smtp\nMAIL_HOST=smtp.mycompany.test\n");
605        let result = rewrite(TEMPLATE, &conversion);
606        assert!(result.contains("MAIL_HOST=smtp.mycompany.test"));
607        assert!(!result.contains("# MAIL_HOST"));
608    }
609
610    #[test]
611    fn rewrite_leaves_an_unrecognized_optional_key_commented_out() {
612        let conversion = convert("APP_ENV=production\n");
613        let result = rewrite(TEMPLATE, &conversion);
614        assert!(result.contains("# MAIL_HOST=smtp.example.com"));
615        assert!(result.contains("# MAIL_PORT=587"));
616    }
617
618    #[test]
619    fn rewrite_appends_a_recognized_key_the_template_never_mentions() {
620        // APP_NAME has no line at all in the real scaffold template.
621        let conversion = convert("APP_NAME=MyRealApp\n");
622        let result = rewrite(TEMPLATE, &conversion);
623        assert!(result.contains("APP_NAME=MyRealApp"));
624    }
625
626    #[test]
627    fn rewrite_appends_carried_over_keys_in_a_labeled_section() {
628        let conversion = convert("STRIPE_KEY=sk_test_abc123\n");
629        let result = rewrite(TEMPLATE, &conversion);
630        assert!(result.contains("Copied from the original Laravel .env"));
631        assert!(result.contains("STRIPE_KEY=sk_test_abc123"));
632    }
633
634    #[test]
635    fn rewrite_omits_the_carried_over_section_when_nothing_was_unrecognized() {
636        let conversion = convert("APP_ENV=production\n");
637        let result = rewrite(TEMPLATE, &conversion);
638        assert!(!result.contains("Copied from the original Laravel .env"));
639    }
640
641    #[test]
642    fn rewrite_never_matches_a_prose_comment_as_a_key() {
643        let conversion = convert("APP_ENV=production\n");
644        let result = rewrite(TEMPLATE, &conversion);
645        assert!(result.contains(
646            "# Base URL used by url()/asset() to build absolute URLs from a relative path."
647        ));
648    }
649}