pmpx-engine 0.3.2

Runs what a plugin answers: resolving the program, starting it, and reporting what happened.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! One run's state: the configuration, the project, and the plugins that are installed.
//!
//! Everything here is read **once**, at the start: `[discovery]` decides how the project is found, which
//! decides which `.pmpx.toml` layers apply, which decides which plugins can answer. Reading any of it on
//! demand would make the order of reads observable in the result.
//!
//! Nothing here prints and nothing here exits: the phases of the setup are reported as [`Event`]s, and
//! every failure is a value. The two argv facts it needs -- the start directory and the contract version
//! to ask the store for -- arrive as [`Options`], because a library that parsed arguments would drag
//! `clap` into every embedder.

use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::time::Instant;

use crate_plugin_kit::{CratePluginKit, KitConfig};
use pmpx_detect::{DetectFailure, FamilyScore, Selection};
use pmpx_plugin::abi::PmpxPlugin;
use pmpx_project::{GlobalConfig, MergedProjectConfig};

use crate::discovery::{self, StopReason, Walk};
use crate::error::Result;
use crate::log::Levels;
use crate::store::{InstalledPlugin, PluginSet};
use crate::ChildOutput;
use crate::{EngineError, Event};

/// What the command line said, as this crate needs it.
#[derive(Debug, Clone, Default)]
pub struct Options {
    /// The directory `-C` named, if any. `None` means the process's own directory.
    pub start_dir: Option<PathBuf>,
    /// `--no-walk-up`: only the start directory is considered a project root.
    pub no_walk_up: bool,
    /// `-p/--plugin`: name a plugin outright, skipping detection.
    pub wanted_plugin: Option<String>,
    /// `--quiet`: no notes on stderr.
    pub quiet: bool,
    /// `--debug`: whether the trace is on, which also decides how loud a plugin may be.
    pub trace: bool,
    /// `--json`: hand the backend pmpx's stderr for its stdout, keeping stdout a JSON stream.
    pub child_output_on_stderr: bool,
    /// The contract version to ask the store for, which is the host's own version.
    pub contract_version: String,
}

/// The whole context of one run.
pub struct Session {
    /// Start directory (what `-C` gave, or cwd).
    pub start_dir: PathBuf,
    /// Global config.
    pub global: GlobalConfig,
    /// Merged project config (several layers of `.pmpx.toml`).
    pub project: MergedProjectConfig,
    /// Manifest list of installed plugins (manifest reads only, no dlopen).
    pub plugins: PluginSet,
    /// Plugin library handle.
    pub(crate) kit: CratePluginKit<PmpxPlugin>,
    /// The directories walk-up visited and why it stopped.
    pub walk: Walk,
    /// The project root. Computed in `open` -- it is the single answer to "where do we run", not
    /// recomputed every time.
    pub project_root: Option<PathBuf>,
    /// The value of `-p/--plugin`.
    pub wanted_plugin: Option<String>,
    /// `--quiet`: turns off the notes on stderr.
    pub quiet: bool,
    /// `--debug`: whether the trace is on.
    trace: bool,
    /// `--json`: the backend's own output goes to stderr, so stdout stays a JSON stream.
    pub(crate) child_output_on_stderr: bool,
}

impl Session {
    /// Read config, scan plugins, walk up. Selects no plugin and loads no code.
    ///
    /// Every step here is a phase of the trace: this is where a run spends the time that is not the
    /// backend's, so it is the part that has to be attributable.
    pub fn open(options: Options, events: &mut dyn FnMut(Event)) -> Result<Self> {
        let start_dir = phase(
            events,
            "session.start-dir",
            || resolve_start_dir(options.start_dir.as_deref()),
            |dir| dir.display().to_string(),
        )?;

        let global = phase(
            events,
            "session.config",
            || {
                GlobalConfig::load().map_err(|error| {
                    EngineError::Setup(format!("failed to read the config: {error}"))
                })
            },
            |_| "global config.toml".to_string(),
        )?;

        // `--no-walk-up` can only tighten `[discovery] walk_up`, never loosen it.
        let mut discovery_cfg = global.discovery.clone();
        if options.no_walk_up {
            discovery_cfg.walk_up = false;
        }

        let data_dir = global.plugin_store.effective_data_dir().map_err(|error| {
            EngineError::Setup(format!("cannot decide the plugin directory: {error}"))
        })?;

        let mut kit_cfg = KitConfig::new("pmpx").with_data_dir(&data_dir);

        // Only a fallback: the wrapper crate-plugin-kit generates repeats whatever the plugin crate
        // itself declares for the contract crate. `KitConfig`'s default here is "0.1", which resolves to
        // nothing while this workspace releases at 0.0.x.
        //
        // The host's own version is the right fallback because the workspace carries a single version, so
        // the CLI and the contract are always published as the same number.
        kit_cfg.contract_version = options.contract_version;

        // The kit's defaults are derived from the id and say `_v1`; this host speaks v3, and the symbol
        // is what a plugin exports. The wrapper body needs no change: the derived default already asks
        // the contract crate for `export!`.
        kit_cfg.entry_symbol = pmpx_plugin::abi::PMPX_ENTRY_SYMBOL.as_bytes().to_vec();

        kit_cfg.prefer_prebuilt = global.plugin_store.effective_prefer_prebuilt();

        let kit = phase(
            events,
            "session.store",
            || {
                CratePluginKit::<PmpxPlugin>::new(kit_cfg).map_err(|error| {
                    EngineError::Setup(format!(
                        "failed to initialise the plugin store: {}\n{error}",
                        data_dir.display()
                    ))
                })
            },
            |_| data_dir.display().to_string(),
        )?;

        let plugins = phase(
            events,
            "session.plugins",
            || {
                PluginSet::load(&kit).map_err(|error| {
                    EngineError::Setup(format!("failed to read the installed plugins: {error}"))
                })
            },
            |set| {
                format!(
                    "{} installed, {} usable",
                    set.plugins.len(),
                    set.usable().count()
                )
            },
        )?;

        // Walk up **once**. The path and the stop reason, the project root, and the config layers are
        // three views of the same traversal, so they are derived here instead of walking again -- that
        // also makes it impossible for them to disagree about where the walk stopped.
        let walk = phase(
            events,
            "session.walk",
            || Ok(discovery::walk(&start_dir, &discovery_cfg)),
            |walk| {
                format!(
                    "{}, stopped because: {}",
                    discovery::dirs(walk.dirs.len()),
                    walk.stopped.describe(discovery_cfg.max_depth)
                )
            },
        )?;

        // The candidates are stat'ed one by one and the search stops at the first hit, so the count is
        // the real cost of this phase -- reporting the walked directories instead would overstate it in a
        // deep tree.
        let checked = Cell::new(0usize);
        let project_root = phase(
            events,
            "session.root",
            || {
                Ok(walk.project_root(|dir| {
                    checked.set(checked.get() + 1);
                    plugins.marks_root(dir)
                }))
            },
            |root| match root {
                Some(root) => format!("{} checked -> {}", checked.get(), root.display()),
                None => format!("{} checked -> none", checked.get()),
            },
        )?;

        let project = phase(
            events,
            "session.project-conf",
            || {
                MergedProjectConfig::from_paths_near_to_far(&walk.config_paths()).map_err(|error| {
                    EngineError::Setup(format!("failed to read the project config: {error}"))
                })
            },
            |project| format!("{} .pmpx.toml", project.sources.len()),
        )?;

        Ok(Self {
            start_dir,
            global,
            project,
            plugins,
            kit,
            walk,
            project_root,
            wanted_plugin: options.wanted_plugin,
            quiet: options.quiet,
            trace: options.trace,
            child_output_on_stderr: options.child_output_on_stderr,
        })
    }

    /// The project root. Not found is not found -- it never falls back to cwd.
    pub fn project_root(&self) -> Option<&Path> {
        self.project_root.as_deref()
    }

    /// The error for "no project detected" (exit code 3).
    ///
    /// The advice names the **installed** plugins and the markers they declared. There is deliberately no
    /// built-in table of "these files look like Rust/Node/…": that would be ecosystem knowledge the plugin
    /// model exists to avoid, and it would duplicate what the plugins already declare.
    pub fn no_project_error(&self) -> EngineError {
        let mut msg = format!("no project type detected in {}.", self.start_dir.display());

        // Where walk-up stopped -- this decides between "searched and found nothing" and "barely searched
        // at all".
        msg.push_str(&format!(
            "\nWalked up {}, stopped because: {}.",
            discovery::dirs(self.walk.dirs.len()),
            self.walk.stopped.describe(self.global.discovery.max_depth)
        ));

        if self.walk.stopped == StopReason::WalkUpDisabled {
            msg.push_str(
                "\n(`--no-walk-up` or the global `[discovery] walk_up = false` turned walk-up off)",
            );
        }

        let installed: Vec<String> = self
            .plugins
            .usable()
            .map(|p| p.name().to_string())
            .collect();
        if installed.is_empty() {
            msg.push_str(
                "\nNo plugins are installed. pmpx decides the project type from the marker files \
                 declared by installed plugins, so nothing can be detected right now.",
            );
        } else {
            msg.push_str(&format!("\nInstalled plugins: {}", installed.join(", ")));

            let mut markers: Vec<&str> = self
                .plugins
                .detect_names()
                .iter()
                .map(String::as_str)
                .collect();
            markers.sort_unstable();
            markers.dedup();
            msg.push_str(&format!(
                "\nThey look for these files: {}",
                markers.join(", ")
            ));
        }

        msg.push_str(
            "\n\nYou can declare it explicitly with a .pmpx.toml in the current directory, for \
             example:\n  [plugin]\n  rust = \"cargo\"",
        );

        EngineError::NoProject(msg)
    }

    /// How much of a plugin's own output this run wants.
    pub fn levels(&self) -> Levels {
        Levels {
            quiet: self.quiet,
            trace: self.trace,
        }
    }

    /// Resolve which plugin to use, scoring the project.
    pub fn select(
        &self,
        root: &Path,
        events: &mut dyn FnMut(Event),
    ) -> std::result::Result<Selection, DetectFailure> {
        crate::detect::select(
            &self.plugins,
            root,
            &self.project,
            &self.global,
            self.wanted_plugin.as_deref(),
            events,
        )
    }

    /// Resolve from scores the caller already computed.
    pub fn select_from(
        &self,
        root: &Path,
        families: &std::collections::BTreeMap<String, FamilyScore>,
        events: &mut dyn FnMut(Event),
    ) -> std::result::Result<Selection, DetectFailure> {
        crate::detect::select_from_scores(
            &self.plugins,
            root,
            families,
            &self.project,
            &self.global,
            self.wanted_plugin.as_deref(),
            events,
        )
    }

    /// Load the selected plugin.
    ///
    /// `dlopen` and the ABI checks happen here, so this is the phase that turns "which plugin" into "code
    /// in this process".
    pub fn load_backend(
        &self,
        selection: &Selection,
        events: &mut dyn FnMut(Event),
    ) -> Result<crate::Backend> {
        let Some(plugin) = self.plugins.by_crate_name(&selection.crate_name) else {
            return Err(EngineError::Setup(format!(
                "plugin {} is not in the list (deleted between the two reads?)",
                selection.crate_name
            )));
        };

        let started = Instant::now();
        let loaded = self.load_plugin(plugin, events);
        events(Event::Phase {
            name: "backend.load",
            micros: started.elapsed().as_micros(),
            detail: match &loaded {
                Ok(_) => plugin.crate_name().to_string(),
                Err(error) => format!("{} FAILED: {error}", plugin.crate_name()),
            },
        });

        loaded
    }

    /// Load one installed plugin, whatever the reason: a verb, `plugin info`, or a store listing its
    /// diagnostics.
    ///
    /// The store knows how a plugin's directory is laid out, so finding the library is this side's job;
    /// everything past that -- opening it, checking what it says about itself, installing the hooks -- is
    /// [`crate::Backend`]'s.
    pub fn load_plugin(
        &self,
        plugin: &InstalledPlugin,
        events: &mut dyn FnMut(Event),
    ) -> Result<crate::Backend> {
        let identity = crate::PluginIdentity {
            name: plugin.name().to_string(),
            crate_name: plugin.crate_name().to_string(),
            dir: plugin.dir().to_path_buf(),
            wanted: plugin.wanted.clone(),
            declared_abi: plugin.abi(),
        };

        // The library file lives in the plugin's own directory, named after its crate with the platform's
        // conventions -- `find_library` knows the last part of that.
        let stem = plugin.crate_name().replace('-', "_");
        let library = crate_plugin_kit::find_library(plugin.dir(), &stem).map_err(|error| {
            EngineError::Setup(format!(
                "cannot find the plugin library for {} in {}: {error}",
                plugin.crate_name(),
                plugin.dir().display()
            ))
        })?;

        crate::Backend::load(&identity, &library, self.levels(), events)
    }
}

/// Run `f`, reporting it as one named phase with the detail `describe` derives from its result.
///
/// A phase that fails is reported too: "the store took 3ms and then failed" is exactly what someone
/// reading a trace wants to know.
fn phase<T, D>(
    events: &mut dyn FnMut(Event),
    name: &'static str,
    f: impl FnOnce() -> Result<T>,
    describe: D,
) -> Result<T>
where
    D: FnOnce(&T) -> String,
{
    let started = Instant::now();
    let out = f();
    events(Event::Phase {
        name,
        micros: started.elapsed().as_micros(),
        detail: match &out {
            Ok(value) => describe(value),
            Err(error) => error.message(),
        },
    });
    out
}

/// The directory a run starts in.
///
/// `-C` must exist, otherwise it is a clear setup error -- quietly falling back to cwd would make "I ran
/// the command in the wrong directory" hard to notice.
///
/// Normalized by [`discovery::normalize`], **not** `canonicalize`: `std::fs::canonicalize` -- and
/// `std::path::absolute` with it -- returns a Windows verbatim path (`\\?\C:\…`), which then travels into
/// the context a plugin is handed, and tools that take a path as an argument (cargo, `cmd`, the package
/// managers themselves) either refuse that form or read it differently. Resolving symlinks is not this
/// layer's business either: the person asked for the directory they named.
fn resolve_start_dir(dir: Option<&Path>) -> Result<PathBuf> {
    match dir {
        Some(dir) => {
            if !dir.is_dir() {
                return Err(EngineError::Usage(format!(
                    "cannot use {} as the directory: it is not a directory",
                    dir.display()
                )));
            }
            Ok(discovery::normalize(dir))
        }
        None => std::env::current_dir().map_err(|error| {
            EngineError::Setup(format!("cannot read the current directory: {error}"))
        }),
    }
}

/// The plugin store, as the host's commands use it.
///
/// Thin on purpose: the kit does the work, and this is where its vocabulary stops. A command says
/// `session.install("pnpm", None)` and never has to know that the plugin store is a crate called
/// `crate-plugin-kit` -- which is also why the field holding it is not public.
impl Session {
    /// The manifest file name this host's plugins use.
    pub fn manifest_name(&self) -> &str {
        &self.kit.config().manifest_name
    }

    /// `pnpm` becomes `pmpx-plugin-pnpm`.
    pub fn normalize_crate_name(&self, name: &str) -> String {
        self.kit.config().normalize_crate_name(name)
    }

    /// Install a plugin by short name, from the registry or a prebuilt asset.
    pub fn install(&self, name: &str, version: Option<&str>) -> Result<crate::store::Installed> {
        Ok(self.kit.install(name, version)?)
    }

    /// Install the plugin in a local checkout.
    pub fn install_from_path(&self, dir: &Path) -> Result<crate::store::Installed> {
        Ok(self.kit.install_from_path(dir)?)
    }

    /// Remove an installed plugin.
    pub fn uninstall(&self, name: &str) -> Result<()> {
        Ok(self.kit.uninstall(name)?)
    }

    /// Rebuild an installed plugin from the source it was installed from.
    pub fn update(&self, name: &str, version: Option<&str>) -> Result<crate::store::Installed> {
        Ok(self.kit.update(name, version)?)
    }

    /// Search crates.io.
    pub fn search(&self, keyword: &str, limit: usize) -> Result<Vec<crate::store::CrateSummary>> {
        Ok(self.kit.search(keyword, limit)?)
    }

    /// What crates.io knows about one crate.
    pub fn view(&self, crate_name: &str) -> Result<Option<crate::store::CrateInfo>> {
        Ok(self.kit.view(crate_name)?)
    }
}
/// How this run hands a started program its stdio.
impl Session {
    /// Where the backend's own output should go.
    pub(crate) fn child_output(&self) -> ChildOutput {
        if self.child_output_on_stderr {
            ChildOutput::OnStderr
        } else {
            ChildOutput::Inherit
        }
    }
}

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

    #[test]
    fn resolve_start_dir_rejects_a_missing_directory() {
        let error = resolve_start_dir(Some(Path::new("definitely/not/here"))).unwrap_err();

        assert!(
            error.message().contains("definitely"),
            "{}",
            error.message()
        );
    }

    #[test]
    fn resolve_start_dir_accepts_an_existing_one() {
        // A directory named the way a person names one -- `tempfile` is not used here because its
        // paths already carry the Windows verbatim prefix, which would hide what this asserts.
        let dir = std::env::temp_dir().join(format!("pmpx-start-dir-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        let resolved = resolve_start_dir(Some(&dir)).unwrap();

        assert!(resolved.is_absolute());
        assert_eq!(
            resolved.file_name(),
            dir.file_name(),
            "a plain path stays the path it was: {resolved:?}"
        );
        assert!(
            !resolved.to_string_lossy().starts_with(r"\\?\"),
            "pmpx must never introduce a Windows verbatim path: {resolved:?}"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }
}