Skip to main content

walker_extras/visitors/
ignore.rs

1//! Ignore discovered content
2
3use std::collections::HashSet;
4use walker_common::utils::url::Urlify;
5
6#[cfg(feature = "sbom-walker")]
7pub(crate) mod sbom {
8    pub use crate::sbom::discover::{DiscoveredContext, DiscoveredSbom, DiscoveredVisitor};
9}
10
11#[cfg(feature = "csaf-walker")]
12pub(crate) mod csaf {
13    pub use crate::csaf::discover::{DiscoveredAdvisory, DiscoveredContext, DiscoveredVisitor};
14}
15
16/// A visitor which can ignore discovered content.
17pub struct Ignore<'s, V> {
18    visitor: V,
19    only: HashSet<&'s str>,
20}
21
22impl<'s, V> Ignore<'s, V> {
23    pub fn new(visitor: V, only: impl IntoIterator<Item = &'s str>) -> Self {
24        Self {
25            visitor,
26            only: HashSet::from_iter(only),
27        }
28    }
29
30    /// check if the item should be ignored
31    ///
32    /// returns `true` if the item should be ignored, `false` otherwise.
33    fn ignore(&self, url: &impl Urlify) -> bool {
34        let url = url.url();
35        let name = url
36            .path_segments()
37            .and_then(|mut path| path.next_back())
38            .unwrap_or(url.path());
39
40        !self.only.is_empty() && !self.only.contains(name)
41    }
42}
43
44#[cfg(feature = "sbom-walker")]
45impl<V: sbom::DiscoveredVisitor> sbom::DiscoveredVisitor for Ignore<'_, V> {
46    type Error = V::Error;
47    type Context = V::Context;
48
49    async fn visit_context(
50        &self,
51        context: &sbom::DiscoveredContext<'_>,
52    ) -> Result<Self::Context, Self::Error> {
53        self.visitor.visit_context(context).await
54    }
55
56    async fn visit_sbom(
57        &self,
58        context: &Self::Context,
59        sbom: sbom::DiscoveredSbom,
60    ) -> Result<(), Self::Error> {
61        if !self.ignore(&sbom) {
62            self.visitor.visit_sbom(context, sbom).await?;
63        }
64
65        Ok(())
66    }
67}
68
69#[cfg(feature = "csaf-walker")]
70impl<V: csaf::DiscoveredVisitor> csaf::DiscoveredVisitor for Ignore<'_, V> {
71    type Error = V::Error;
72    type Context = V::Context;
73
74    async fn visit_context(
75        &self,
76        context: &csaf::DiscoveredContext<'_>,
77    ) -> Result<Self::Context, Self::Error> {
78        self.visitor.visit_context(context).await
79    }
80
81    async fn visit_advisory(
82        &self,
83        context: &Self::Context,
84        csaf: csaf::DiscoveredAdvisory,
85    ) -> Result<(), Self::Error> {
86        if !self.ignore(&csaf) {
87            self.visitor.visit_advisory(context, csaf).await?;
88        }
89
90        Ok(())
91    }
92}