1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16pub enum LineEnding {
17 Lf,
19 CrLf,
21}
22
23impl LineEnding {
24 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 pub fn detect(text: &str) -> Self {
35 Self::detect_bytes(text.as_bytes())
36 }
37
38 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
51pub struct Stat {
52 pub len: u64,
54 pub mtime: Option<i64>,
56}
57
58impl Stat {
59 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
76pub struct FileKey {
77 pub len: u64,
79 pub mtime: Option<i64>,
81 pub hash: u64,
83}
84
85impl FileKey {
86 pub fn stat(&self) -> Stat {
88 Stat {
89 len: self.len,
90 mtime: self.mtime,
91 }
92 }
93}
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Source {
99 pub path: RepoPath,
101 pub text: String,
103 pub eol: LineEnding,
105 pub key: FileKey,
107}
108
109impl Source {
110 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 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
137pub 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
157pub fn load_text(root: &RepoRoot, path: &RepoPath) -> Result<String> {
160 Ok(load(root, path)?.text)
161}
162
163pub(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
172pub(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
182pub 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}