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
//! Ignore discovered content

use std::collections::HashSet;
use walker_common::utils::url::Urlify;

#[cfg(feature = "sbom-walker")]
pub(crate) mod sbom {
    pub use crate::sbom::discover::{DiscoveredContext, DiscoveredSbom, DiscoveredVisitor};
}

#[cfg(feature = "csaf-walker")]
pub(crate) mod csaf {
    pub use crate::csaf::discover::{DiscoveredAdvisory, DiscoveredContext, DiscoveredVisitor};
}

/// A visitor which can ignore discovered content.
pub struct Ignore<'s, V> {
    visitor: V,
    only: HashSet<&'s str>,
}

impl<'s, V> Ignore<'s, V> {
    pub fn new(visitor: V, only: impl IntoIterator<Item = &'s str>) -> Self {
        Self {
            visitor,
            only: HashSet::from_iter(only),
        }
    }

    /// check if the item should be ignored
    ///
    /// returns `true` if the item should be ignored, `false` otherwise.
    fn ignore(&self, url: &impl Urlify) -> bool {
        let url = url.url();
        let name = url
            .path_segments()
            .and_then(|path| path.last())
            .unwrap_or(url.path());

        !self.only.is_empty() && !self.only.contains(name)
    }
}

#[cfg(feature = "sbom-walker")]
impl<'s, V: sbom::DiscoveredVisitor> sbom::DiscoveredVisitor for Ignore<'s, V> {
    type Error = V::Error;
    type Context = V::Context;

    async fn visit_context(
        &self,
        context: &sbom::DiscoveredContext<'_>,
    ) -> Result<Self::Context, Self::Error> {
        self.visitor.visit_context(context).await
    }

    async fn visit_sbom(
        &self,
        context: &Self::Context,
        sbom: sbom::DiscoveredSbom,
    ) -> Result<(), Self::Error> {
        if !self.ignore(&sbom) {
            self.visitor.visit_sbom(context, sbom).await?;
        }

        Ok(())
    }
}

#[cfg(feature = "csaf-walker")]
impl<'s, V: csaf::DiscoveredVisitor> csaf::DiscoveredVisitor for Ignore<'s, V> {
    type Error = V::Error;
    type Context = V::Context;

    async fn visit_context(
        &self,
        context: &csaf::DiscoveredContext<'_>,
    ) -> Result<Self::Context, Self::Error> {
        self.visitor.visit_context(context).await
    }

    async fn visit_advisory(
        &self,
        context: &Self::Context,
        csaf: csaf::DiscoveredAdvisory,
    ) -> Result<(), Self::Error> {
        if !self.ignore(&csaf) {
            self.visitor.visit_advisory(context, csaf).await?;
        }

        Ok(())
    }
}