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
use codespan::{ByteIndex, FileId, Files, Span};
use http::uri::{Parts, Uri};
use pulldown_cmark::{Event, OffsetIter, Parser, Tag};
use std::{
cell::RefCell,
fmt::Debug,
path::{Path, PathBuf},
};
#[derive(Debug, Clone, PartialEq)]
pub struct Link {
pub uri: Uri,
pub span: Span,
pub file: FileId,
}
impl Link {
pub(crate) fn parse(
uri: &str,
range: std::ops::Range<usize>,
file: FileId,
) -> Result<Link, http::Error> {
let start = ByteIndex(range.start as u32);
let end = ByteIndex(range.end as u32);
let span = Span::new(start, end);
if let Ok(uri) = uri.parse() {
return Ok(Link { uri, span, file });
}
let mut parts = Parts::default();
parts.path_and_query = Some(uri.parse()?);
let uri = Uri::from_parts(parts)?;
Ok(Link { uri, span, file })
}
pub(crate) fn as_filesystem_path(
&self,
root_dir: &Path,
files: &Files,
) -> PathBuf {
debug_assert!(
self.uri.scheme_str().is_none()
|| self.uri.scheme_str() == Some("file"),
"this operation only makes sense for file URIs"
);
let path = decoded_path(self.uri.path());
if path.is_absolute() {
let mut full_path = root_dir.to_path_buf();
full_path.extend(
path.components()
.filter(|&c| c != std::path::Component::RootDir),
);
full_path
} else {
let parent_dir = match Path::new(files.name(self.file)).parent() {
Some(p) => root_dir.join(p),
None => root_dir.to_path_buf(),
};
let got = parent_dir.join(path);
got
}
}
}
fn decoded_path(percent_encoded_path: &str) -> PathBuf {
percent_encoding::percent_decode_str(percent_encoded_path)
.decode_utf8()
.map(|p| PathBuf::from(p.into_owned()))
.unwrap_or_else(|_| PathBuf::from(percent_encoded_path))
}
pub fn extract_links<I>(
target_files: I,
files: &Files,
) -> (Vec<Link>, Vec<IncompleteLink>)
where
I: IntoIterator<Item = FileId>,
{
let mut links = Vec::new();
let broken_links = RefCell::new(Vec::new());
for file_id in target_files {
let cb = on_broken_links(file_id, &broken_links);
links.extend(Links::new(file_id, files, &cb));
}
(links, broken_links.into_inner())
}
fn on_broken_links<'a>(
file: FileId,
dest: &'a RefCell<Vec<IncompleteLink>>,
) -> impl Fn(&str, &str) -> Option<(String, String)> + 'a {
move |raw, _| {
dest.borrow_mut().push(IncompleteLink {
text: raw.to_string(),
file,
});
None
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct IncompleteLink {
pub text: String,
pub file: FileId,
}
struct Links<'a> {
events: OffsetIter<'a>,
file: FileId,
files: &'a Files,
}
impl<'a> Links<'a> {
fn new(
file: FileId,
files: &'a Files,
cb: &'a dyn Fn(&str, &str) -> Option<(String, String)>,
) -> Links<'a> {
let src = files.source(file);
Links {
events: Parser::new_with_broken_link_callback(
src,
pulldown_cmark::Options::all(),
Some(cb),
)
.into_offset_iter(),
file,
files,
}
}
}
impl<'a> Iterator for Links<'a> {
type Item = Link;
fn next(&mut self) -> Option<Self::Item> {
while let Some((event, range)) = self.events.next() {
match event {
Event::Start(Tag::Link(_, dest, _))
| Event::Start(Tag::Image(_, dest, _)) => {
log::trace!(
"Found \"{}\" at {}..{}",
dest,
range.start,
range.end
);
match Link::parse(&dest, range.clone(), self.file) {
Ok(link) => return Some(link),
Err(e) => {
let location = self
.files
.location(self.file, range.start as u32)
.unwrap();
log::warn!( "Unable to parse \"{}\" as a URI on line {}: {}", dest, location.line, e);
continue;
},
}
},
_ => {},
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detect_the_most_basic_link() {
let src = "This is a link to [nowhere](http://doesnt.exist/)";
let link: Uri = "http://doesnt.exist/".parse().unwrap();
let mut files = Files::new();
let id = files.add("whatever", src);
let got: Vec<Link> = Links::new(id, &files, &|_, _| None).collect();
assert_eq!(got.len(), 1);
assert_eq!(got[0].uri, link);
}
#[test]
fn link_path_with_percent_encoding() {
let uri = "./TechNote%20094%20Accessing%20Wintech%20download%20site%20Rev%20A.pdf";
let should_be = Path::new(
"./TechNote 094 Accessing Wintech download site Rev A.pdf",
);
let got = decoded_path(uri);
assert_eq!(got, should_be);
}
}