lychee_lib/types/input/
content.rs

1//! Input content representation and construction.
2//!
3//! The `InputContent` type represents the actual content extracted from various
4//! input sources, along with metadata about the source and file type.
5
6use super::source::ResolvedInputSource;
7use crate::ErrorKind;
8use crate::types::FileType;
9use std::borrow::Cow;
10use std::fs;
11use std::path::PathBuf;
12
13/// Encapsulates the content for a given input
14#[derive(Debug)]
15pub struct InputContent {
16    /// Input source
17    pub source: ResolvedInputSource,
18    /// File type of given input
19    pub file_type: FileType,
20    /// Raw UTF-8 string content
21    pub content: String,
22}
23
24impl InputContent {
25    #[must_use]
26    /// Create an instance of `InputContent` from an input string
27    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    /// Create an instance of `InputContent` from an input string
36    #[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}