Skip to main content

trusty_code/fs_browse/
roster.rs

1//! Known-project roster discovery for the GUI's workstream-first
2//! project-picker modal (issue #3365).
3//!
4//! Why: DOC-48 §8/DOC-39 §4.2 shift the GUI's entry concept from "new
5//! session" to "new workstream" — creating a workstream now binds it to a
6//! project through a MODAL, not [`super::list_dir`]'s arbitrary-directory
7//! browse-and-descend picker (7a). A modal wants a short, flat, best-guess
8//! candidate LIST to click through, not a filesystem tree to navigate. The
9//! prior GUI slice's own module doc recorded this exact gap: "no pre-session
10//! roster endpoint exists yet" — this module is that endpoint's daemon-side
11//! data source. There is no existing project/config registry in this crate
12//! to reuse (`crate::binding::ProjectBinding` is the daemon's OWN one-project
13//! binding, not a multi-project registry), so this is a fresh, best-effort
14//! filesystem scan, deliberately narrow in scope (see `MAX_ENTRIES`).
15//!
16//! **Update (issue #3435):** trusty-mpm's shared project registry — a real
17//! cross-machine registry this crate does not own — is now the PRIMARY
18//! source for the roster the GUI actually renders; this module's scan has
19//! been demoted to the SECONDARY source (surfacing local-only, unregistered
20//! candidates the registry doesn't know about) plus the graceful-degradation
21//! fallback for when the mpm daemon is unreachable. See `super::mpm_registry`
22//! for the merge step and [`ProjectCandidate::registered`]. This module's own
23//! scan behavior and discovery heuristic below are otherwise unchanged.
24//!
25//! **Discovery heuristic.** This workspace's own convention — visible in the
26//! very checkout this crate lives in — is `~/trusty-mpm-projects/<owner>/
27//! <repo>` (an owner-scoped project root trusty-mpm's own tooling
28//! established). When that directory exists, [`list_projects`] scans it two
29//! levels deep (owner dirs, then their repo dirs) and returns every repo dir
30//! that [`super::is_git_repo`] accepts — the same discriminator 7a's picker
31//! already uses. When it does NOT exist (a machine without trusty-mpm's
32//! project layout), this falls back to a single-level scan of the home
33//! directory itself, on the theory that a developer machine without the
34//! owner-scoped layout more commonly keeps repos as direct children of `~`
35//! (e.g. `~/acme-api`) — still filtered to git repos only, so a home full of
36//! Documents/Downloads/etc. does not flood the picker with noise.
37//!
38//! What: [`ProjectCandidate`] is one flat, pre-resolved row the picker can
39//! render directly (no further filesystem calls needed, unlike 7a's
40//! navigate-then-list flow); [`ProjectRoster`] is the whole response body.
41//! [`list_projects`] is a thin `dirs::home_dir()`-resolving wrapper around
42//! [`list_projects_in`], the actual (testable) scan — mirroring
43//! `crate::serve::mod::build_router`/`build_router_at`'s real-vs-injectable
44//! split so tests never touch the real developer home directory. Every
45//! filesystem read here is best-effort: an unreadable or missing scan root
46//! degrades to an empty (or partial) roster, never an error — mirroring
47//! [`super::list_dir`]'s own per-entry best-effort philosophy, appropriate
48//! here since this endpoint is a convenience shortlist, not the only way to
49//! bind a project (an operator can still fall back to the [`super::list_dir`]
50//! browse surface, which this ticket leaves untouched).
51//! Test: `tests::*`.
52
53use std::path::Path;
54
55use serde::Serialize;
56
57use super::is_git_repo;
58
59/// Hard cap on the number of roster entries returned.
60///
61/// Why: this is a "quick pick" shortlist for a modal, not a paginated
62/// browser — an unbounded scan of a large `trusty-mpm-projects` tree (or, in
63/// the fallback case, a large home directory) must never turn a "small
64/// roster" call into a slow, huge response. 200 comfortably covers a
65/// realistic multi-owner project tree while staying obviously "small" per
66/// the issue's own requirement. `pub(super)` (not private) so
67/// `super::mpm_registry`'s merge step (issue #3435) truncates the
68/// registry-augmented roster to the same cap rather than duplicating the
69/// magic number.
70/// Test: `tests::scan_is_capped_at_max_entries`.
71pub(super) const MAX_ENTRIES: usize = 200;
72
73/// One candidate project row — everything the picker needs to render and
74/// bind it without a further round-trip.
75///
76/// Why: mirrors [`super::DirEntryInfo`] in spirit (name + path a client can
77/// bind directly), but flatter — no `is_dir` (every entry here is already
78/// known to be a directory) and no `is_git_repo` (every entry here is
79/// already known to be a git repo — filtering, not badging, is this
80/// endpoint's job). `owner` carries the `trusty-mpm-projects/<owner>/<repo>`
81/// layout's owner segment when the scan found it that way, so the picker can
82/// disambiguate two repos that share a name under different owners; `None`
83/// on the home-directory fallback path, where there is no owner segment.
84/// `registered` (issue #3435) distinguishes a project known to trusty-mpm's
85/// shared project registry from one this crate found only by scanning the
86/// filesystem — a plain fs scan can never set it `true` on its own, so every
87/// candidate this module produces starts `false`; only
88/// `super::mpm_registry::merge` (the registry-primary merge step) flips it.
89/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`.
90#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
91pub struct ProjectCandidate {
92    /// The repo directory's own name (e.g. `trusty-tools`).
93    pub name: String,
94    /// Absolute path to the repo directory.
95    pub path: String,
96    /// The owning directory's name under `~/trusty-mpm-projects`, when the
97    /// scan found this candidate that way; `None` on the home-directory
98    /// fallback path.
99    pub owner: Option<String>,
100    /// Whether this candidate is also known to trusty-mpm's shared project
101    /// registry (issue #3435). Always `false` from a bare filesystem scan —
102    /// see the struct docs.
103    pub registered: bool,
104}
105
106/// Which source produced a [`ProjectRoster`] (issue #3435, code-critic PR
107/// #3439 review, HIGH 2).
108///
109/// Why: the #3363 lesson — "nothing registered" and "the registry was
110/// unreachable" are different operator-facing situations and must not
111/// collapse into the same-looking empty/all-unregistered roster. A bare
112/// `bool` would work, but a named enum reads at the call site
113/// (`source == RosterSource::FsOnly`) without a comment explaining which
114/// state `true`/`false` means, and its `serde` rendering (`"registry"` /
115/// `"fs_only"`) is self-describing on the wire too.
116/// What: [`Self::Registry`] means the mpm daemon was reached and `entries`
117/// is the registry-primary/fs-secondary merge (see `super::mpm_registry`);
118/// [`Self::FsOnly`] means the registry was never reached (unreachable
119/// daemon, or not yet queried) and `entries` is the bare filesystem scan,
120/// every candidate `registered: false`.
121/// Test: `super::mpm_registry::tests::merged_roster_with_uses_registry_when_daemon_reachable`,
122/// `super::mpm_registry::tests::merged_roster_with_degrades_to_fs_only_when_daemon_unreachable`.
123#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)]
124#[serde(rename_all = "snake_case")]
125pub enum RosterSource {
126    /// The mpm registry was reached; `entries` is the registry-primary merge.
127    Registry,
128    /// The mpm registry was unreachable (or never queried); `entries` is the
129    /// filesystem scan alone.
130    #[default]
131    FsOnly,
132}
133
134/// The `fs.list_projects` response body — everything the picker needs for
135/// one render.
136///
137/// Why: a bare `Vec<ProjectCandidate>` would work equally well over the
138/// wire, but wrapping it in a named struct (mirroring [`super::DirListing`])
139/// leaves room to add roster-level metadata later (e.g. a `truncated: bool`
140/// flag) without a breaking wire-shape change — `source` (issue #3435) is
141/// exactly that: an additive field a client predating it can simply ignore.
142/// Test: `tests::empty_home_returns_empty_roster`.
143#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
144pub struct ProjectRoster {
145    /// Candidate projects, sorted case-insensitively by `name`, capped at
146    /// [`MAX_ENTRIES`].
147    pub entries: Vec<ProjectCandidate>,
148    /// Which source produced `entries` (issue #3435). A bare filesystem scan
149    /// (this module's own [`list_projects`]/[`list_projects_in`]) always
150    /// reports [`RosterSource::FsOnly`] — only `super::mpm_registry::merge`
151    /// reports [`RosterSource::Registry`], on a successful registry fetch.
152    #[serde(default)]
153    pub source: RosterSource,
154}
155
156/// `fs.list_projects()` — the daemon-side entry point (issue #3365).
157///
158/// Why: the one function `protocol::list_projects` calls; resolves the real
159/// home directory so the RPC handler itself stays a one-liner.
160/// What: resolves the managed workspace root through
161/// [`trusty_common::workspace_layout::workspace_root`] — the SAME resolver
162/// trusty-mpm uses (#5203), so an operator who retargets the root via
163/// `TRUSTY_MPM_WORKSPACE_ROOT` or `workspace_root_template` gets a picker that
164/// scans where the checkouts actually are. `dirs::home_dir()` unresolvable ->
165/// an empty [`ProjectRoster`] (never an error — see module docs on the
166/// best-effort philosophy); it is still needed for the flat fallback scan.
167/// Otherwise delegates to [`list_projects_in`].
168/// Test: `tests::configured_workspace_root_is_scanned_not_the_default`
169/// (the #5203 regression), plus `protocol::tests::list_projects_returns_entries_array`.
170pub fn list_projects() -> ProjectRoster {
171    // #5203: scan the CONFIGURED workspace root, not a hardcoded literal.
172    match dirs::home_dir() {
173        Some(home) => list_projects_in(&home, &trusty_common::workspace_layout::workspace_root()),
174        None => ProjectRoster::default(),
175    }
176}
177
178/// The testable core of [`list_projects`]: scan a given `home` directory
179/// rather than resolving the real one.
180///
181/// Why: split out so tests can point this at a tempdir instead of the
182/// developer's (or CI runner's) actual home — the same seam
183/// `serve::mod::build_router_at` uses for the workstream store's data dir.
184/// What: if `workspace_root` is a directory, scans it two levels deep (owner
185/// dirs -> their repo dirs, each filtered to [`super::is_git_repo`]) via
186/// [`scan_owner_layout`]; otherwise scans `home` itself one level deep via
187/// [`scan_flat_layout`]. Either way, results are sorted case-insensitively by
188/// `name` and truncated to [`MAX_ENTRIES`].
189///
190/// #5203 split `workspace_root` out of `home` rather than deriving it here: the
191/// root is configurable and may sit anywhere, so only the caller (which owns the
192/// resolver) can say where it is. `home` remains a separate parameter because
193/// the FLAT fallback genuinely scans the home directory, not the workspace root.
194/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`,
195/// `tests::falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir`,
196/// `tests::non_git_directories_are_excluded`,
197/// `tests::scan_is_capped_at_max_entries`,
198/// `tests::empty_home_returns_empty_roster`.
199///
200/// `pub(super)` (not private) so `super::mpm_registry`'s tests (issue #3435)
201/// can build a hermetic filesystem-only `ProjectRoster` against a tempdir
202/// `home`, the same seam this module's own tests already use, rather than
203/// hand-rolling a second scan helper.
204pub(super) fn list_projects_in(home: &Path, workspace_root: &Path) -> ProjectRoster {
205    let mut entries = if workspace_root.is_dir() {
206        scan_owner_layout(workspace_root)
207    } else {
208        scan_flat_layout(home)
209    };
210    entries.sort_by_key(|e| e.name.to_lowercase());
211    entries.truncate(MAX_ENTRIES);
212    ProjectRoster {
213        entries,
214        source: RosterSource::FsOnly,
215    }
216}
217
218/// Scan `<home>/trusty-mpm-projects/<owner>/<repo>` two levels deep,
219/// keeping only `<repo>` dirs that are git repos.
220///
221/// Why: this workspace's own owner-scoped layout (see module docs) —
222/// factored out from [`list_projects_in`] so each layout has its own,
223/// independently testable scan function.
224/// What: skips unreadable roots/owner dirs (best-effort — a permission
225/// refusal on one owner dir must not blank the whole roster) and dotfile
226/// entries at both levels.
227/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`,
228/// `tests::unreadable_owner_dir_is_skipped_not_fatal`.
229fn scan_owner_layout(mpm_root: &Path) -> Vec<ProjectCandidate> {
230    let mut out = Vec::new();
231    let Ok(owners) = std::fs::read_dir(mpm_root) else {
232        return out;
233    };
234    for owner_entry in owners.flatten() {
235        let owner_path = owner_entry.path();
236        if !owner_path.is_dir() {
237            continue;
238        }
239        let owner_name = owner_entry.file_name().to_string_lossy().into_owned();
240        if owner_name.starts_with('.') {
241            continue;
242        }
243        let Ok(repos) = std::fs::read_dir(&owner_path) else {
244            continue;
245        };
246        for repo_entry in repos.flatten() {
247            let repo_path = repo_entry.path();
248            if !repo_path.is_dir() {
249                continue;
250            }
251            let repo_name = repo_entry.file_name().to_string_lossy().into_owned();
252            if repo_name.starts_with('.') || !is_git_repo(&repo_path) {
253                continue;
254            }
255            out.push(ProjectCandidate {
256                name: repo_name,
257                path: repo_path.display().to_string(),
258                owner: Some(owner_name.clone()),
259                registered: false,
260            });
261        }
262    }
263    out
264}
265
266/// Scan `home` itself one level deep, keeping only entries that are git
267/// repos.
268///
269/// Why: the fallback layout for a machine without `~/trusty-mpm-projects`
270/// (see module docs) — factored out for the same reason as
271/// [`scan_owner_layout`].
272/// What: skips an unreadable `home` (best-effort -> empty) and dotfile
273/// entries.
274/// Test: `tests::falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir`.
275fn scan_flat_layout(home: &Path) -> Vec<ProjectCandidate> {
276    let mut out = Vec::new();
277    let Ok(read) = std::fs::read_dir(home) else {
278        return out;
279    };
280    for entry in read.flatten() {
281        let path = entry.path();
282        if !path.is_dir() {
283            continue;
284        }
285        let name = entry.file_name().to_string_lossy().into_owned();
286        if name.starts_with('.') || !is_git_repo(&path) {
287            continue;
288        }
289        out.push(ProjectCandidate {
290            name,
291            path: path.display().to_string(),
292            owner: None,
293            registered: false,
294        });
295    }
296    out
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    fn mkdir(p: &Path) {
304        std::fs::create_dir_all(p).expect("mkdir");
305    }
306
307    fn mk_git_repo(p: &Path) {
308        mkdir(p);
309        mkdir(&p.join(".git"));
310    }
311
312    /// The owner-scoped `trusty-mpm-projects/<owner>/<repo>` layout must be
313    /// scanned two levels deep, returning only git repos with their owner
314    /// attached.
315    #[test]
316    fn trusty_mpm_projects_layout_is_scanned_two_levels_deep() {
317        let home = tempfile::tempdir().expect("tempdir");
318        let root = home.path().join("trusty-mpm-projects");
319        mk_git_repo(&root.join("bobmatnyc").join("trusty-tools"));
320        mkdir(&root.join("bobmatnyc").join("scratch")); // not a git repo
321        mk_git_repo(&root.join("acme").join("widgets"));
322
323        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
324
325        assert_eq!(roster.entries.len(), 2);
326        let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
327        assert!(names.contains(&"trusty-tools"));
328        assert!(names.contains(&"widgets"));
329        let tt = roster
330            .entries
331            .iter()
332            .find(|e| e.name == "trusty-tools")
333            .expect("trusty-tools entry");
334        assert_eq!(tt.owner.as_deref(), Some("bobmatnyc"));
335    }
336
337    /// Without a `trusty-mpm-projects` root, the scan falls back to `home`
338    /// itself, one level deep, git repos only, `owner: None`.
339    #[test]
340    fn falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir() {
341        let home = tempfile::tempdir().expect("tempdir");
342        mk_git_repo(&home.path().join("acme-api"));
343        mkdir(&home.path().join("Downloads")); // not a git repo
344
345        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
346
347        assert_eq!(roster.entries.len(), 1);
348        assert_eq!(roster.entries[0].name, "acme-api");
349        assert_eq!(roster.entries[0].owner, None);
350    }
351
352    /// A non-git directory, at either scan level, must never appear in the
353    /// roster — this is a project shortlist, not a general directory
354    /// listing (unlike `super::list_dir`, which lists everything).
355    #[test]
356    fn non_git_directories_are_excluded() {
357        let home = tempfile::tempdir().expect("tempdir");
358        let root = home.path().join("trusty-mpm-projects");
359        mkdir(&root.join("bobmatnyc").join("not-a-repo"));
360
361        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
362
363        assert!(roster.entries.is_empty());
364    }
365
366    /// A missing/unreadable `trusty-mpm-projects` OWNER dir must not blank
367    /// the whole roster — best-effort per-owner scanning, mirroring
368    /// `list_dir`'s per-entry philosophy.
369    #[test]
370    fn unreadable_owner_dir_is_skipped_not_fatal() {
371        let home = tempfile::tempdir().expect("tempdir");
372        let root = home.path().join("trusty-mpm-projects");
373        // A file named like an owner dir (not a directory) is simply
374        // skipped by the `owner_path.is_dir()` guard rather than erroring.
375        mkdir(&root);
376        std::fs::write(root.join("not-a-dir-owner"), "x").expect("write");
377        mk_git_repo(&root.join("realowner").join("repo"));
378
379        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
380
381        assert_eq!(roster.entries.len(), 1);
382        assert_eq!(roster.entries[0].owner.as_deref(), Some("realowner"));
383    }
384
385    /// A home with no `trusty-mpm-projects` dir and no git repos of its own
386    /// returns an empty roster, not an error.
387    #[test]
388    fn empty_home_returns_empty_roster() {
389        let home = tempfile::tempdir().expect("tempdir");
390        mkdir(&home.path().join("Documents"));
391
392        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
393
394        assert!(roster.entries.is_empty());
395    }
396
397    /// A scan producing more than [`MAX_ENTRIES`] candidates must be capped,
398    /// never returned in full — this is a "quick pick" shortlist, not a
399    /// paginated browser (see `MAX_ENTRIES`'s own docs).
400    #[test]
401    fn scan_is_capped_at_max_entries() {
402        let home = tempfile::tempdir().expect("tempdir");
403        let owner = home.path().join("trusty-mpm-projects").join("owner");
404        for i in 0..(MAX_ENTRIES + 25) {
405            mk_git_repo(&owner.join(format!("repo-{i:04}")));
406        }
407
408        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
409
410        assert_eq!(roster.entries.len(), MAX_ENTRIES);
411    }
412
413    /// Results must be sorted case-insensitively by name, regardless of
414    /// owner or directory read order.
415    #[test]
416    fn results_are_sorted_case_insensitively_by_name() {
417        let home = tempfile::tempdir().expect("tempdir");
418        let root = home.path().join("trusty-mpm-projects");
419        mk_git_repo(&root.join("owner").join("Zebra"));
420        mk_git_repo(&root.join("owner").join("apple"));
421        mk_git_repo(&root.join("owner").join("Banana"));
422
423        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));
424
425        let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
426        assert_eq!(names, vec!["apple", "Banana", "Zebra"]);
427    }
428
429    /// #5203 REGRESSION: a CONFIGURED workspace root must be the directory the
430    /// picker scans — not the hardcoded `~/trusty-mpm-projects`.
431    ///
432    /// Why: this is the defect itself. Before the fix, [`list_projects`] built
433    /// its scan root as `home.join("trusty-mpm-projects")` and never read
434    /// `TRUSTY_MPM_WORKSPACE_ROOT`, so an operator who retargeted the managed
435    /// root got a picker that reported every real checkout as missing. This
436    /// test drives the PRODUCTION entry point (not the injectable core) so it
437    /// exercises the resolver wiring, which is exactly what was absent.
438    /// What: points the env var at a tempdir holding `<owner>/<repo>/.git`, then
439    /// asserts `list_projects()` finds that repo AND that the path it reports is
440    /// under the configured root. Against the pre-fix commit this fails at the
441    /// first assertion — the roster comes back from the default root instead.
442    /// Test: this test.
443    #[test]
444    fn configured_workspace_root_is_scanned_not_the_default() {
445        let _guard = env_lock();
446        let configured = tempfile::tempdir().expect("tempdir");
447        mk_git_repo(&configured.path().join("acme").join("widgets"));
448
449        // SAFETY: every env-mutating test in this module holds `env_lock()`.
450        unsafe {
451            std::env::set_var(
452                trusty_common::workspace_layout::WORKSPACE_ROOT_ENV,
453                configured.path(),
454            );
455        }
456        let roster = list_projects();
457        // SAFETY: as above.
458        unsafe {
459            std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
460        }
461
462        let found = roster
463            .entries
464            .iter()
465            .find(|e| e.name == "widgets")
466            .unwrap_or_else(|| {
467                panic!(
468                    "the configured workspace root {} must be scanned; roster was {:?}",
469                    configured.path().display(),
470                    roster.entries
471                )
472            });
473        assert_eq!(found.owner.as_deref(), Some("acme"));
474        assert!(
475            Path::new(&found.path).starts_with(configured.path()),
476            "entry path {} must sit under the configured root {}",
477            found.path,
478            configured.path().display()
479        );
480    }
481
482    /// #5203: with nothing configured, the default must stay
483    /// `~/trusty-mpm-projects` — the fix must not move the root for the
484    /// overwhelming majority of operators who configure nothing.
485    ///
486    /// Why: the companion to the regression above. A resolver that honoured
487    /// config but changed the unconfigured default would break every existing
488    /// install silently.
489    /// What: with the env var cleared AND no config template supplied, the
490    /// shared resolver returns `<home>/trusty-mpm-projects`. Asserts against
491    /// `resolve_workspace_root(None)` rather than the zero-argument
492    /// `workspace_root()`, which reads the DEVELOPER'S OWN `config.yaml` — a
493    /// machine with `workspace_root_template` set would otherwise fail this
494    /// test for a correct build.
495    /// Test: this test.
496    #[test]
497    fn default_workspace_root_is_unchanged_when_nothing_is_configured() {
498        let _guard = env_lock();
499        // SAFETY: guarded by `env_lock()`.
500        unsafe {
501            std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
502        }
503        let root = trusty_common::workspace_layout::resolve_workspace_root(None);
504        let home = dirs::home_dir().expect("home");
505        assert_eq!(root, home.join("trusty-mpm-projects"));
506    }
507
508    /// Serialise the env-mutating tests in this module.
509    ///
510    /// Why: `cargo test` shares one process environment across parallel test
511    /// threads, so an unguarded `set_var` leaks into a sibling's assertions.
512    /// What: a process-global mutex, poison-tolerant (a panicking test must not
513    /// wedge every later one).
514    /// Test: used by `configured_workspace_root_is_scanned_not_the_default`,
515    /// `default_workspace_root_is_unchanged_when_nothing_is_configured`.
516    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
517        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
518        LOCK.get_or_init(|| std::sync::Mutex::new(()))
519            .lock()
520            .unwrap_or_else(|e| e.into_inner())
521    }
522}