-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
input.rs
324 lines (294 loc) · 10.6 KB
/
input.rs
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
use crate::types::FileType;
use crate::Result;
use async_stream::try_stream;
use futures::stream::Stream;
use glob::glob_with;
use jwalk::WalkDir;
use reqwest::Url;
use serde::Serialize;
use shellexpand::tilde;
use std::fmt::Display;
use std::fs;
use std::path::{Path, PathBuf};
use tokio::io::{stdin, AsyncReadExt};
const STDIN: &str = "-";
// Check the extension of the given path against the list of known/accepted
// file extensions
fn valid_extension(p: &Path) -> bool {
matches!(FileType::from(p), FileType::Markdown | FileType::Html)
}
#[derive(Debug)]
/// Encapsulates the content for a given input
pub struct InputContent {
/// Input source
pub source: InputSource,
/// File type of given input
pub file_type: FileType,
/// Raw UTF-8 string content
pub content: String,
}
impl InputContent {
#[must_use]
/// Create an instance of `InputContent` from an input string
pub fn from_string(s: &str, file_type: FileType) -> Self {
// TODO: consider using Cow (to avoid one .clone() for String types)
Self {
source: InputSource::String(s.to_owned()),
file_type,
content: s.to_owned(),
}
}
}
impl TryFrom<&PathBuf> for InputContent {
type Error = crate::ErrorKind;
fn try_from(path: &PathBuf) -> std::result::Result<Self, Self::Error> {
let input = fs::read_to_string(&path)?;
Ok(Self {
source: InputSource::String(input.clone()),
file_type: FileType::from(path),
content: input,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Input types which lychee supports
pub enum InputSource {
/// URL (of HTTP/HTTPS scheme).
RemoteUrl(Box<Url>),
/// Unix shell-style glob pattern.
FsGlob {
/// The glob pattern matching all input files
pattern: String,
/// Don't be case sensitive when matching files against a glob
ignore_case: bool,
},
/// File path.
FsPath(PathBuf),
/// Standard Input.
Stdin,
/// Raw string input.
String(String),
}
// Custom serialization for enum is needed
// Otherwise we get "key must be a string" when using the JSON writer
// Related: https://github.com/serde-rs/json/issues/45
impl Serialize for InputSource {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl Display for InputSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::RemoteUrl(url) => url.as_str(),
Self::FsGlob { pattern, .. } => pattern,
Self::FsPath(path) => path.to_str().unwrap_or_default(),
Self::Stdin => "stdin",
Self::String(s) => s,
})
}
}
/// Lychee Input with optional file hint for parsing
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Input {
/// Origin of input
pub source: InputSource,
/// Hint to indicate which extractor to use
pub file_type_hint: Option<FileType>,
}
impl Input {
#[must_use]
/// Construct a new `Input` source. In case the input is a `glob` pattern,
/// `glob_ignore_case` decides whether matching files against the `glob` is
/// case-insensitive or not
pub fn new(value: &str, file_type_hint: Option<FileType>, glob_ignore_case: bool) -> Self {
let source = if value == STDIN {
InputSource::Stdin
} else if let Ok(url) = Url::parse(value) {
InputSource::RemoteUrl(Box::new(url))
} else {
// this seems to be the only way to determine if this is a glob pattern
let is_glob = glob::Pattern::escape(value) != value;
if is_glob {
InputSource::FsGlob {
pattern: value.to_owned(),
ignore_case: glob_ignore_case,
}
} else {
InputSource::FsPath(value.into())
}
};
Self {
source,
file_type_hint,
}
}
#[allow(clippy::missing_panics_doc)]
/// Retrieve the contents from the input
///
/// # Errors
///
/// Returns an error if the contents can not be retrieved
/// because of an underlying I/O error (e.g. an error while making a
/// network request or retrieving the contents from the file system)
pub async fn get_contents(
self,
skip_missing: bool,
) -> impl Stream<Item = Result<InputContent>> {
try_stream! {
match self.source {
InputSource::RemoteUrl(ref url) => {
let contents: InputContent = Self::url_contents(url).await?;
yield contents;
},
InputSource::FsGlob {
ref pattern,
ignore_case,
} => {
for await content in Self::glob_contents(pattern, ignore_case).await {
let content = content?;
yield content;
}
}
InputSource::FsPath(ref path) => {
if path.is_dir() {
for entry in WalkDir::new(path).skip_hidden(true)
.process_read_dir(|_, _, _, children| {
children.retain(|child| {
let entry = match child.as_ref() {
Ok(x) => x,
Err(_) => return true,
};
let file_type = entry.file_type();
if file_type.is_dir() {
// Required for recursion
return true;
}
if file_type.is_symlink() {
return false;
}
if !file_type.is_file() {
return false;
}
return valid_extension(&entry.path());
});
}) {
let entry = entry?;
if entry.file_type().is_dir() {
continue;
}
let content = Self::path_content(entry.path()).await?;
yield content
}
} else {
let content = Self::path_content(path).await;
match content {
Err(_) if skip_missing => (),
Err(e) => Err(e)?,
Ok(content) => yield content,
};
}
},
InputSource::Stdin => {
let content = Self::stdin_content(self.file_type_hint).await?;
yield content;
},
InputSource::String(ref s) => {
let content = Self::string_content(s, self.file_type_hint);
yield content;
},
}
}
}
async fn url_contents(url: &Url) -> Result<InputContent> {
// Assume HTML for default paths
let file_type = if url.path().is_empty() || url.path() == "/" {
FileType::Html
} else {
FileType::from(url.as_str())
};
let res = reqwest::get(url.clone()).await?;
let input_content = InputContent {
source: InputSource::RemoteUrl(Box::new(url.clone())),
file_type,
content: res.text().await?,
};
Ok(input_content)
}
async fn glob_contents(
path_glob: &str,
ignore_case: bool,
) -> impl Stream<Item = Result<InputContent>> + '_ {
let glob_expanded = tilde(&path_glob).to_string();
let mut match_opts = glob::MatchOptions::new();
match_opts.case_sensitive = !ignore_case;
try_stream! {
for entry in glob_with(&glob_expanded, match_opts)? {
match entry {
Ok(path) => {
// Directories can have a suffix which looks like
// a file extension (like `foo.html`). This can lead to
// unexpected behavior with glob patterns like
// `**/*.html`. Therefore filter these out.
// See https://github.com/lycheeverse/lychee/pull/262#issuecomment-913226819
if path.is_dir() {
continue;
}
let content: InputContent = Self::path_content(&path).await?;
yield content;
}
Err(e) => println!("{e:?}"),
}
}
}
}
/// Get the input content of a given path
/// # Errors
///
/// Will return `Err` if file contents can't be read
pub async fn path_content<P: Into<PathBuf> + AsRef<Path> + Clone>(
path: P,
) -> Result<InputContent> {
let content = tokio::fs::read_to_string(&path)
.await
.map_err(|e| (path.clone().into(), e))?;
let input_content = InputContent {
file_type: FileType::from(path.as_ref()),
source: InputSource::FsPath(path.into()),
content,
};
Ok(input_content)
}
async fn stdin_content(file_type_hint: Option<FileType>) -> Result<InputContent> {
let mut content = String::new();
let mut stdin = stdin();
stdin.read_to_string(&mut content).await?;
let input_content = InputContent {
source: InputSource::Stdin,
file_type: file_type_hint.unwrap_or_default(),
content,
};
Ok(input_content)
}
fn string_content(s: &str, file_type_hint: Option<FileType>) -> InputContent {
InputContent::from_string(s, file_type_hint.unwrap_or_default())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_extension() {
assert!(valid_extension(Path::new("file.md")));
assert!(valid_extension(Path::new("file.markdown")));
assert!(valid_extension(Path::new("file.html")));
assert!(valid_extension(Path::new("file.htm")));
assert!(valid_extension(Path::new("file.HTM")));
assert!(!valid_extension(Path::new("file.txt")));
assert!(!valid_extension(Path::new("file")));
}
}