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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
mod link_formatter;
pub mod issue_validator;

use regex::{Regex, Captures};

use mdbook::book::{Book, BookItem};
use mdbook::errors::Error;
use mdbook::preprocess::{Preprocessor, PreprocessorContext};
use url::Url;
use crate::link_formatter::LinkFormatter;
use crate::issue_validator::{IssueValidator, issue_from_url, ValidationResult};

pub struct ValidatorProcessorOptions {
    hide_invalid: bool,
    invalid_message: String
}

#[derive(Debug, Eq, PartialEq)]
enum ValidationSection {
    NonValidationSection(String),
    ValidationSection(Vec<Url>, String),
}

pub struct ValidatorProcessor {
    pub validator: Box<dyn IssueValidator>
}

impl Preprocessor for ValidatorProcessor {
    fn name(&self) -> &str { "section-validator" }

    fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book, Error> {
        let options = self.build_options(ctx);

        book.for_each_mut(|item| {
            if let BookItem::Chapter(chapter) = item {
                chapter.content =
                    self.process_chapter(&chapter.content, &options)
            }
        });
        Ok(book)
    }

    fn supports_renderer(&self, renderer: &str) -> bool { renderer == "html" }
}

impl ValidatorProcessor {
    fn build_options(&self, ctx: &PreprocessorContext) -> ValidatorProcessorOptions {
        let mut options = ValidatorProcessorOptions {
            hide_invalid: true,
            invalid_message: "🚨 Warning, this content is out of date and is included for historical reasons. 🚨".to_string()
        };

        if let Some(config) = ctx.config.get_preprocessor("section-validator") {
            if let Some(toml::value::Value::Boolean(hide_closed)) = config.get("hide_invalid") {
                options.hide_invalid = *hide_closed;
            }
            if let Some(toml::value::Value::String(message)) = config.get("invalid_message") {
                options.invalid_message = message.to_string();
            }
        }

        options
    }

    fn process_chapter(
        &self,
        raw_content: &str,
        options: &ValidatorProcessorOptions
    ) -> String {
        let mut content = String::new();
        for section in ValidatorProcessor::validation_sections(raw_content) {
            match section {
                ValidationSection::NonValidationSection(text) => {
                    content.push_str(&text);
                },
                ValidationSection::ValidationSection(links, text) => {
                    let validation_result = self.is_section_valid(&links);
                    if options.hide_invalid && validation_result == ValidationResult::NoLongerValid {
                        continue;
                    }
                    content.push_str(&*format!("<div class=\"validated-content\" links=\"{}\">\n\n", ValidatorProcessor::links_joined(&links)));
                    if validation_result == ValidationResult::NoLongerValid {
                        content.push_str(&*options.invalid_message);
                    } else {
                        let mut is_or_are = "is";
                        if links.len() != 1 {
                            is_or_are = "are";
                        }
                        content.push_str(&*format!("⚠️ This is only valid while {} {} open", LinkFormatter::markdown_many(&links), is_or_are));
                    }
                    content.push_str(&text);
                    content.push_str("\n</div>");
                }
            }
        }
        content
    }

    fn validation_sections(raw_content: &str) -> Vec<ValidationSection> {
        let section_regex = Regex::new(r"(?m)^!!!(.+)$(?s)(.+?)(?-s)^!!!$").unwrap();

        let captures: Vec<Captures> = section_regex.captures_iter(&raw_content).collect();
        let mut sections: Vec<ValidationSection> = Vec::new();

        if captures.is_empty() {
            return vec!(ValidationSection::NonValidationSection(raw_content.to_string()));
        }

        let mut last_endpoint: usize = 0;
        for capture in captures {
            let mat = capture.get(0).unwrap();
            let start = mat.start();

            if start - last_endpoint != 0 {
                sections.push(ValidationSection::NonValidationSection(raw_content[last_endpoint..start].to_string()));
            }

            last_endpoint = mat.end();

            sections.push(ValidationSection::ValidationSection(
                ValidatorProcessor::links_to_check(capture.get(1).unwrap().as_str()),
                capture.get(2).unwrap().as_str().to_string()
            ))
        }


        if raw_content.len() > last_endpoint {
            sections.push(ValidationSection::NonValidationSection(raw_content[last_endpoint..raw_content.len()].to_string()));
        }

        return sections;
    }

    fn links_to_check(links: &str) -> Vec<Url> {
        links.split(",").map(|text| Url::parse(text).unwrap()).collect()
    }

    fn links_joined(links: &Vec<Url>) -> String {
        let links_strs: Vec<String> = links.into_iter().map(|url| url.as_str().to_string()).collect();
        links_strs.join(",")
    }

    fn is_section_valid(&self, links: &Vec<Url>) ->ValidationResult {
        links.into_iter()
            .map(|u| issue_from_url(u))
            .map(|issue| self.validator.validate(&issue))
            .reduce(|a, b|
            if a == ValidationResult::StillValid && b == ValidationResult::StillValid { a }
            else { ValidationResult::NoLongerValid }
        ).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::IssueValidator;
    use super::ValidatorProcessor;
    use super::ValidationSection;
    use url::Url;
    use crate::issue_validator::{Issue, ValidationResult};
    use crate::ValidatorProcessorOptions;

    #[test]
    fn test_validation_sections_single_link() {
        let content = "whatever
!!!https://github.com/example/example/issues/1

some content to be conditionally included.

!!!

other content";

        let sections: Vec<ValidationSection> = ValidatorProcessor::validation_sections(&content);

        assert_eq!(sections.len(), 3);
        assert_eq!(sections.get(0).unwrap(), &ValidationSection::NonValidationSection("whatever\n".to_string()));
        assert_eq!(
            sections.get(1).unwrap(),
            &ValidationSection::ValidationSection(
                vec![Url::parse("https://github.com/example/example/issues/1").unwrap()],
                "\n\nsome content to be conditionally included.\n\n".to_string()
            )
        );
        assert_eq!(sections.get(2).unwrap(), &ValidationSection::NonValidationSection("\n\nother content".to_string()));
    }

    #[test]
    fn test_validation_sections_multiple() {
        let content = "!!!https://github.com/example/example/issues/1

some content to be conditionally included.

!!!

other content

!!!https://github.com/example/example/issues/1,https://github.com/example/example/issues/2

other content to be conditionally included.

!!!";

        let sections: Vec<ValidationSection> = ValidatorProcessor::validation_sections(&content);

        assert_eq!(sections.len(), 3);
        assert_eq!(
            sections.get(0).unwrap(),
            &ValidationSection::ValidationSection(
                vec![Url::parse("https://github.com/example/example/issues/1").unwrap()],
                "\n\nsome content to be conditionally included.\n\n".to_string()
            )
        );
        assert_eq!(sections.get(1).unwrap(), &ValidationSection::NonValidationSection("\n\nother content\n\n".to_string()));
        assert_eq!(
            sections.get(2).unwrap(),
            &ValidationSection::ValidationSection(
                vec![
                    Url::parse("https://github.com/example/example/issues/1").unwrap(),
                    Url::parse("https://github.com/example/example/issues/2").unwrap()
                ],
                "\n\nother content to be conditionally included.\n\n".to_string()
            )
        );
    }

    #[test]
    fn test_content_all_valid_still_included_with_warning() {
        let content = "whatever
!!!https://github.com/example/example/issues/1

some content to be conditionally included.

!!!

other content
        ";

        let validator = FakeIssueValidator { validate_behavior: ValidateBehavior::AllValid };

        let processor = ValidatorProcessor { validator: Box::new(validator) };

        let options = ValidatorProcessorOptions { hide_invalid: true, invalid_message: "".to_string() };

        let received_chapter = processor.process_chapter(
            content,
            &options
        );

        let expected_chapter = "whatever
<div class=\"validated-content\" links=\"https://github.com/example/example/issues/1\">

⚠️ This is only valid while [example/example#1](https://github.com/example/example/issues/1) is open ⚠️

some content to be conditionally included.


</div>

other content
        ";
        assert_eq!(received_chapter, expected_chapter.to_string());
    }

    #[test]
    fn tset_content_none_valid_content_not_included() {
        let content = "whatever
!!!https://github.com/example/example/issues/1

some content to be conditionally included.

!!!

other content
        ";

        let validator = FakeIssueValidator { validate_behavior: ValidateBehavior::NoneValid };

        let processor = ValidatorProcessor { validator: Box::new(validator) };

        let received_chapter = processor.process_chapter(
            content,
            &ValidatorProcessorOptions {
                hide_invalid: true,
                invalid_message: "🚨 Warning, this content is out of date and is included for historical reasons. 🚨".to_string()
            }
        );

        let expected_chapter = "whatever


other content
        ";
        assert_eq!(received_chapter, expected_chapter.to_string());
    }

    #[test]
    fn test_content_none_valid_content_still_included_with_warning() {
        let content = "whatever
!!!https://github.com/example/example/issues/1

some content to be conditionally included.

!!!

other content
        ";

        let validator = FakeIssueValidator { validate_behavior: ValidateBehavior::NoneValid };

        let processor = ValidatorProcessor { validator: Box::new(validator) };

        let received_chapter = processor.process_chapter(
            content,
            &ValidatorProcessorOptions {
                hide_invalid: false,
                invalid_message: "🚨 Warning, this content is out of date and is included for historical reasons. 🚨".to_string()
            }
        );

        let expected_chapter = "whatever
<div class=\"validated-content\" links=\"https://github.com/example/example/issues/1\">

🚨 Warning, this content is out of date and is included for historical reasons. 🚨

some content to be conditionally included.


</div>

other content
        ";
        assert_eq!(received_chapter, expected_chapter.to_string());
    }

    enum ValidateBehavior {
        AllValid,
        NoneValid
    }

    struct FakeIssueValidator {
        validate_behavior: ValidateBehavior
    }

    impl IssueValidator for FakeIssueValidator {
        fn validate(&self, _link: &Issue) -> ValidationResult {
            match &self.validate_behavior {
                ValidateBehavior::NoneValid => ValidationResult::NoLongerValid,
                ValidateBehavior::AllValid => ValidationResult::StillValid
            }
        }
    }
}