Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle absolute paths #91

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
#### Added

* If a URL points to a directory, check if index.html exists in that directory. [PR#90]
* Treat absolute paths as absolute with respect to the `base_url`, not with respect to the file system. [PR#91]

[PR#90]: https://github.com/deadlinks/cargo-deadlinks/pull/90
[PR#91]: https://github.com/deadlinks/cargo-deadlinks/pull/91

#### Fixes

Expand Down
45 changes: 43 additions & 2 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ fn parse_a_hrefs(handle: &Handle, base_url: &Url, urls: &mut HashSet<Url>) {
.iter()
.find(|attr| &attr.name.local == "href")
{
let val = &attr.value;
if let Ok(link) = base_url.join(val) {
let mut val = attr.value.clone();
// Treat absolute paths as absolute with respect to the `base_url`, not with respect to the file system.
if attr.value.starts_with('/') {
val.pop_front_char();
}

if let Ok(link) = base_url.join(&val) {
debug!("link is {:?}", link);
urls.insert(link);
} else {
Expand All @@ -51,3 +56,39 @@ fn parse_a_hrefs(handle: &Handle, base_url: &Url, urls: &mut HashSet<Url>) {
parse_a_hrefs(&child, base_url, urls);
}
}

#[cfg(test)]
mod test {
use html5ever::parse_document;
use html5ever::{rcdom::RcDom, tendril::TendrilSink};
use std::collections::HashSet;
use url::Url;

use super::parse_a_hrefs;

#[test]
fn test_parse_a_hrefs() {
let html = r#"
<!DOCTYPE html>
<html>
<body>
<a href="a.html">a</a>
<a href="/b/c.html">a</a>
</body>
</html>
"#;

let dom = parse_document(RcDom::default(), Default::default())
.from_utf8()
.read_from(&mut html.as_bytes())
.unwrap();

let base_url = Url::from_directory_path("/base").unwrap();

let mut urls = HashSet::new();
parse_a_hrefs(&dom.document, &base_url, &mut urls);

assert!(urls.contains(&Url::from_file_path("/base/a.html").unwrap()));
assert!(urls.contains(&Url::from_file_path("/base/b/c.html").unwrap()));
}
}