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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use spinners::{Spinner, Spinners};

use crate::finder::{Finder, UrlFinder};
use crate::validator::{ValidateUrls, ValidationResult, Validator};
use std::cmp::Ordering;
use std::io;
use std::path::Path;
use std::time::Duration;

pub mod finder;
pub mod validator;

pub struct UrlsUp {
    finder: Finder,
    validator: Validator,
}

pub struct UrlsUpOptions {
    // White listed URLs to allow being broken
    pub white_list: Option<Vec<String>>,
    // Timeout for getting a response
    pub timeout: Duration,
    // HTTP status codes to allow being present
    pub allowed_status_codes: Option<Vec<u16>>,
    // Thread count
    pub thread_count: usize,
    // Allow requests to time out
    pub allow_timeout: bool,
}

#[derive(Debug, Eq, Clone)]
pub struct UrlLocation {
    // The URL that was found
    pub url: String,
    // Line number where URL was found
    pub line: u64,
    // Name of file where URL was found
    pub file_name: String,
}

impl Ord for UrlLocation {
    fn cmp(&self, other: &Self) -> Ordering {
        self.url.cmp(&other.url)
    }
}

impl PartialOrd for UrlLocation {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for UrlLocation {
    fn eq(&self, other: &Self) -> bool {
        if cfg!(test) {
            // In tests we want to compare all properties
            (&self.url, &self.file_name, self.line) == (&other.url, &other.file_name, other.line)
        } else {
            self.url == other.url
        }
    }
}

impl UrlsUp {
    pub fn new(finder: Finder, validator: Validator) -> Self {
        Self { finder, validator }
    }

    pub async fn run(
        &self,
        paths: Vec<&Path>,
        opts: UrlsUpOptions,
    ) -> io::Result<Vec<ValidationResult>> {
        println!("> Using threads: {}", &opts.thread_count);
        println!("> Using timeout (seconds): {}", &opts.timeout.as_secs());
        println!("> Allow timeout: {}", &opts.allow_timeout);

        if let Some(white_list) = &opts.white_list {
            println!("> Ignoring white listed URL(s)");
            for (i, url) in white_list.iter().enumerate() {
                println!("{:4}. {}", i + 1, url.to_string());
            }
        }

        if let Some(allowed) = &opts.allowed_status_codes {
            println!("> Allowing HTTP status codes");
            for (i, status_code) in allowed.iter().enumerate() {
                println!("{:4}. {}", i + 1, status_code.to_string());
            }
        }

        let files_singular_plural = match &paths.len() {
            1 => "file",
            _ => "files",
        };

        println!(
            "> Will check URLs in {} {}",
            paths.len(),
            files_singular_plural
        );
        for (i, file) in paths.iter().enumerate() {
            println!("{:4}. {}", i + 1, file.display());
        }

        println!(); // Make output more readable

        let spinner_find_urls = self.spinner_start("Finding URLs in files...".to_string());

        // Find URLs from files
        let mut url_locations = self.finder.find_urls(paths)?;

        // Apply white list
        if let Some(white_list) = &opts.white_list {
            url_locations = self.apply_white_list(url_locations, white_list);
        }

        // Save URL count to avoid having to clone URL list later
        let url_count = url_locations.len();

        // Deduplicate URLs to avoid duplicate work
        let dedup_urls = self.dedup(url_locations);

        if let Some(sp) = spinner_find_urls {
            sp.stop();
        }

        println!(
            "\n\n> Found {} unique URL(s), {} in total",
            &dedup_urls.len(),
            url_count
        );

        for (i, ul) in dedup_urls.iter().enumerate() {
            println!("{:4}. {}", i + 1, ul.url.to_string());
        }

        println!(); // Make output more readable

        let validation_spinner = self.spinner_start("Checking URLs...".into());

        // Check URLs
        let mut non_ok_urls: Vec<ValidationResult> = self
            .validator
            .validate_urls(dedup_urls, &opts)
            .await
            .into_iter()
            .filter(ValidationResult::is_not_ok)
            .collect();

        if let Some(allowed) = &opts.allowed_status_codes {
            non_ok_urls = self.filter_allowed_status_codes(non_ok_urls, allowed.clone());
        }

        if opts.allow_timeout {
            non_ok_urls = self.filter_timeouts(non_ok_urls);
        }

        if let Some(sp) = validation_spinner {
            sp.stop();
        }

        Ok(non_ok_urls)
    }

    fn apply_white_list(
        &self,
        url_locations: Vec<UrlLocation>,
        white_list: &[String],
    ) -> Vec<UrlLocation> {
        url_locations
            .into_iter()
            .filter(|ul| !white_list.contains(&ul.url))
            .filter(|ul| {
                // If URL starts with any white listed URL
                for white_listed_url in white_list.iter() {
                    if ul.url.starts_with(white_listed_url) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn filter_allowed_status_codes(
        &self,
        validation_results: Vec<ValidationResult>,
        allowed_status_codes: Vec<u16>,
    ) -> Vec<ValidationResult> {
        validation_results
            .into_iter()
            .filter(|vr| {
                if let Some(status_code) = vr.status_code {
                    if allowed_status_codes.contains(&status_code) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn filter_timeouts(&self, validation_results: Vec<ValidationResult>) -> Vec<ValidationResult> {
        validation_results
            .into_iter()
            .filter(|vr| {
                if let Some(description) = &vr.description {
                    if description == "operation timed out" {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn dedup(&self, mut list: Vec<UrlLocation>) -> Vec<UrlLocation> {
        list.sort();
        list.dedup();
        list
    }

    fn spinner_start(&self, msg: String) -> Option<Spinner> {
        if term::stdout().is_some() {
            Some(Spinner::new(Spinners::Dots, msg))
        } else {
            println!("{}", msg);
            None
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(non_snake_case)]

    use super::*;

    #[test]
    fn test_dedup() {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let duplicate = vec![
            UrlLocation {
                url: "duplicate".to_string(),
                line: 99,
                file_name: "this-file-name-dup".to_string(),
            },
            UrlLocation {
                url: "duplicate".to_string(),
                line: 99,
                file_name: "this-file-name-dup".to_string(),
            },
            UrlLocation {
                url: "unique-1".to_string(),
                line: 10,
                file_name: "this-file-name-1".to_string(),
            },
            UrlLocation {
                url: "unique-2".to_string(),
                line: 20,
                file_name: "this-file-name-2".to_string(),
            },
        ];

        let actual = urls_up.dedup(duplicate);
        let expected = vec![
            UrlLocation {
                url: "duplicate".to_string(),
                line: 99,
                file_name: "this-file-name-dup".to_string(),
            },
            UrlLocation {
                url: "unique-1".to_string(),
                line: 10,
                file_name: "this-file-name-1".to_string(),
            },
            UrlLocation {
                url: "unique-2".to_string(),
                line: 20,
                file_name: "this-file-name-2".to_string(),
            },
        ];

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_apply_white_list__filters_out_white_listed_urls() {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let urls = vec![
            UrlLocation {
                url: "http://should-keep.com".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
            },
            UrlLocation {
                url: "http://should-ignore.com".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
            },
            UrlLocation {
                url: "http://should-also-ignore.com/something/something-else".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
            },
        ];

        let white_list: Vec<String> =
            vec!["http://should-ignore.com", "http://should-also-ignore.com"]
                .into_iter()
                .map(String::from)
                .collect();

        let actual = urls_up.apply_white_list(urls, &white_list);
        let expected = vec![UrlLocation {
            url: "http://should-keep.com".to_string(),
            line: 0,
            file_name: "arbitrary".to_string(),
        }];

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_filter_allowed_status_codes__removes_allowed_status_codes() {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let vr1 = ValidationResult {
            url: "keep-this".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: Some(200),
            description: None,
        };
        let vr2 = ValidationResult {
            url: "keep-this-2".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: None,
            description: Some("arbitrary".to_string()),
        };
        let vr3 = ValidationResult {
            url: "remove-this".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: Some(404),
            description: None,
        };
        let actual = urls_up.filter_allowed_status_codes(vec![vr1, vr2, vr3], vec![404]);
        let expected = vec![
            ValidationResult {
                url: "keep-this".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
                status_code: Some(200),
                description: None,
            },
            ValidationResult {
                url: "keep-this-2".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
                status_code: None,
                description: Some("arbitrary".to_string()),
            },
        ];

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_filter_timeouts__removes_timeouts() {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let vr1 = ValidationResult {
            url: "keep-this".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: Some(200),
            description: None,
        };
        let vr2 = ValidationResult {
            url: "keep-this-2".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: None,
            description: Some("arbitrary".to_string()),
        };
        let vr3 = ValidationResult {
            url: "remove-this".to_string(),
            line: 0, // arbitrary
            file_name: "arbitrary".to_string(),
            status_code: None,
            description: Some("operation timed out".to_string()),
        };
        let actual = urls_up.filter_timeouts(vec![vr1, vr2, vr3]);
        let expected = vec![
            ValidationResult {
                url: "keep-this".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
                status_code: Some(200),
                description: None,
            },
            ValidationResult {
                url: "keep-this-2".to_string(),
                line: 0, // arbitrary
                file_name: "arbitrary".to_string(),
                status_code: None,
                description: Some("arbitrary".to_string()),
            },
        ];

        assert_eq!(actual, expected)
    }
}

#[cfg(test)]
mod it_tests {
    #![allow(non_snake_case)]

    use super::*;
    use mockito::mock;
    use std::io::Write;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[tokio::test]
    async fn test_run__has_no_issues() -> TestResult {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.run(vec![file.path()], opts).await?;

        assert!(actual.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn test_run__has_issues() -> TestResult {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/404").with_status(404).create();
        let endpoint = mockito::server_url() + "/404";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let result = urls_up.run(vec![file.path()], opts).await?;

        assert!(!result.is_empty());

        let actual = result.first().unwrap();

        assert_eq!(actual.description, None);
        assert_eq!(actual.url, "http://127.0.0.1:1234/404".to_string());
        assert_eq!(actual.status_code, Some(404));
        Ok(())
    }

    #[tokio::test]
    async fn test_run__issues_when_timeout_reached() -> TestResult {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_nanos(1), // Use very small timeout
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let result = urls_up.run(vec![file.path()], opts).await?;

        assert!(!result.is_empty());

        let actual = result.first().unwrap();

        assert_eq!(actual.description, Some("operation timed out".to_string()));
        assert_eq!(actual.url, "http://127.0.0.1:1234/200".to_string());
        assert_eq!(actual.status_code, None);
        Ok(())
    }

    #[tokio::test]
    async fn test_run__no_issues_when_timeout_reached_and_allow_timeout() -> TestResult {
        let urls_up = UrlsUp::new(Finder::default(), Validator::default());
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_nanos(1), // Use very small timeout
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: true,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.run(vec![file.path()], opts).await?;

        assert!(actual.is_empty());
        Ok(())
    }
}