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}
39
40impl RequiredDependency {
41    /// Build a requirement at byte `offset` of the config `source`.
42    #[must_use]
43    pub fn at_offset(
44        package_name: String,
45        config_path: &Path,
46        source: &str,
47        offset: usize,
48        dev_only: bool,
49    ) -> Self {
50        let offset = offset.min(source.len());
51        let before = source.get(..offset).unwrap_or_default();
52        let line = before.matches('\n').count() + 1;
53        let line_start = before.rfind('\n').map_or(0, |index| index + 1);
54        Self {
55            package_name,
56            config_path: config_path.to_path_buf(),
57            line: u32::try_from(line).unwrap_or(u32::MAX),
58            col: u32::try_from(offset - line_start).unwrap_or(u32::MAX),
59            dev_only,
60        }
61    }
62}