Skip to content

Commit

Permalink
Move remap code to remap; add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mre committed May 15, 2022
1 parent c7aa7ca commit 7c2e783
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 11 deletions.
13 changes: 3 additions & 10 deletions lychee-lib/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,17 +413,10 @@ impl Client {
/// Remap URI using the client-defined remap patterns
#[must_use]
pub fn remap(&self, uri: Uri) -> Result<Uri> {
let remaps = match self.remaps {
Some(ref remaps) => remaps,
None => return Ok(uri),
};
let mut uri = uri;
for (pattern, new_url) in remaps {
if pattern.is_match(uri.as_str()) {
uri = Uri::try_from(new_url.to_owned())?
}
match self.remaps {
Some(ref remaps) => remaps.remap(uri),
None => Ok(uri),
}
Ok(uri)
}

/// Returns whether the given `uri` should be ignored from checking.
Expand Down
69 changes: 68 additions & 1 deletion lychee-lib/src/remap.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use std::ops::Index;

use crate::Result;
use regex::Regex;
use reqwest::Url;

use crate::Uri;

/// Remaps allow mapping from a URI pattern to a different URI
///
/// Some use-cases are
Expand All @@ -11,4 +16,66 @@ use reqwest::Url;
/// large set of regular expressions has a performance impact. Also there are no
/// constraints on the URI mapping, so the rules might contradict with each
/// other.
pub type Remaps = Vec<(Regex, Url)>;
#[derive(Debug, Clone)]
pub struct Remaps(Vec<(Regex, Url)>);

impl Remaps {
/// Create a new remapper
pub fn new(patterns: Vec<(Regex, Url)>) -> Self {
Self(patterns)
}

/// Remap URI using the client-defined remap patterns
#[must_use]
pub fn remap(&self, uri: Uri) -> Result<Uri> {
let mut uri = uri;
for (pattern, new_url) in &self.0 {
if pattern.is_match(uri.as_str()) {
uri = Uri::try_from(new_url.to_owned())?
}
}
Ok(uri)
}

/// Get the number of defined remap rules
pub fn len(&self) -> usize {
self.0.len()
}
}

impl Index<usize> for Remaps {
type Output = (Regex, Url);

fn index(&self, index: usize) -> &(regex::Regex, url::Url) {
&self.0[index]
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_remap() {
let pattern = Regex::new("https://example.com").unwrap();
let uri = Uri::try_from("http://127.0.0.1:8080").unwrap();
let remaps = Remaps::new(vec![(pattern, uri.clone().url)]);

let input = Uri::try_from("https://example.com").unwrap();
let remapped = remaps.remap(input).unwrap();

assert_eq!(remapped, uri);
}

#[test]
fn test_remap_path() {
let pattern = Regex::new("../../issues").unwrap();
let uri = Uri::try_from("https://example.com").unwrap();
let remaps = Remaps::new(vec![(pattern, uri.clone().url)]);

let input = Uri::try_from("../../issues").unwrap();
let remapped = remaps.remap(input).unwrap();

assert_eq!(remapped, uri);
}
}

0 comments on commit 7c2e783

Please sign in to comment.