1use super::*;
34mod annotations;
35mod placement;
36mod proposal;
37mod references;
38mod snapshot;
39pub use super::authored_target::AuthoredTarget;
40pub use annotations::Annotations;
41pub use placement::PlacementKey;
42use serde::{Deserialize, Serialize};
43pub use snapshot::{Footprint, Layout, Node, Project, footprint, read_layout, read_project};
44
45#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(transparent)]
47pub struct BasedOn(
48 #[serde(with = "crate::platform::path_serde::map")] BTreeMap<PathBuf, Option<String>>,
49);
50impl std::ops::Deref for BasedOn {
51 type Target = BTreeMap<PathBuf, Option<String>>;
52 fn deref(&self) -> &Self::Target {
53 &self.0
54 }
55}
56impl std::ops::DerefMut for BasedOn {
57 fn deref_mut(&mut self) -> &mut Self::Target {
58 &mut self.0
59 }
60}
61impl FromIterator<(PathBuf, Option<String>)> for BasedOn {
62 fn from_iter<T: IntoIterator<Item = (PathBuf, Option<String>)>>(iter: T) -> Self {
63 Self(iter.into_iter().collect())
64 }
65}
66impl IntoIterator for BasedOn {
67 type Item = (PathBuf, Option<String>);
68 type IntoIter = std::collections::btree_map::IntoIter<PathBuf, Option<String>>;
69 fn into_iter(self) -> Self::IntoIter {
70 self.0.into_iter()
71 }
72}
73impl Extend<(PathBuf, Option<String>)> for BasedOn {
74 fn extend<T: IntoIterator<Item = (PathBuf, Option<String>)>>(&mut self, iter: T) {
75 self.0.extend(iter);
76 }
77}
78#[derive(Debug, Clone, Serialize, Deserialize)]
79#[serde(tag = "kind", rename_all = "camelCase")]
80pub enum Operation {
81 Create {
82 name: ArtifactName,
83 path: AuthoredTarget,
84 },
85 SetPath {
86 name: ArtifactName,
87 path: AuthoredTarget,
88 },
89 AddPart {
90 whole: ArtifactName,
91 part: ArtifactName,
92 #[serde(default)]
93 at: Option<[f64; 2]>,
94 },
95 RemovePart {
96 whole: ArtifactName,
97 part: ArtifactName,
98 },
99 MovePart {
100 part: ArtifactName,
101 from: Option<ArtifactName>,
102 to: Option<ArtifactName>,
103 #[serde(default)]
104 at: Option<[f64; 2]>,
105 },
106 SaveSource {
107 name: ArtifactName,
108 source: String,
109 },
110 Rename {
111 old: ArtifactName,
112 new: ArtifactName,
113 },
114 Delete {
115 name: ArtifactName,
116 },
117 SavePlaces {
118 places: BTreeMap<PlacementKey, [f64; 2]>,
119 },
120 SetComment {
121 name: ArtifactName,
122 text: String,
123 },
124 MoveComment {
125 from: ArtifactName,
126 to: ArtifactName,
127 },
128 ResetPlaces {
129 whole: Option<ArtifactName>,
130 },
131}
132#[derive(Debug, Serialize, thiserror::Error)]
133#[serde(tag = "kind", rename_all = "camelCase")]
134pub enum Refusal {
135 #[error("{}: {message}", crate::platform::path_text(.file))]
136 Invalid {
137 #[serde(with = "crate::platform::path_serde")]
138 file: PathBuf,
139 message: String,
140 line: Option<usize>,
141 column: Option<usize>,
142 },
143 #[error("{} changed on disk; reload its current content.", crate::platform::path_text(.file))]
144 Changed {
145 #[serde(with = "crate::platform::path_serde")]
146 file: PathBuf,
147 current: Option<String>,
148 },
149 #[error("{reason}")]
150 NotAllowed { reason: String },
151 #[error("{message}")]
152 Io { message: String },
153}
154impl From<ConfigError> for Refusal {
155 fn from(error: ConfigError) -> Self {
156 Self::Invalid {
157 file: error.path,
158 line: position(&error.message, "line "),
159 column: position(&error.message, "column "),
160 message: error.message,
161 }
162 }
163}
164fn position(message: &str, marker: &str) -> Option<usize> {
165 message
166 .split_once(marker)?
167 .1
168 .split(|character: char| !character.is_ascii_digit())
169 .next()?
170 .parse()
171 .ok()
172}
173fn io(error: impl std::fmt::Display) -> Refusal {
174 Refusal::Io {
175 message: error.to_string(),
176 }
177}
178fn forbidden(reason: impl Into<String>) -> Refusal {
179 Refusal::NotAllowed {
180 reason: reason.into(),
181 }
182}
183
184pub fn read(project: &Path) -> Result<BasedOn, Refusal> {
186 let root = crate::platform::canonicalize(project).map_err(io)?;
187 let sources = discovery::sources(&root)?;
188 let files = sources
189 .into_iter()
190 .map(|(file, source)| {
191 (
192 file.strip_prefix(&root)
193 .expect("definition below project")
194 .to_owned(),
195 Some(source),
196 )
197 })
198 .collect::<BasedOn>();
199 Ok(files)
200}
201fn disk(file: &Path) -> Result<Option<String>, Refusal> {
202 match read_regular_text(file) {
203 Ok(source) => Ok(Some(source)),
204 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
205 Err(error) => Err(io(error)),
206 }
207}
208
209fn compare_named_bases(
212 root: &Path,
213 based_on: &BasedOn,
214 operation: &Operation,
215) -> Result<(), Refusal> {
216 let names = match operation {
217 Operation::Create { name, .. }
218 | Operation::SetPath { name, .. }
219 | Operation::SaveSource { name, .. }
220 | Operation::Delete { name }
221 | Operation::SetComment { name, .. } => vec![name.clone()],
222 Operation::AddPart { whole, .. } | Operation::RemovePart { whole, .. } => {
223 vec![whole.clone()]
224 }
225 Operation::MovePart { from, to, .. } => from.iter().chain(to.iter()).cloned().collect(),
226 Operation::Rename { old, new } => vec![old.clone(), new.clone()],
227 Operation::MoveComment { from, to } => vec![from.clone(), to.clone()],
228 Operation::SavePlaces { places } => places.keys().map(|key| key.owner().clone()).collect(),
229 Operation::ResetPlaces { whole } => whole.iter().cloned().collect(),
230 };
231 for name in &names {
232 discovery::definition_name(name).map_err(forbidden)?;
233 }
234 for (file, expected) in based_on.iter().filter(|(file, _)| {
235 names
236 .iter()
237 .any(|name| file.file_stem().and_then(|stem| stem.to_str()) == Some(name.as_str()))
238 }) {
239 if !file.starts_with(discovery::DEFINITION_DIR)
240 || file.extension().is_none_or(|extension| extension != "artf")
241 {
242 return Err(forbidden(
243 "Base files must be definition paths below .artifactize/.",
244 ));
245 }
246 crate::scope::logical_path(&crate::platform::path_text(file))
247 .map_err(|error| forbidden(error.to_string()))?;
248 let absolute = root.join(file);
249 crate::platform::program::reject_link_ancestors(&absolute).map_err(forbidden)?;
250 let current = disk(&absolute)?;
251 if ¤t != expected {
252 return Err(Refusal::Changed {
253 file: file.clone(),
254 current,
255 });
256 }
257 }
258 Ok(())
259}
260
261fn compare_changes(
262 root: &Path,
263 based_on: &BasedOn,
264 changes: &BTreeMap<PathBuf, Option<String>>,
265) -> Result<(), Refusal> {
266 for file in changes.keys() {
267 let relative = file.strip_prefix(root).expect("project file");
268 let current = disk(file)?;
269 let expected = based_on.get(relative).ok_or_else(|| {
270 forbidden(format!(
271 "No base content was supplied for {}.",
272 crate::platform::path_text(relative)
273 ))
274 })?;
275 if ¤t != expected {
276 return Err(Refusal::Changed {
277 file: relative.to_owned(),
278 current,
279 });
280 }
281 }
282 Ok(())
283}
284
285pub fn apply(project: &Path, based_on: &BasedOn, operation: Operation) -> Result<BasedOn, Refusal> {
287 apply_bases(project, based_on, operation, false)
288}
289
290pub fn apply_shown(
293 project: &Path,
294 based_on: &BasedOn,
295 operation: Operation,
296) -> Result<BasedOn, Refusal> {
297 apply_bases(project, based_on, operation, true)
298}
299
300fn apply_bases(
301 project: &Path,
302 based_on: &BasedOn,
303 operation: Operation,
304 allow_creation: bool,
305) -> Result<BasedOn, Refusal> {
306 let root = crate::platform::canonicalize(project).map_err(io)?;
307 let state = crate::store::state_dir(None).map_err(io)?;
308 let locks =
309 crate::workspace::prepare_directory(&state.join("definition-locks"), &root).map_err(io)?;
310 use sha2::Digest;
311 let identity = sha2::Sha256::digest(crate::platform::path_text(&root).as_bytes());
312 let identity = identity
313 .iter()
314 .map(|byte| format!("{byte:02x}"))
315 .collect::<String>();
316 let lock_path = locks.join(format!("{identity}.lock"));
317 let lock = crate::platform::open_no_follow(
318 std::fs::OpenOptions::new()
319 .read(true)
320 .write(true)
321 .create(true)
322 .truncate(false),
323 &lock_path,
324 )
325 .map_err(io)?;
326 crate::platform::paths::lock(&lock).map_err(io)?;
327 let sources = discovery::sources(&root)?;
328 compare_named_bases(&root, based_on, &operation)?;
329 let proposed = proposal::propose(&root, &sources, operation)?;
330 let changes = proposal::changes(&sources, &proposed);
331 let mut bases;
332 let based_on = if allow_creation {
333 bases = based_on.clone();
334 for file in changes.keys() {
335 let relative = file.strip_prefix(&root).expect("project file");
336 if !bases.contains_key(relative) {
337 if let Some(current) = disk(file)? {
338 return Err(Refusal::Changed {
339 file: relative.to_owned(),
340 current: Some(current),
341 });
342 }
343 bases.insert(relative.to_owned(), None);
344 }
345 }
346 &bases
347 } else {
348 based_on
349 };
350 compare_changes(&root, based_on, &changes)?;
351 discovery::read_sources(root.clone(), &proposed)?;
352 let originals = changes
353 .keys()
354 .map(|file| Ok((file.clone(), disk(file)?)))
355 .collect::<Result<BTreeMap<_, _>, Refusal>>()?;
356 let mut staged = Vec::new();
357 for (file, source) in &changes {
358 if let Some(source) = source {
359 let mut temp =
360 tempfile::NamedTempFile::new_in(file.parent().expect("definition directory"))
361 .map_err(io)?;
362 std::io::Write::write_all(&mut temp, source.as_bytes()).map_err(io)?;
363 staged.push((file.clone(), temp));
364 }
365 }
366 compare_changes(&root, based_on, &changes)?;
368 let written = (|| -> Result<(), Refusal> {
369 for (file, temp) in staged {
370 crate::platform::paths::replace_open_file(temp, &file).map_err(io)?;
371 }
372 for (file, source) in &changes {
373 if source.is_none() {
374 crate::platform::paths::remove_regular(file).map_err(io)?;
375 }
376 }
377 Ok(())
378 })();
379 if let Err(error) = written {
380 for (file, source) in originals {
381 if let Some(source) = source {
382 crate::platform::paths::restore_file(&file, source.as_bytes()).map_err(io)?;
383 } else if let Err(error) = crate::platform::paths::remove_regular(&file)
384 && error.kind() != std::io::ErrorKind::NotFound
385 {
386 return Err(io(error));
387 }
388 }
389 return Err(error);
390 }
391 Ok(changes
392 .into_iter()
393 .map(|(file, source)| {
394 (
395 file.strip_prefix(&root).expect("project file").to_owned(),
396 source,
397 )
398 })
399 .collect())
400}
401fn change_part(
402 doc: &mut toml_edit::DocumentMut,
403 part: &ArtifactName,
404 add: bool,
405) -> Result<(), Refusal> {
406 if doc.get("parts").is_none() {
407 if !add {
408 return Err(forbidden(format!("{part} is not a part of this Artifact.")));
409 }
410 doc["parts"] = toml_edit::value(toml_edit::Array::new());
411 }
412 let parts = doc["parts"].as_array_mut().expect("validated parts");
413 let index = parts
414 .iter()
415 .position(|value| value.as_str() == Some(part.as_str()));
416 match (add, index) {
417 (true, None) => parts.push(part.as_str()),
418 (false, Some(index)) => {
419 parts.remove(index);
420 }
421 (true, Some(_)) => {
422 return Err(forbidden(format!(
423 "{part} is already a part of this Artifact."
424 )));
425 }
426 (false, None) => return Err(forbidden(format!("{part} is not a part of this Artifact."))),
427 }
428 if parts.is_empty() {
429 doc.remove("parts");
430 }
431 Ok(())
432}
433fn node_file(config: &RepoConfig, name: &ArtifactName) -> Result<PathBuf, Refusal> {
434 config
435 .artifacts
436 .get(name)
437 .map(|artifact| config.root.join(artifact.declaration_path()))
438 .ok_or_else(|| forbidden(format!("Unknown Artifact {name}.")))
439}
440fn update(
441 config: &RepoConfig,
442 proposed: &mut BTreeMap<PathBuf, String>,
443 name: &ArtifactName,
444 edit: impl FnOnce(&mut toml_edit::DocumentMut, &Path) -> Result<(), Refusal>,
445) -> Result<(), Refusal> {
446 let file = node_file(config, name)?;
447 let mut doc = proposed[&file]
448 .parse::<toml_edit::DocumentMut>()
449 .expect("validated source");
450 edit(&mut doc, &file)?;
451 proposed.insert(file, doc.to_string());
452 Ok(())
453}
454
455fn check_style(
456 config: &RepoConfig,
457 proposed: &mut BTreeMap<PathBuf, String>,
458 name: &ArtifactName,
459) -> Result<(), Refusal> {
460 update(config, proposed, name, |doc, file| {
461 annotations::validate_style(doc, file, config, name)
462 })
463}
464
465fn placement(
466 config: &RepoConfig,
467 proposed: &BTreeMap<PathBuf, String>,
468 part: &ArtifactName,
469 whole: Option<&ArtifactName>,
470) -> Option<[f64; 2]> {
471 let owner = whole.unwrap_or(part);
472 let file = node_file(config, owner).ok()?;
473 let annotations = annotations::read(proposed.get(&file)?, config, owner);
474 if whole.is_some() {
475 annotations.parts.get(part).copied()
476 } else {
477 annotations.at
478 }
479}