wdl_cli/
analysis.rs

1//! Facilities for performing a typical analysis using the `wdl-*` crates.
2
3use std::collections::HashSet;
4use std::sync::Arc;
5
6use anyhow::Error;
7use futures::future::BoxFuture;
8use nonempty::NonEmpty;
9use tracing::warn;
10use wdl_analysis::Analyzer;
11use wdl_analysis::DiagnosticsConfig;
12use wdl_analysis::ProgressKind;
13use wdl_analysis::Validator;
14use wdl_lint::Linter;
15
16mod results;
17mod source;
18
19pub use results::AnalysisResults;
20pub use source::Source;
21
22/// The type of the initialization callback.
23type InitCb = Box<dyn Fn() + 'static>;
24
25/// The type of the progress callback.
26type ProgressCb =
27    Box<dyn Fn(ProgressKind, usize, usize) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
28
29/// An analysis.
30pub struct Analysis {
31    /// The set of root nodes to analyze.
32    ///
33    /// Can be files, directories, or URLs.
34    sources: Vec<Source>,
35
36    /// A list of rules to except.
37    exceptions: HashSet<String>,
38
39    /// Whether or not to enable linting.
40    lint: bool,
41
42    /// The initialization callback.
43    init: InitCb,
44
45    /// The progress callback.
46    progress: ProgressCb,
47}
48
49impl Analysis {
50    /// Adds a source to the analysis.
51    pub fn add_source(mut self, source: Source) -> Self {
52        self.sources.push(source);
53        self
54    }
55
56    /// Adds multiple sources to the analysis.
57    pub fn extend_sources(mut self, source: impl IntoIterator<Item = Source>) -> Self {
58        self.sources.extend(source);
59        self
60    }
61
62    /// Adds a rule to the excepted rules list.
63    pub fn add_exception(mut self, rule: impl Into<String>) -> Self {
64        self.exceptions.insert(rule.into());
65        self
66    }
67
68    /// Adds multiple rules to the excepted rules list.
69    pub fn extend_exceptions(mut self, rules: impl IntoIterator<Item = String>) -> Self {
70        self.exceptions.extend(rules);
71        self
72    }
73
74    /// Sets whether linting is enabled.
75    pub fn lint(mut self, value: bool) -> Self {
76        self.lint = value;
77        self
78    }
79
80    /// Sets the initialization callback.
81    pub fn init<F>(mut self, init: F) -> Self
82    where
83        F: Fn() + 'static,
84    {
85        self.init = Box::new(init);
86        self
87    }
88
89    /// Sets the progress callback.
90    pub fn progress<F>(mut self, progress: F) -> Self
91    where
92        F: Fn(ProgressKind, usize, usize) -> BoxFuture<'static, ()> + Send + Sync + 'static,
93    {
94        self.progress = Box::new(progress);
95        self
96    }
97
98    /// Runs the analysis and returns all results (if any exist).
99    pub async fn run(self) -> std::result::Result<AnalysisResults, NonEmpty<Arc<Error>>> {
100        warn_unknown_rules(&self.exceptions);
101        let config = wdl_analysis::Config::default()
102            .with_diagnostics_config(get_diagnostics_config(&self.exceptions));
103
104        (self.init)();
105
106        let validator = Box::new(move || {
107            let mut validator = Validator::default();
108
109            if self.lint {
110                let visitor = get_lint_visitor(&self.exceptions);
111                validator.add_visitor(visitor);
112            }
113
114            validator
115        });
116
117        let mut analyzer = Analyzer::new_with_validator(
118            config,
119            move |_, kind, count, total| (self.progress)(kind, count, total),
120            validator,
121        );
122
123        for source in self.sources {
124            if let Err(error) = source.register(&mut analyzer).await {
125                return Err(NonEmpty::new(Arc::new(error)));
126            }
127        }
128
129        let results = analyzer
130            .analyze(())
131            .await
132            .map_err(|error| NonEmpty::new(Arc::new(error)))?;
133
134        AnalysisResults::try_new(results)
135    }
136}
137
138impl Default for Analysis {
139    fn default() -> Self {
140        Self {
141            sources: Default::default(),
142            exceptions: Default::default(),
143            lint: Default::default(),
144            init: Box::new(|| {}),
145            progress: Box::new(|_, _, _| Box::pin(async {})),
146        }
147    }
148}
149
150/// Warns about any unknown rules.
151fn warn_unknown_rules(exceptions: &HashSet<String>) {
152    let mut names = wdl_analysis::rules()
153        .iter()
154        .map(|rule| rule.id().to_owned())
155        .collect::<Vec<_>>();
156
157    names.extend(wdl_lint::rules().iter().map(|rule| rule.id().to_owned()));
158
159    let mut unknown = exceptions
160        .iter()
161        .filter(|rule| !names.iter().any(|name| name.eq_ignore_ascii_case(rule)))
162        .map(|rule| format!("`{rule}`"))
163        .collect::<Vec<_>>();
164
165    if !unknown.is_empty() {
166        unknown.sort();
167
168        warn!(
169            "ignoring unknown excepted rule{s}: {rules}",
170            s = if unknown.len() == 1 { "" } else { "s" },
171            rules = unknown.join(", ")
172        );
173    }
174}
175
176/// Gets the rules as a diagnositics configuration with the excepted rules
177/// removed.
178fn get_diagnostics_config(exceptions: &HashSet<String>) -> DiagnosticsConfig {
179    DiagnosticsConfig::new(wdl_analysis::rules().into_iter().filter(|rule| {
180        !exceptions
181            .iter()
182            .any(|exception| exception.eq_ignore_ascii_case(rule.id()))
183    }))
184}
185
186/// Gets a lint visitor with the excepted rules removed.
187fn get_lint_visitor(exceptions: &HashSet<String>) -> Linter {
188    Linter::new(wdl_lint::rules().into_iter().filter(|rule| {
189        !exceptions
190            .iter()
191            .any(|exception| exception.eq_ignore_ascii_case(rule.id()))
192    }))
193}