Skip to main content

aoc_toolkit/application/progress/readme/
file.rs

1use std::fs;
2use std::io::{self, Write};
3use std::path::{Component, Path, PathBuf};
4
5use tempfile::NamedTempFile;
6
7use super::{ReadmeSectionError, replace_progress_section};
8use crate::ClientError;
9use crate::client::cache;
10use crate::project::ReadmeSettings;
11
12#[derive(Debug, thiserror::Error)]
13pub enum ReadmeWriteError {
14    #[error("README progress updates are disabled; enable progress.readme.enabled in aoc.toml")]
15    Disabled,
16
17    #[error("README path must point to an existing regular file inside the project: {0}")]
18    InvalidPath(PathBuf),
19
20    #[error("Cannot update README at {path}: {source}")]
21    Io {
22        path: PathBuf,
23        #[source]
24        source: io::Error,
25    },
26
27    #[error("Cannot lock the project README: {0}")]
28    Lock(#[from] ClientError),
29
30    #[error(transparent)]
31    Section(#[from] ReadmeSectionError),
32}
33
34/// Updates the managed README section and reports whether the file changed.
35///
36/// # Errors
37///
38/// Returns an error if updates are disabled, the path or markers are invalid,
39/// or the file cannot be locked, read, or atomically replaced.
40pub fn update_readme(
41    project_root: &Path,
42    settings: &ReadmeSettings,
43    markdown: &str,
44) -> Result<bool, ReadmeWriteError> {
45    if !settings.enabled {
46        return Err(ReadmeWriteError::Disabled);
47    }
48
49    let configured_path = settings
50        .path
51        .as_deref()
52        .unwrap_or_else(|| Path::new("README.md"));
53    let root = project_root
54        .canonicalize()
55        .map_err(|source| io_error(project_root, source))?;
56    let path = resolve_readme_path(&root, configured_path)?;
57    let _guard = cache::lock(&root.join(".aoc-toolkit/readme.lock"))?;
58
59    let original = fs::read_to_string(&path).map_err(|source| io_error(&path, source))?;
60    let updated = replace_progress_section(&original, markdown)?;
61
62    if updated == original {
63        return Ok(false);
64    }
65
66    replace_file(&path, &updated)?;
67    Ok(true)
68}
69
70fn resolve_readme_path(root: &Path, configured_path: &Path) -> Result<PathBuf, ReadmeWriteError> {
71    let invalid = || ReadmeWriteError::InvalidPath(configured_path.to_path_buf());
72    if configured_path.as_os_str().is_empty()
73        || !configured_path
74            .components()
75            .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
76    {
77        return Err(invalid());
78    }
79
80    let candidate = root.join(configured_path);
81    let metadata =
82        fs::symlink_metadata(&candidate).map_err(|source| io_error(&candidate, source))?;
83    if !metadata.is_file() {
84        return Err(invalid());
85    }
86
87    let path = candidate
88        .canonicalize()
89        .map_err(|source| io_error(&candidate, source))?;
90    if !path.starts_with(root) {
91        return Err(invalid());
92    }
93
94    Ok(path)
95}
96
97fn replace_file(path: &Path, content: &str) -> Result<(), ReadmeWriteError> {
98    let parent = path
99        .parent()
100        .ok_or_else(|| ReadmeWriteError::InvalidPath(path.to_path_buf()))?;
101    let permissions = fs::metadata(path)
102        .map_err(|source| io_error(path, source))?
103        .permissions();
104
105    let mut temporary = NamedTempFile::new_in(parent).map_err(|source| io_error(path, source))?;
106    temporary
107        .write_all(content.as_bytes())
108        .map_err(|source| io_error(path, source))?;
109    temporary
110        .as_file()
111        .set_permissions(permissions)
112        .map_err(|source| io_error(path, source))?;
113    temporary
114        .as_file()
115        .sync_all()
116        .map_err(|source| io_error(path, source))?;
117    temporary
118        .persist(path)
119        .map_err(|error| io_error(path, error.error))?;
120
121    Ok(())
122}
123
124fn io_error(path: &Path, source: io::Error) -> ReadmeWriteError {
125    ReadmeWriteError::Io {
126        path: path.to_path_buf(),
127        source,
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use std::{fs, path::PathBuf};
134
135    use tempfile::tempdir;
136
137    use super::{ReadmeWriteError, update_readme};
138    use crate::application::progress::readme::{END_MARKER, START_MARKER};
139    use crate::project::ReadmeSettings;
140
141    #[test]
142    fn updates_the_configured_file_and_skips_an_identical_write() {
143        let project = tempdir().unwrap();
144        let docs = project.path().join("docs");
145        fs::create_dir(&docs).unwrap();
146        let path = docs.join("AoC.md");
147        let original = format!("# My project\n{START_MARKER}\n{END_MARKER}\nManual notes\n");
148        fs::write(&path, original).unwrap();
149
150        let settings = ReadmeSettings {
151            enabled: true,
152            path: Some(PathBuf::from("docs/AoC.md")),
153            ..ReadmeSettings::default()
154        };
155
156        assert!(update_readme(project.path(), &settings, "New progress\n").unwrap());
157        assert!(!update_readme(project.path(), &settings, "New progress\n").unwrap());
158        assert_eq!(
159            fs::read_to_string(path).unwrap(),
160            format!("# My project\n{START_MARKER}\nNew progress\n{END_MARKER}\nManual notes\n"),
161        );
162    }
163
164    #[test]
165    fn refuses_disabled_export_and_paths_outside_the_project() {
166        let project = tempdir().unwrap();
167        let disabled = ReadmeSettings::default();
168
169        assert!(matches!(
170            update_readme(project.path(), &disabled, "Progress"),
171            Err(ReadmeWriteError::Disabled),
172        ));
173
174        let outside = ReadmeSettings {
175            enabled: true,
176            path: Some(PathBuf::from("../README.md")),
177            ..ReadmeSettings::default()
178        };
179        assert!(matches!(
180            update_readme(project.path(), &outside, "Progress"),
181            Err(ReadmeWriteError::InvalidPath(_)),
182        ));
183    }
184
185    #[test]
186    fn preserves_the_original_file_when_markers_are_missing() {
187        let project = tempdir().unwrap();
188        let path = project.path().join("README.md");
189        let original = "# Project\nManual notes\n";
190        fs::write(&path, original).unwrap();
191        let settings = ReadmeSettings {
192            enabled: true,
193            ..ReadmeSettings::default()
194        };
195
196        assert!(matches!(
197            update_readme(project.path(), &settings, "Progress"),
198            Err(ReadmeWriteError::Section(_)),
199        ));
200        assert_eq!(fs::read_to_string(path).unwrap(), original);
201    }
202}