Skip to main content

fallow_core/plugins/
config_dependencies.rs

1//! Dependencies that a config names without a source import: the packages
2//! that config imports credit, and the packages that a config needs installed.
3
4use std::path::{Path, PathBuf};
5
6use super::{PluginResult, config_parser};
7
8/// Credit each package that a config file imports.
9pub(super) fn add_import_referenced_dependencies(
10    result: &mut PluginResult,
11    source: &str,
12    config_path: &Path,
13) {
14    let imports = config_parser::extract_imports(source, config_path);
15    for import in &imports {
16        result
17            .referenced_dependencies
18            .push(crate::resolve::extract_package_name(import));
19    }
20}
21
22/// A package that a config needs installed, although no source file imports
23/// it. A tool loads the package by name, for example a TypeScript language
24/// service plugin, or the config sets a key that needs a companion package.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct RequiredDependency {
27    /// The package name, without a subpath.
28    pub package_name: String,
29    /// The absolute path of the config file.
30    pub config_path: PathBuf,
31    /// 1-based line of the value that names the need.
32    pub line: u32,
33    /// 0-based byte column of that value.
34    pub col: u32,
35    /// True when only a development tool loads the package. A `--production`
36    /// run does not report a development requirement.
37    pub dev_only: bool,
38    /// Other packages that also provide the need. A manifest that lists one
39    /// of them satisfies the requirement, and that package counts as used.
40    pub provided_by: &'static [&'static str],
41}
42
43impl RequiredDependency {
44    /// Build a requirement at byte `offset` of the config `source`.
45    #[must_use]
46    pub(crate) fn at_offset(
47        package_name: String,
48        config_path: &Path,
49        source: &str,
50        offset: usize,
51        dev_only: bool,
52    ) -> Self {
53        let offset = offset.min(source.len());
54        let before = source.get(..offset).unwrap_or_default();
55        let line = before.matches('\n').count() + 1;
56        let line_start = before.rfind('\n').map_or(0, |index| index + 1);
57        Self {
58            package_name,
59            config_path: config_path.to_path_buf(),
60            line: u32::try_from(line).unwrap_or(u32::MAX),
61            col: u32::try_from(offset - line_start).unwrap_or(u32::MAX),
62            dev_only,
63            provided_by: &[],
64        }
65    }
66
67    /// Set the other packages that also provide the need.
68    #[must_use]
69    pub(crate) const fn with_providers(mut self, provided_by: &'static [&'static str]) -> Self {
70        self.provided_by = provided_by;
71        self
72    }
73}