Skip to main content

mortise_core/app/
mod.rs

1//! Reading one app folder into a snapshot.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5use std::time::UNIX_EPOCH;
6
7use serde::{Deserialize, Serialize};
8
9use crate::boundary::links::{self, Cycle, Link, ModuleSource};
10use crate::boundary::rules::{self, CoverageSettings, Rules, RulesSource};
11use crate::findings::{self, DEFAULT_COVERAGE_LIMIT, Findings, Subject};
12use crate::modules::clover::{self, Coverage};
13use crate::modules::code::propose_codes;
14use crate::modules::composer::{Lock, Version};
15use crate::modules::git::{self, Git};
16use crate::modules::kind::Kinds;
17use crate::modules::layout::Layout;
18use crate::modules::module::{Module, ModuleState, ReadCache, find_modules};
19use crate::package::PackageData;
20
21#[cfg(feature = "watch")]
22pub(crate) mod live;
23
24const LARAVEL: &str = "laravel/framework";
25const PACKAGE: &str = "nwidart/laravel-modules";
26const ACTUATOR: &str = "nwidart/laravel-actuator";
27
28/// The coverage report an app's coverage figures come from.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct CoverageReport {
31    /// The clover file. Absolute.
32    pub path: PathBuf,
33    /// When the file was written, in seconds since 1970.
34    pub written: Option<i64>,
35}
36
37/// Everything Mortise knows about an app from one read of its folder.
38///
39/// A snapshot is never changed. A later read gives a new one.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct AppSnapshot {
42    /// The app folder: the one that holds `artisan`. Absolute.
43    pub root: PathBuf,
44    /// The name of the app folder.
45    pub name: String,
46    /// The version of `laravel/framework`. Absent when the lock file does not list it.
47    pub laravel: Option<Version>,
48    /// The version of `nwidart/laravel-modules`.
49    pub package: Version,
50    /// The version of `nwidart/laravel-actuator`, when the app has it.
51    pub actuator: Option<Version>,
52    /// `APP_URL` from `.env`, to propose the base URL of an environment.
53    pub app_url: Option<String>,
54    /// `APP_ENV` from `.env`. It tells Mortise to ask before a command in production.
55    /// `APP_URL` and `APP_ENV` are the only lines Mortise reads from that file.
56    pub app_env: Option<String>,
57    pub layout: Layout,
58    /// The modules, sorted by name.
59    pub modules: Vec<Module>,
60    /// The coverage report, when one was found.
61    pub coverage_report: Option<CoverageReport>,
62    pub git: Git,
63    /// Which module uses which, by the name of the module that uses and then of the
64    /// one that is used.
65    pub links: Vec<Link>,
66    /// The groups of modules that are on and use each other.
67    pub cycles: Vec<Cycle>,
68    /// The boundary rules the links were checked against.
69    pub rules: Rules,
70    pub rules_source: RulesSource,
71    /// Why the `coverage` object of `mortise.json` is ignored, when it cannot be read.
72    /// The parser's message. Coverage then comes from the settings.
73    pub coverage_ignored: Option<String>,
74    /// What the rules and the checks on files found.
75    pub findings: Findings,
76    /// A module covered less than this many per cent is a warning.
77    pub coverage_limit: u8,
78    /// What the package said in the reads the user started, from [`ReadOptions::package`].
79    /// The read fills in the tables of each module's ran migrations.
80    pub package_data: PackageData,
81}
82
83impl AppSnapshot {
84    /// How many modules are turned on.
85    pub fn modules_on(&self) -> usize {
86        self.modules
87            .iter()
88            .filter(|module| module.state == ModuleState::On)
89            .count()
90    }
91
92    /// Files in all modules together.
93    pub fn files(&self) -> u64 {
94        self.modules.iter().map(|module| module.files).sum()
95    }
96
97    /// Lines of PHP in all modules together.
98    pub fn lines(&self) -> u64 {
99        self.modules.iter().map(|module| module.lines).sum()
100    }
101
102    /// Tests in all modules together.
103    pub fn tests(&self) -> u32 {
104        self.modules.iter().map(|module| module.tests).sum()
105    }
106
107    /// The coverage of all modules together. `None` when no module has a figure.
108    pub fn coverage(&self) -> Option<Coverage> {
109        let mut total: Option<Coverage> = None;
110        for coverage in self.modules.iter().filter_map(|module| module.coverage) {
111            total.get_or_insert_default().add(coverage);
112        }
113        total
114    }
115
116    /// The link from one module to another, if the first uses the second.
117    pub fn link(&self, from: &str, to: &str) -> Option<&Link> {
118        self.links
119            .iter()
120            .find(|link| link.from == from && link.to == to)
121    }
122
123    /// The module of the circle of `module` that `module` uses directly: the link a
124    /// circle finding opens on. `None` when `module` is in no circle.
125    pub fn circle_neighbour(&self, module: &str) -> Option<&str> {
126        crate::boundary::links::circle_neighbour(&self.links, module)
127    }
128
129    /// The links of modules that `name` uses.
130    pub fn uses<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Link> {
131        self.links.iter().filter(move |link| link.from == name)
132    }
133
134    /// The links of modules that use `name`.
135    pub fn used_by<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Link> {
136        self.links.iter().filter(move |link| link.to == name)
137    }
138
139    /// The links that break a rule.
140    pub fn problem_links(&self) -> impl Iterator<Item = &Link> {
141        self.links
142            .iter()
143            .filter(|link| link.is_problem(&self.rules))
144    }
145
146    /// The modules that carry a circle `name` is in without carrying it, by name. Empty
147    /// while "No circular use" is off, because then no circle is a finding.
148    pub fn circles_counted_elsewhere<'a>(&'a self, name: &str) -> Vec<&'a str> {
149        let mut carriers: Vec<&str> = Vec::new();
150        if self.rules.no_circular_use {
151            for cycle in &self.cycles {
152                let member = cycle.modules.iter().any(|module| module == name);
153                if member && cycle.carrier != name && !carriers.contains(&cycle.carrier.as_str()) {
154                    carriers.push(&cycle.carrier);
155                }
156            }
157        }
158        carriers.sort_unstable();
159        carriers
160    }
161
162    /// The module with this name.
163    pub fn module(&self, name: &str) -> Option<&Module> {
164        self.modules.iter().find(|module| module.name == name)
165    }
166
167    /// The code of every module, by module name. Store it, and pass it to the next read.
168    pub fn codes(&self) -> BTreeMap<String, String> {
169        self.modules
170            .iter()
171            .map(|module| (module.name.clone(), module.code.clone()))
172            .collect()
173    }
174
175    /// The modules folder as the user writes it: relative to the app folder when it
176    /// is inside it, with `/` between the parts.
177    pub fn modules_dir_shown(&self) -> String {
178        self.path_shown(&self.layout.modules_dir)
179    }
180
181    /// A path as the user writes it: relative to the app folder when it is inside it.
182    pub fn path_shown(&self, path: &Path) -> String {
183        shown(&self.root, path)
184    }
185}
186
187/// `path` relative to `root` when it is inside it, else whole. Parts are joined with `/`
188/// on every platform, so a line opens in an editor and in a CI log on Windows too.
189/// `.` and `..` are resolved by name first, so `Modules/../../shared` is outside.
190pub(crate) fn shown(root: &Path, path: &Path) -> String {
191    use std::path::{Component, Prefix};
192    let path = lexical(path);
193    let rest = path.strip_prefix(lexical(root)).unwrap_or(&path);
194    let mut start = String::new();
195    let mut parts: Vec<String> = Vec::new();
196    for component in rest.components() {
197        match component {
198            // `C:` or `\\server\share` on Windows. A verbatim `\\?\D:` or `\\?\UNC\server\share`
199            // names the same folder as `D:` or `\\server\share`, and only those take `/`.
200            Component::Prefix(prefix) => match prefix.kind() {
201                Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => {
202                    start = format!("{}:", char::from(drive));
203                }
204                Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
205                    start = format!("//{}/{}", server.to_string_lossy(), share.to_string_lossy());
206                }
207                // Any other verbatim path or a device keeps its spelling: it needs `\`.
208                Prefix::Verbatim(_) | Prefix::DeviceNS(_) => {
209                    return path.to_string_lossy().into_owned();
210                }
211            },
212            Component::RootDir => start.push('/'),
213            other => parts.push(other.as_os_str().to_string_lossy().into_owned()),
214        }
215    }
216    start + &parts.join("/")
217}
218
219/// `path` with `.` and `..` resolved by name, without asking the file system.
220/// A `..` at the root stays at the root; a `..` at the start of a relative path stays.
221pub(crate) fn lexical(path: &Path) -> PathBuf {
222    use std::path::Component;
223    let mut parts: Vec<Component<'_>> = Vec::new();
224    for component in path.components() {
225        match component {
226            Component::CurDir => {}
227            Component::ParentDir => match parts.last() {
228                Some(Component::Normal(_)) => {
229                    parts.pop();
230                }
231                Some(Component::RootDir | Component::Prefix(_)) => {}
232                _ => parts.push(component),
233            },
234            other => parts.push(other),
235        }
236    }
237    parts.iter().collect()
238}
239
240/// Why a folder could not be read as an app.
241#[derive(Debug, thiserror::Error)]
242pub enum ReadError {
243    /// The folder has no `artisan` file and no `composer.json` that requires `laravel/framework`.
244    #[error("{} is not a Laravel app", root.display())]
245    NotLaravel { root: PathBuf },
246    /// The folder has no `composer.lock`, so no version can be read.
247    #[error("{} has no composer.lock", root.display())]
248    NoLock { root: PathBuf },
249    /// `composer.lock` has no entry for `nwidart/laravel-modules`.
250    #[error("{} does not use nwidart/laravel-modules", root.display())]
251    NoPackage { root: PathBuf },
252    /// `composer.lock` is not valid JSON.
253    #[error("{} is not valid JSON: {message}", path.display())]
254    InvalidLock { path: PathBuf, message: String },
255    /// The coverage report given for the read, such as with `mortise check --coverage`,
256    /// cannot be read or is no clover report.
257    #[error("cannot read the coverage report {}: {message}", path.display())]
258    CoverageReport { path: PathBuf, message: String },
259    #[error("cannot read {}: {source}", path.display())]
260    Io {
261        path: PathBuf,
262        source: std::io::Error,
263    },
264}
265
266/// `APP_ENV` from the `.env` file of the app in `root`, read now. A confirmation
267/// checks it again just before a destructive command starts.
268pub fn read_app_env(root: &Path) -> Option<String> {
269    read_env(root).1
270}
271
272/// `APP_URL` and `APP_ENV` from the `.env` file of the app, in one read.
273/// No other line is looked at.
274fn read_env(root: &Path) -> (Option<String>, Option<String>) {
275    match std::fs::read_to_string(root.join(".env")) {
276        Ok(env) => (env_value(&env, "APP_URL"), env_value(&env, "APP_ENV")),
277        Err(_) => (None, None),
278    }
279}
280
281/// The value of one name in the text of a `.env` file. As in dotenv, a later line
282/// of the same name replaces an earlier one.
283fn env_value(env: &str, name: &str) -> Option<String> {
284    let value = env.lines().rev().find_map(|line| {
285        let line = line.trim_start();
286        let line = line.strip_prefix("export ").unwrap_or(line);
287        line.strip_prefix(name)?.trim_start().strip_prefix('=')
288    })?;
289    let value = value.trim();
290    let value = match value.chars().next() {
291        // A quoted value ends at the closing quote.
292        Some(quote @ ('"' | '\'')) => value[1..].split(quote).next().unwrap_or_default(),
293        // A plain value ends where a comment starts.
294        _ => value.split(" #").next().unwrap_or_default().trim_end(),
295    };
296    (!value.is_empty()).then(|| value.to_owned())
297}
298
299/// Reads the app in `root`. Reads only: nothing in the folder is changed and nothing is run.
300pub fn read_app(root: &Path) -> Result<AppSnapshot, ReadError> {
301    read_app_with(root, &BTreeMap::new())
302}
303
304/// Reads the app in `root`, keeping the codes its modules already have.
305///
306/// `codes` maps a module name to its code. A module that is not in it gets a new
307/// code that differs from all of them.
308pub fn read_app_with(
309    root: &Path,
310    codes: &BTreeMap<String, String>,
311) -> Result<AppSnapshot, ReadError> {
312    read_app_cached(
313        root,
314        codes,
315        &ReadOptions::default(),
316        &mut ReadCache::default(),
317    )
318}
319
320/// What the user set for an app in Mortise, as far as reading it is concerned.
321///
322/// The coverage limit and report come, first to last, from `coverage_given`, from the
323/// `coverage` object of `mortise.json`, and from `coverage_limit` and `coverage_report`.
324#[derive(Debug, Clone, PartialEq, Eq)]
325pub struct ReadOptions {
326    /// A module covered less than this many per cent is a warning.
327    pub coverage_limit: u8,
328    /// The clover report, relative to the app folder or absolute. `None` looks in
329    /// `phpunit.xml` and the usual places.
330    pub coverage_report: Option<PathBuf>,
331    /// Coverage given for this read only, such as the flags of `mortise check`. A value
332    /// that is set wins over `mortise.json`.
333    pub coverage_given: CoverageSettings,
334    /// What the package said in the reads the user started. Kept in memory only.
335    pub package: PackageData,
336}
337
338impl Default for ReadOptions {
339    fn default() -> Self {
340        Self {
341            coverage_limit: DEFAULT_COVERAGE_LIMIT,
342            coverage_report: None,
343            coverage_given: CoverageSettings::default(),
344            package: PackageData::default(),
345        }
346    }
347}
348
349/// Reads the app in `root`. Files that did not change since they were put in
350/// `cache` are not read again.
351pub fn read_app_cached(
352    root: &Path,
353    codes: &BTreeMap<String, String>,
354    options: &ReadOptions,
355    cache: &mut ReadCache,
356) -> Result<AppSnapshot, ReadError> {
357    let root = std::path::absolute(root).map_err(|source| ReadError::Io {
358        path: root.to_owned(),
359        source,
360    })?;
361
362    if !root.join("artisan").is_file() && !requires_laravel(&root) {
363        return Err(ReadError::NotLaravel { root });
364    }
365
366    let lock_path = root.join("composer.lock");
367    let lock = match std::fs::read(&lock_path) {
368        Ok(json) => Lock::parse(&json).map_err(|error| ReadError::InvalidLock {
369            path: lock_path,
370            message: error.to_string(),
371        })?,
372        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
373            return Err(ReadError::NoLock { root });
374        }
375        Err(source) => {
376            return Err(ReadError::Io {
377                path: lock_path,
378                source,
379            });
380        }
381    };
382    let Some(package) = lock.version(PACKAGE) else {
383        return Err(ReadError::NoPackage { root });
384    };
385
386    let (layout, config) = Layout::read(&root);
387    let kinds = Kinds::new(config.as_ref(), &layout.app_folder);
388    let (found, status_entries) = find_modules(&layout, &kinds, cache);
389
390    // A code is kept once given. Only modules without one get a proposal.
391    let taken: BTreeSet<String> = codes.values().cloned().collect();
392    let new_names = found
393        .iter()
394        .map(|module| module.name.as_str())
395        .filter(|name| !codes.contains_key(*name));
396    let mut proposed = propose_codes(new_names, &taken).into_iter();
397    let codes: Vec<String> = found
398        .iter()
399        .map(|module| match codes.get(&module.name) {
400            Some(code) => code.clone(),
401            None => proposed.next().unwrap_or_default(),
402        })
403        .collect();
404
405    // A module's folder as git and the coverage report name it.
406    let folders: Vec<String> = found
407        .iter()
408        .map(|module| shown(&root, &module.dir))
409        .collect();
410
411    // The rules, and the coverage settings that the app keeps beside them.
412    let rules::RulesFile {
413        rules,
414        source: rules_source,
415        coverage: in_file,
416        coverage_ignored,
417    } = rules::load_file(&root);
418    let coverage_limit = options
419        .coverage_given
420        .limit
421        .or(in_file.limit)
422        .unwrap_or(options.coverage_limit);
423
424    // A report given for this read must be read; a fault is an error, not a fallback.
425    let report = match &options.coverage_given.report {
426        Some(given) => {
427            let path = root.join(given);
428            let fault = |message: String| ReadError::CoverageReport {
429                path: path.clone(),
430                message,
431            };
432            let xml = std::fs::read(&path).map_err(|error| fault(error.to_string()))?;
433            match clover::read_report(&xml) {
434                (files, None) => Some((path, files)),
435                (_, Some(message)) => return Err(fault(message)),
436            }
437        }
438        // The report the user named, if it is there; else the one Mortise finds.
439        None => in_file
440            .report
441            .as_ref()
442            .or(options.coverage_report.as_ref())
443            .map(|path| root.join(path))
444            .filter(|path| path.is_file())
445            .or_else(|| clover::find_report(&root))
446            .and_then(|path| {
447                let xml = std::fs::read(&path).ok()?;
448                Some((path, clover::read_report(&xml).0))
449            }),
450    };
451    let (report_path, report) = report.unzip();
452    let coverage_of = |folder: &str| -> Option<Coverage> {
453        // The report has the paths of the machine that ran the tests, so only the
454        // part from the modules folder on can be compared.
455        let inside = format!("/{folder}/");
456        let at_start = format!("{folder}/");
457        let mut total: Option<Coverage> = None;
458        for file in report.as_ref()? {
459            if file.path.contains(&inside) || file.path.starts_with(&at_start) {
460                total.get_or_insert_default().add(file.coverage);
461            }
462        }
463        total
464    };
465
466    // Which module uses which, checked against the rules of the app.
467    let sources: Vec<ModuleSource<'_>> = found
468        .iter()
469        .zip(&folders)
470        .map(|(module, folder)| ModuleSource {
471            name: &module.name,
472            on: module.state != ModuleState::Off,
473            namespace: &module.namespace,
474            surface: module.surface.as_ref(),
475            files: module
476                .scan
477                .sources
478                .iter()
479                // A test is not a boundary of the running app.
480                .filter(|source| !source.is_test)
481                .map(|source| {
482                    (
483                        format!("{folder}/{}", source.relative),
484                        source.analysis.refs.as_slice(),
485                    )
486                })
487                .collect(),
488            declared: module
489                .scan
490                .sources
491                .iter()
492                .flat_map(|source| {
493                    source
494                        .analysis
495                        .declares
496                        .iter()
497                        .map(|declared| declared.class.as_str())
498                })
499                .collect(),
500        })
501        .collect();
502    let (links, cycles) = links::build(&sources, &rules);
503    drop(sources);
504
505    let git = git::read(&root);
506    let (churn, uncommitted) = match git {
507        Git::Repository { .. } => {
508            let dirs: Vec<PathBuf> = found.iter().map(|module| module.dir.clone()).collect();
509            (git::churn(&root, &folders), git::uncommitted(&root, &dirs))
510        }
511        _ => (BTreeMap::new(), vec![None; found.len()]),
512    };
513
514    let modules: Vec<Module> = found
515        .into_iter()
516        .zip(codes)
517        .zip(&folders)
518        .zip(uncommitted)
519        .map(|(((module, code), folder), uncommitted)| Module {
520            name: module.name,
521            code,
522            dir: module.dir,
523            state: module.state,
524            description: module.description,
525            priority: module.priority,
526            manifest: module.manifest,
527            surface: module.surface,
528            namespace: module.namespace,
529            files: module.scan.files,
530            lines: module.scan.lines,
531            kinds: module.scan.kinds,
532            commands: module.scan.commands.into_iter().collect(),
533            tests: module.scan.tests,
534            coverage: coverage_of(folder),
535            churn: churn.get(folder).copied(),
536            uncommitted,
537        })
538        .collect();
539
540    let findings = findings::find(&Subject {
541        root: &root,
542        modules: &modules,
543        links: &links,
544        cycles: &cycles,
545        rules: &rules,
546        status_entries: &status_entries,
547        statuses_file: &shown(&root, &layout.statuses_file),
548        has_coverage_report: report_path.is_some(),
549        coverage_limit,
550        package: &options.package,
551    });
552
553    let package_data = options.package.with_tables(&modules);
554    let (app_url, app_env) = read_env(&root);
555    Ok(AppSnapshot {
556        name: root
557            .file_name()
558            .map(|name| name.to_string_lossy().into_owned())
559            .unwrap_or_else(|| root.display().to_string()),
560        laravel: lock.version(LARAVEL),
561        package,
562        actuator: lock.version(ACTUATOR),
563        app_url,
564        app_env,
565        layout,
566        modules,
567        coverage_report: report_path.map(|path| CoverageReport {
568            written: std::fs::metadata(&path)
569                .and_then(|metadata| metadata.modified())
570                .ok()
571                .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
572                .map(|since| since.as_secs() as i64),
573            path,
574        }),
575        git,
576        links,
577        cycles,
578        rules,
579        rules_source,
580        coverage_ignored,
581        findings,
582        coverage_limit,
583        package_data,
584        root,
585    })
586}
587
588fn requires_laravel(root: &Path) -> bool {
589    std::fs::read(root.join("composer.json"))
590        .ok()
591        .and_then(|json| serde_json::from_slice::<serde_json::Value>(&json).ok())
592        .is_some_and(|composer| {
593            ["require", "require-dev"]
594                .iter()
595                .any(|section| composer.get(section).and_then(|s| s.get(LARAVEL)).is_some())
596        })
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn a_path_is_shown_with_slashes_and_whole_when_outside_the_app() {
605        let (root, outside, whole) = if cfg!(windows) {
606            (r"C:\ci\app", r"D:\shared\Modules", "D:/shared/Modules")
607        } else {
608            ("/ci/app", "/shared/Modules", "/shared/Modules")
609        };
610        let root = Path::new(root);
611        assert_eq!(
612            shown(root, &root.join("Modules").join("Billing")),
613            "Modules/Billing"
614        );
615        assert_eq!(shown(root, Path::new(outside)), whole);
616        // `base_path('../shared/Modules')` climbs out of the app.
617        assert_eq!(
618            shown(root, &root.join("..").join("shared").join("Modules")),
619            if cfg!(windows) {
620                "C:/ci/shared/Modules"
621            } else {
622                "/ci/shared/Modules"
623            }
624        );
625    }
626
627    #[cfg(windows)]
628    #[test]
629    fn a_verbatim_or_unc_path_is_shown_as_a_path_that_opens() {
630        let root = Path::new(r"\\server\share\repo");
631        assert_eq!(
632            shown(root, Path::new(r"\\server\share\shared\Modules")),
633            "//server/share/shared/Modules"
634        );
635        assert_eq!(
636            shown(root, Path::new(r"\\?\D:\shared\Modules")),
637            "D:/shared/Modules"
638        );
639        assert_eq!(
640            shown(root, Path::new(r"\\?\UNC\server\share\shared")),
641            "//server/share/shared"
642        );
643        let volume = r"\\?\Volume{0}\shared";
644        assert_eq!(shown(root, Path::new(volume)), volume);
645    }
646
647    #[test]
648    fn the_url_and_the_environment_of_the_app_are_read_from_their_lines() {
649        let env = "APP_NAME=Shop\nAPP_ENV=production\nAPP_URLS=no\nAPP_URL=https://shop-api.test\nDB_PASSWORD=secret\n";
650        assert_eq!(
651            env_value(env, "APP_URL").as_deref(),
652            Some("https://shop-api.test")
653        );
654        assert_eq!(
655            env_value("APP_URL=\"http://localhost:8000\" # dev", "APP_URL").as_deref(),
656            Some("http://localhost:8000")
657        );
658        assert_eq!(
659            env_value("APP_URL = http://localhost # dev", "APP_URL").as_deref(),
660            Some("http://localhost")
661        );
662        assert_eq!(
663            env_value("export APP_URL='http://a.test'", "APP_URL").as_deref(),
664            Some("http://a.test")
665        );
666        assert_eq!(env_value("APP_URL=", "APP_URL"), None);
667        assert_eq!(env_value("# APP_URL=http://old.test", "APP_URL"), None);
668        assert_eq!(env_value("APP_ENV=local", "APP_URL"), None);
669        assert_eq!(env_value(env, "APP_ENV").as_deref(), Some("production"));
670        assert_eq!(
671            env_value("APP_URL=http://a.test\nAPP_URL=http://b.test", "APP_URL").as_deref(),
672            Some("http://b.test")
673        );
674    }
675}