1use crate::{generate::format_rust, names::GeneratedNames, Generator};
2use anyhow::{bail, Context, Result};
3use fs2::FileExt;
4use std::{
5 fs::{self, OpenOptions},
6 io::Write,
7 path::{Path, PathBuf},
8};
9
10struct Change {
11 path: PathBuf,
12 before: Option<Vec<u8>>,
13 after: Vec<u8>,
14}
15pub fn make_mail(root: &Path, name: &str) -> Result<Vec<PathBuf>> {
17 generate(root, name, false)
18}
19pub fn make_notification(root: &Path, name: &str) -> Result<Vec<PathBuf>> {
21 generate(root, name, true)
22}
23fn generate(root: &Path, name: &str, notification: bool) -> Result<Vec<PathBuf>> {
24 generate_with(root, name, notification, |file, path, existing| {
25 if existing {
26 file.persist(path).map(|_| ()).map_err(|e| e.error.into())
27 } else {
28 file.persist_noclobber(path)
29 .map(|_| ())
30 .map_err(|e| e.error.into())
31 }
32 })
33}
34fn generate_with(
35 root: &Path,
36 name: &str,
37 notification: bool,
38 mut persist: impl FnMut(tempfile::NamedTempFile, &Path, bool) -> Result<()>,
39) -> Result<Vec<PathBuf>> {
40 let names = GeneratedNames::new(name)?;
41 reject_symlinks(root, &root.join(".capy-generator.lock"))?;
42 let lock = OpenOptions::new()
43 .read(true)
44 .write(true)
45 .create(true)
46 .truncate(false)
47 .open(root.join(".capy-generator.lock"))?;
48 lock.lock_exclusive()
49 .context("Cannot lock the Capy generator registry")?;
50 let directory = if notification {
51 "notifications"
52 } else {
53 "mail"
54 };
55 let registry_path = format!("app/{directory}/mod.rs");
56 reject_symlinks(root, &root.join(®istry_path))?;
57 let registry = match fs::read_to_string(root.join(®istry_path)) {
58 Ok(value) => Some(value),
59 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
60 Err(e) => return Err(e.into()),
61 };
62 names.check_registry(
63 registry.as_deref().unwrap_or(""),
64 &names.module,
65 Generator::Controller,
66 )?;
67 let mut changes = Vec::new();
68 let mut add = |relative: &str, after: String, existing: bool| -> Result<()> {
69 let path = root.join(relative);
70 reject_symlinks(root, &path)?;
71 let before = match fs::read(&path) {
72 Ok(bytes) => Some(bytes),
73 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
74 Err(e) => return Err(e.into()),
75 };
76 if before.is_some() != existing {
77 bail!(
78 "{} {}. Capy never silently overwrites application files.",
79 path.display(),
80 if existing {
81 "is missing"
82 } else {
83 "already exists"
84 }
85 );
86 }
87 let after = if relative.ends_with(".rs") {
88 format_rust(&after)?
89 } else {
90 after
91 };
92 changes.push(Change {
93 path,
94 before,
95 after: after.into_bytes(),
96 });
97 Ok(())
98 };
99 let source = if notification {
100 include_str!("../templates/mail/notification.rs.txt")
101 } else {
102 include_str!("../templates/mail/mail.rs.txt")
103 };
104 add(
105 &format!("app/{directory}/{}.rs", names.module),
106 source
107 .replace("{{module}}", &names.module)
108 .replace("{{type}}", &names.ty),
109 false,
110 )?;
111 add(
112 ®istry_path,
113 format!(
114 "{}\npub mod {};\n",
115 registry
116 .as_deref()
117 .unwrap_or("//! Application-owned outbound communication."),
118 names.module
119 ),
120 registry.is_some(),
121 )?;
122 add(
123 &format!("templates/mail/{}.html", names.module),
124 include_str!("../templates/mail/body.html.txt").into(),
125 false,
126 )?;
127 add(
128 &format!("templates/mail/{}.txt", names.module),
129 include_str!("../templates/mail/body.txt.txt").into(),
130 false,
131 )?;
132 if registry.is_none() {
133 let app = read(root, "app/mod.rs")?;
134 GeneratedNames::new(directory)?.check_registry(&app, directory, Generator::Controller)?;
135 add("app/mod.rs", format!("{app}\npub mod {directory};\n"), true)?;
136 }
137 let mut manifest = read(root, "Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
139 let dependency = manifest["dependencies"]["capy"]
140 .as_table_like_mut()
141 .context("Use a table-style capy-framework dependency before installing mail.")?;
142 let mut features = dependency
143 .get("features")
144 .and_then(|v| v.as_array())
145 .cloned()
146 .unwrap_or_default();
147 if !features.iter().any(|f| f.as_str() == Some("mail")) {
148 features.push("mail");
149 }
150 dependency.insert("features", toml_edit::value(features));
151 add("Cargo.toml", manifest.to_string(), true)?;
152 let factory = crate::project::application_file(root);
153 let main = read(root, factory)?;
154 if !main.contains(".mail()") && !main.contains(".with_mail(") {
155 add(
156 factory,
157 crate::project::wire_application(&main, ".mail()")?,
158 true,
159 )?;
160 }
161 if !root.join("config/mail.toml").exists() {
162 add(
163 "config/mail.toml",
164 include_str!("../templates/mail/config.toml.txt").into(),
165 false,
166 )?;
167 } else {
168 reject_symlinks(root, &root.join("config/mail.toml"))?;
169 }
170 let mut staged = Vec::new();
172 for change in &changes {
173 let mut file = tempfile::NamedTempFile::new_in(root)?;
174 if change.before.is_some() {
175 file.as_file()
176 .set_permissions(fs::metadata(&change.path)?.permissions())?;
177 }
178 file.write_all(&change.after)?;
179 file.as_file().sync_all()?;
180 staged.push(file);
181 }
182 let mut directories = Vec::new();
183 let mut committed = 0;
184 let result: Result<()> = (|| {
185 for change in &changes {
186 let mut missing: Vec<_> = change
187 .path
188 .parent()
189 .context("Missing parent")?
190 .ancestors()
191 .take_while(|p| *p != root && !p.exists())
192 .map(Path::to_path_buf)
193 .collect();
194 missing.reverse();
195 for path in missing {
196 reject_symlinks(root, &path)?;
197 fs::create_dir(&path)?;
198 directories.push(path);
199 }
200 }
201 for (file, change) in staged.into_iter().zip(&changes) {
202 persist(file, &change.path, change.before.is_some())?;
203 committed += 1;
204 }
205 Ok(())
206 })();
207 if let Err(error) = result {
208 for change in changes[..committed].iter().rev() {
209 if let Some(before) = &change.before {
210 let mut file = tempfile::NamedTempFile::new_in(root)?;
211 file.as_file()
212 .set_permissions(fs::metadata(&change.path)?.permissions())?;
213 file.write_all(before)?;
214 file.as_file().sync_all()?;
215 file.persist(&change.path)
216 .map_err(|e| e.error)
217 .context("Mail generator rollback failed; inspect partially installed files")?;
218 } else {
219 fs::remove_file(&change.path)?;
220 }
221 }
222 for directory in directories.into_iter().rev() {
223 fs::remove_dir(directory)?;
224 }
225 return Err(error.context("Mail generation failed; committed changes were rolled back"));
226 }
227 Ok(changes.into_iter().map(|c| c.path).collect())
228}
229fn read(root: &Path, relative: &str) -> Result<String> {
230 let path = root.join(relative);
231 reject_symlinks(root, &path)?;
232 Ok(fs::read_to_string(path)?)
233}
234fn reject_symlinks(root: &Path, path: &Path) -> Result<()> {
235 for ancestor in path.ancestors().take_while(|p| *p != root) {
236 if fs::symlink_metadata(ancestor).is_ok_and(|m| m.file_type().is_symlink()) {
237 bail!("Mail generator refuses symlink {}", ancestor.display());
238 }
239 }
240 Ok(())
241}
242#[cfg(test)]
243mod tests {
244 use super::*;
245 #[test]
246 fn collision_and_failed_install_leave_application_unchanged() {
247 let temp = tempfile::tempdir().unwrap();
248 let root = temp.path().join("app");
249 crate::new_project_with_frontend(&root, "app", crate::FrontendDriver::None).unwrap();
250 let before = fs::read(root.join("app/mod.rs")).unwrap();
251 let mut writes = 0;
252 assert!(generate_with(&root, "WelcomeMail", false, |file, path, _| {
253 writes += 1;
254 if writes == 6 {
255 bail!("simulated failure");
256 }
257 file.persist(path).map(|_| ()).map_err(|e| e.error.into())
258 })
259 .is_err());
260 assert_eq!(fs::read(root.join("app/mod.rs")).unwrap(), before);
261 assert!(!root.join("app/mail").exists());
262 assert!(!root.join("templates").exists());
263 make_mail(&root, "WelcomeMail").unwrap();
264 make_notification(&root, "WelcomeNotification").unwrap();
265 let before = fs::read(root.join("app/mail/mod.rs")).unwrap();
266 assert!(make_mail(&root, "WelcomeMail").is_err());
267 assert_eq!(fs::read(root.join("app/mail/mod.rs")).unwrap(), before);
268 assert_eq!(
269 read(&root, "src/bootstrap.rs")
270 .unwrap()
271 .matches(".mail()")
272 .count(),
273 1
274 );
275 }
276 #[cfg(unix)]
277 #[test]
278 fn symlinked_templates_are_rejected_before_writes() {
279 let temp = tempfile::tempdir().unwrap();
280 let root = temp.path().join("app");
281 crate::new_project_with_frontend(&root, "app", crate::FrontendDriver::None).unwrap();
282 std::os::unix::fs::symlink(temp.path(), root.join("templates")).unwrap();
283 assert!(make_mail(&root, "WelcomeMail").is_err());
284 assert!(!root.join("app/mail").exists());
285 }
286}