tokenize_cli/
file_data.rs

1use std::{
2    fs,
3    io::{self, Write},
4    path::{Path, PathBuf},
5};
6
7#[derive(Debug)]
8pub struct FileData {
9    path: PathBuf,
10    content: Vec<u8>,
11}
12
13impl FileData {
14    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
15        let path = path.as_ref();
16        let content = fs::read(path)?;
17
18        Ok(Self {
19            path: path.to_path_buf(),
20            content,
21        })
22    }
23
24    pub fn write<W: Write>(&self, buf: &mut W) -> io::Result<()> {
25        writeln!(
26            buf,
27            "-------- {} --------\n```{}",
28            self.path.display(),
29            self.extension()
30        )?;
31        buf.write_all(&self.content)?;
32        writeln!(buf, "```")
33    }
34
35    #[must_use]
36    pub fn extension(&self) -> &str {
37        self.path
38            .extension()
39            .and_then(|s| s.to_str())
40            .unwrap_or_default()
41    }
42}