Skip to main content

sokf_core/source/
text.rs

1//! This module reads one file as UTF-8, records the line ending of its first
2//! line, normalises the text to line feed (LF), computes the file key, and splits the
3//! frontmatter from the body.
4
5use std::{fs, path::Path, time::UNIX_EPOCH};
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use tramlines_md::markdown::{Split, split_frontmatter};
10
11use super::fnv1a64;
12use crate::{Error, RepoPath, RepoRoot, Result};
13
14/// `LineEnding` is the line ending of a file's first line.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16pub enum LineEnding {
17    /// A line feed (`\n`).
18    Lf,
19    /// A carriage return and line feed (`\r\n`).
20    CrLf,
21}
22
23impl LineEnding {
24    /// `apply` converts LF text to this line ending.
25    pub fn apply(self, text: &str) -> String {
26        match self {
27            LineEnding::Lf => text.to_string(),
28            LineEnding::CrLf => text.replace('\n', "\r\n"),
29        }
30    }
31
32    /// `detect` returns the line ending of the first line of `text`, or LF when
33    /// `text` has no line break.
34    pub fn detect(text: &str) -> Self {
35        Self::detect_bytes(text.as_bytes())
36    }
37
38    /// `detect_bytes` is `detect` for bytes that need not be UTF-8.
39    pub fn detect_bytes(bytes: &[u8]) -> Self {
40        match bytes.iter().position(|&b| b == b'\n') {
41            Some(i) if i > 0 && bytes[i - 1] == b'\r' => LineEnding::CrLf,
42            _ => LineEnding::Lf,
43        }
44    }
45}
46
47// sokf:begin file-key
48/// `Stat` holds the metadata that the walk reads without opening the file
49/// (CACHE-1_AC-1).
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
51pub struct Stat {
52    /// The byte length.
53    pub len: u64,
54    /// The modification time in nanoseconds since the epoch, when known.
55    pub mtime: Option<i64>,
56}
57
58impl Stat {
59    /// `of` builds the stat of a file from its metadata.
60    pub fn of(meta: &fs::Metadata) -> Stat {
61        let mtime = meta
62            .modified()
63            .ok()
64            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
65            .and_then(|d| i64::try_from(d.as_nanos()).ok());
66        Stat {
67            len: meta.len(),
68            mtime,
69        }
70    }
71}
72
73/// `FileKey` identifies a file's content for the cache (CACHE-1_AC-1,
74/// CACHE-1_AC-2).
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
76pub struct FileKey {
77    /// The byte length.
78    pub len: u64,
79    /// The modification time in nanoseconds since the epoch, when known.
80    pub mtime: Option<i64>,
81    /// The FNV-1a 64 hash of the bytes.
82    pub hash: u64,
83}
84
85impl FileKey {
86    /// `stat` returns the length and modification time from the key.
87    pub fn stat(&self) -> Stat {
88        Stat {
89            len: self.len,
90            mtime: self.mtime,
91        }
92    }
93}
94// sokf:end file-key
95
96/// `Source` is one loaded file, with its text normalised to LF.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Source {
99    /// The file's path in the repository.
100    pub path: RepoPath,
101    /// The text, with LF line endings.
102    pub text: String,
103    /// The line ending of the first line.
104    pub eol: LineEnding,
105    /// The file key.
106    pub key: FileKey,
107}
108
109impl Source {
110    /// `from_text` builds a source from text, for tests and scaffolds, and
111    /// derives the key from the text alone.
112    pub fn from_text(path: RepoPath, raw: &str) -> Self {
113        let eol = LineEnding::detect(raw);
114        Source {
115            path,
116            text: raw.replace("\r\n", "\n"),
117            eol,
118            key: FileKey {
119                len: raw.len() as u64,
120                mtime: None,
121                hash: fnv1a64(raw.as_bytes()),
122            },
123        }
124    }
125
126    /// `line_count` returns the number of lines. A last line without a line
127    /// break counts as a line.
128    pub fn line_count(&self) -> usize {
129        if self.text.is_empty() {
130            0
131        } else {
132            self.text.matches('\n').count() + usize::from(!self.text.ends_with('\n'))
133        }
134    }
135}
136
137/// `load` reads a file under `root` as UTF-8 and returns it as a source, with
138/// its modification time in the key. It returns an I/O error when the file
139/// isn't valid UTF-8.
140// sokf-implements: SOKF_VALIDATION_2
141// sokf-implements: SOKF_VALIDATION_35
142pub fn load(root: &RepoRoot, path: &RepoPath) -> Result<Source> {
143    let fs_path = path.to_fs(root);
144    let bytes = fs::read(&fs_path).map_err(|e| Error::io(&fs_path, e))?;
145    let raw = String::from_utf8(bytes).map_err(|e| {
146        Error::io(
147            &fs_path,
148            std::io::Error::new(std::io::ErrorKind::InvalidData, e.utf8_error()),
149        )
150    })?;
151    let mtime = fs::metadata(&fs_path).ok().and_then(|m| Stat::of(&m).mtime);
152    let mut source = Source::from_text(path.clone(), &raw);
153    source.key.mtime = mtime;
154    Ok(source)
155}
156
157/// `load_text` reads a file under `root` and returns only its text, for a file
158/// that a document includes rather than one that sokf parses.
159pub fn load_text(root: &RepoRoot, path: &RepoPath) -> Result<String> {
160    Ok(load(root, path)?.text)
161}
162
163/// `create_parent` creates the directory that holds `fs_path`, and each
164/// directory above it that is missing.
165pub(crate) fn create_parent(fs_path: &Path) -> Result<()> {
166    if let Some(parent) = fs_path.parent() {
167        fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
168    }
169    Ok(())
170}
171
172/// `read_optional` reads a file on disk as text, or returns `None` when the
173/// file is absent.
174pub(crate) fn read_optional(fs_path: &Path) -> Result<Option<String>> {
175    match fs::read_to_string(fs_path) {
176        Ok(t) => Ok(Some(t)),
177        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
178        Err(e) => Err(Error::io(fs_path, e)),
179    }
180}
181
182/// `split` splits a source's frontmatter from its body.
183// sokf-implements: SOKF_FORMAT_17
184pub fn split(source: &Source) -> Split<'_> {
185    split_frontmatter(&source.text)
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    fn src(text: &str) -> Source {
193        Source::from_text(RepoPath::parse("/a.md").unwrap(), text)
194    }
195
196    #[test]
197    fn detects_and_restores_line_endings() {
198        assert_eq!(LineEnding::detect("a\r\nb\n"), LineEnding::CrLf);
199        assert_eq!(LineEnding::detect("a\nb\r\n"), LineEnding::Lf);
200        assert_eq!(LineEnding::detect("no newline"), LineEnding::Lf);
201        assert_eq!(LineEnding::detect(""), LineEnding::Lf);
202        assert_eq!(LineEnding::CrLf.apply("a\nb\n"), "a\r\nb\r\n");
203        assert_eq!(LineEnding::Lf.apply("a\nb\n"), "a\nb\n");
204        let s = src("a\r\nb\r\n");
205        assert_eq!(s.text, "a\nb\n");
206        assert_eq!(s.eol, LineEnding::CrLf);
207        assert_eq!(s.key.len, 6);
208    }
209
210    #[test]
211    fn counts_lines() {
212        assert_eq!(src("").line_count(), 0);
213        assert_eq!(src("a").line_count(), 1);
214        assert_eq!(src("a\n").line_count(), 1);
215        assert_eq!(src("a\nb").line_count(), 2);
216        assert_eq!(src("a\nb\n").line_count(), 2);
217    }
218
219    #[test]
220    fn splits_frontmatter_from_body() {
221        let s = src("---\ntype: A\nid: a\n---\n\n# Title\n");
222        let sp = split(&s);
223        assert_eq!(sp.frontmatter, Some(("type: A\nid: a\n", 2)));
224        assert_eq!(sp.body, "\n# Title\n");
225        assert_eq!(sp.body_line, 5);
226    }
227
228    #[test]
229    fn no_frontmatter_is_all_body() {
230        let s = src("# Title\n---\n");
231        let sp = split(&s);
232        assert_eq!(sp.frontmatter, None);
233        assert_eq!(sp.body, "# Title\n---\n");
234        assert_eq!(sp.body_line, 1);
235    }
236
237    #[test]
238    fn unclosed_frontmatter_runs_to_the_end() {
239        let s = src("---\ntype: A\n");
240        let sp = split(&s);
241        assert_eq!(sp.frontmatter, Some(("type: A\n", 2)));
242        assert_eq!(sp.body, "");
243        assert_eq!(sp.body_line, 3);
244        let s = src("---");
245        let sp = split(&s);
246        assert_eq!(sp.frontmatter, Some(("", 2)));
247        let s = src("---\n---\nbody");
248        let sp = split(&s);
249        assert_eq!(sp.frontmatter, Some(("", 2)));
250        assert_eq!(sp.body, "body");
251        assert_eq!(sp.body_line, 3);
252    }
253
254    #[test]
255    fn loads_from_disk_with_a_key() {
256        let dir = crate::test_support::fresh_dir("src");
257        fs::write(dir.join("f.md"), "x\r\ny\r\n").unwrap();
258        fs::write(dir.join("bad.md"), [0xFF, 0xFE]).unwrap();
259        let root = RepoRoot::new(dir.clone());
260        let path = RepoPath::parse("/f.md").unwrap();
261        let s = load(&root, &path).unwrap();
262        assert_eq!(s.text, "x\ny\n");
263        assert_eq!(s.eol, LineEnding::CrLf);
264        assert!(s.key.mtime.is_some());
265        assert_eq!(load_text(&root, &path).unwrap(), "x\ny\n");
266        assert!(load(&root, &RepoPath::parse("/missing.md").unwrap()).is_err());
267        assert!(load(&root, &RepoPath::parse("/bad.md").unwrap()).is_err());
268        fs::remove_dir_all(&dir).unwrap();
269    }
270}