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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use crate::RuleConfig;
use ast_grep_core::language::Language;
use globset::{Glob, GlobSet, GlobSetBuilder};
use std::path::Path;

/// RuleBucket stores rules of the same language id.
/// Rules for different language will stay in separate buckets.
pub struct RuleBucket<L: Language> {
  rules: Vec<RuleConfig<L>>,
  lang: L,
}

impl<L: Language> RuleBucket<L> {
  fn new(lang: L) -> Self {
    Self {
      rules: vec![],
      lang,
    }
  }
  pub fn add(&mut self, rule: RuleConfig<L>) {
    self.rules.push(rule);
  }
}

struct ContingentRule<L: Language> {
  rule: RuleConfig<L>,
  files_globs: Option<GlobSet>,
  ignore_globs: Option<GlobSet>,
}

fn build_glob_set(paths: &Vec<String>) -> Result<GlobSet, globset::Error> {
  let mut builder = GlobSetBuilder::new();
  for path in paths {
    builder.add(Glob::new(path)?);
  }
  builder.build()
}

impl<L> TryFrom<RuleConfig<L>> for ContingentRule<L>
where
  L: Language,
{
  type Error = globset::Error;
  fn try_from(rule: RuleConfig<L>) -> Result<Self, Self::Error> {
    let files_globs = rule.files.as_ref().map(build_glob_set).transpose()?;
    let ignore_globs = rule.ignores.as_ref().map(build_glob_set).transpose()?;
    Ok(Self {
      rule,
      files_globs,
      ignore_globs,
    })
  }
}

impl<L: Language> ContingentRule<L> {
  pub fn matches_path<P: AsRef<Path>>(&self, path: P) -> bool {
    if let Some(ignore_globs) = &self.ignore_globs {
      if ignore_globs.is_match(&path) {
        return false;
      }
    }
    if let Some(files_globs) = &self.files_globs {
      return files_globs.is_match(path);
    }
    true
  }
}

/// A collection of rules to run one round of scanning.
/// Rules will be grouped together based on their language, path globbing and pattern rule.
pub struct RuleCollection<L: Language + Eq> {
  // use vec since we don't have many languages
  /// a list of rule buckets grouped by languages.
  /// Tenured rules will always run against a file of that language type.
  tenured: Vec<RuleBucket<L>>,
  /// contingent rules will run against a file if it matches file/ignore glob.
  contingent: Vec<ContingentRule<L>>,
}

impl<L: Language + Eq> RuleCollection<L> {
  pub fn try_new(configs: Vec<RuleConfig<L>>) -> Result<Self, globset::Error> {
    let mut tenured = vec![];
    let mut contingent = vec![];
    for config in configs {
      if config.files.is_none() && config.ignores.is_none() {
        Self::add_tenured_rule(&mut tenured, config);
      } else {
        contingent.push(ContingentRule::try_from(config)?);
      }
    }
    Ok(Self {
      tenured,
      contingent,
    })
  }

  pub fn for_path<P: AsRef<Path>>(&self, path: P) -> Vec<&RuleConfig<L>> {
    let mut all_rules = vec![];
    let Some(lang) = L::from_path(path.as_ref()) else {
      return vec![];
    };
    for rule in &self.tenured {
      if rule.lang == lang {
        all_rules = rule.rules.iter().collect();
        break;
      }
    }
    all_rules.extend(self.contingent.iter().filter_map(|cont| {
      if cont.rule.language == lang && cont.matches_path(path.as_ref()) {
        Some(&cont.rule)
      } else {
        None
      }
    }));
    all_rules
  }

  pub fn get_rule(&self, id: &str) -> Option<&RuleConfig<L>> {
    for rule in &self.tenured {
      for r in &rule.rules {
        if r.id == id {
          return Some(r);
        }
      }
    }
    None
  }

  fn add_tenured_rule(tenured: &mut Vec<RuleBucket<L>>, rule: RuleConfig<L>) {
    let lang = rule.language.clone();
    for bucket in tenured.iter_mut() {
      if bucket.lang == lang {
        bucket.add(rule);
        return;
      }
    }
    let mut bucket = RuleBucket::new(lang);
    bucket.add(rule);
    tenured.push(bucket);
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::from_yaml_string;
  use crate::test::TypeScript;

  fn make_rule(files: &str) -> RuleCollection<TypeScript> {
    let rule_config = from_yaml_string(&format!(
      r"
id: test
message: test rule
severity: info
language: Tsx
rule:
  all: []
{files}"
    ))
    .unwrap()
    .pop()
    .unwrap();
    RuleCollection::try_new(vec![rule_config]).expect("should parse")
  }

  fn assert_match_path(collection: &RuleCollection<TypeScript>, path: &str) {
    let rules = collection.for_path(path);
    assert_eq!(rules.len(), 1);
    assert_eq!(rules[0].id, "test");
  }

  fn assert_ignore_path(collection: &RuleCollection<TypeScript>, path: &str) {
    let rules = collection.for_path(path);
    assert!(rules.is_empty());
  }

  #[test]
  fn test_ignore_rule() {
    let src = r#"
ignores:
  - ./manage.py
  - "**/test*"
"#;
    let collection = make_rule(src);
    assert_ignore_path(&collection, "./manage.py");
    assert_ignore_path(&collection, "./src/test.py");
    assert_match_path(&collection, "./src/app.py");
  }

  #[test]
  fn test_files_rule() {
    let src = r#"
files:
  - ./manage.py
  - "**/test*"
"#;
    let collection = make_rule(src);
    assert_match_path(&collection, "./manage.py");
    assert_match_path(&collection, "./src/test.py");
    assert_ignore_path(&collection, "./src/app.py");
  }

  #[test]
  fn test_files_with_ignores_rule() {
    let src = r#"
files:
  - ./src/**/*.py
ignores:
  - ./src/excluded/*.py
"#;
    let collection = make_rule(src);
    assert_match_path(&collection, "./src/test.py");
    assert_match_path(&collection, "./src/some_folder/test.py");
    assert_ignore_path(&collection, "./src/excluded/app.py");
  }
}