lychee_lib/types/input/
content.rs1use super::source::ResolvedInputSource;
7use crate::ErrorKind;
8use crate::types::FileType;
9use std::borrow::Cow;
10use std::fs;
11use std::path::PathBuf;
12
13#[derive(Debug)]
15pub struct InputContent {
16 pub source: ResolvedInputSource,
18 pub file_type: FileType,
20 pub content: String,
22}
23
24impl InputContent {
25 #[must_use]
26 pub fn from_string(s: &str, file_type: FileType) -> Self {
28 Self {
29 source: ResolvedInputSource::String(Cow::Owned(s.to_owned())),
30 file_type,
31 content: s.to_owned(),
32 }
33 }
34
35 #[must_use]
37 pub fn from_str<S: Into<Cow<'static, str>>>(s: S, file_type: FileType) -> Self {
38 let cow = s.into();
39 Self {
40 source: ResolvedInputSource::String(cow.clone()),
41 file_type,
42 content: cow.into_owned(),
43 }
44 }
45}
46
47impl TryFrom<&PathBuf> for InputContent {
48 type Error = crate::ErrorKind;
49
50 fn try_from(path: &PathBuf) -> std::result::Result<Self, Self::Error> {
51 let input = match fs::read_to_string(path) {
52 Ok(content) => content,
53 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
54 log::warn!(
55 "Skipping file with invalid UTF-8 content: {}",
56 path.display()
57 );
58 return Err(ErrorKind::ReadFileInput(e, path.clone()));
59 }
60 Err(e) => return Err(ErrorKind::ReadFileInput(e, path.clone())),
61 };
62
63 Ok(Self {
64 source: ResolvedInputSource::String(Cow::Owned(input.clone())),
65 file_type: FileType::from(path),
66 content: input,
67 })
68 }
69}