Skip to main content

artifactize_core/config/
edit.rs

1//! Workbench file operations, shared with `config rename`.
2//!
3//! Call [`read`] to obtain project-relative file contents. For each file an operation
4//! writes (including a new name, whose content is `None`), pass its last-read content in
5//! [`BasedOn`]. [`apply`] returns fresh contents for the next edit. Refusals write nothing:
6//! invalid definitions include their file and source position, conflicts include the disk
7//! contents, and forbidden operations explain the remaining reference or cycle.
8//!
9//! [`read_project`] returns each node's definition file, exact authored PATH, target kind,
10//! missing-target mark, raw-content SHA-256 identity and annotations, plus the file contents
11//! used as [`BasedOn`]. Merge a successful delta into those bases before the next edit.
12//! Creation is always `.artifactize/<name>.artf`; rename stays in its original subfolder.
13//! [`footprint`] previews the exact files an operation changes, with their snapshot bases
14//! (including `None` for new destinations), using the same candidate edit as [`apply`].
15//!
16//! [`Operation`] creates a node, changes PATH or source, adds/removes/moves parts, renames
17//! and deletes, and saves/resets places or sets/moves a comment. A move changes both wholes
18//! in one transaction. Rename updates structural references and whole-local place keys;
19//! delete names every remaining referrer. Comments and unknown annotations are not references.
20//! A stale file returns [`Refusal::Changed`] with its current text (`None` when deleted),
21//! including when the changed text is no longer valid. Source can repair that text after
22//! the caller reloads its base. Invalid candidates include file, line and column; cycles,
23//! occupied comment destinations and remaining referrers have readable reasons.
24//!
25//! Every complete prospective project validates before writes. Annotations never invalidate
26//! a configuration check; a known malformed section refuses operations that edit it. Other
27//! annotation data and untouched text remain as authored. The UI owns unsaved-typing policy.
28//! [`Operation::SavePlaces`] uses a plain node name for its top-level `at`, or `whole/part`
29//! for a whole-local position. The client supplies every top-level node on its first manual
30//! placement, and destination-local coordinates for drops. Omitted drop coordinates carry
31//! the previous numeric position. Reset with `None` removes top-level places only; `Some`
32//! removes that whole's local places. Empty comment text removes it. No layout file exists.
33use 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
184/// Exact definition contents, keyed by project-relative file.
185pub 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
209// Give a stale edit its current disk text even when the edit's other preconditions now fail.
210// The final comparison below remains authoritative and covers every actually changed file.
211fn 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 &current != 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 &current != expected {
276            return Err(Refusal::Changed {
277                file: relative.to_owned(),
278                current,
279            });
280        }
281    }
282    Ok(())
283}
284
285/// Apply one validated operation. An absent entry in `based_on` is never an implicit CAS.
286pub fn apply(project: &Path, based_on: &BasedOn, operation: Operation) -> Result<BasedOn, Refusal> {
287    let root = crate::platform::canonicalize(project).map_err(io)?;
288    let state = crate::store::state_dir(None).map_err(io)?;
289    let locks =
290        crate::workspace::prepare_directory(&state.join("definition-locks"), &root).map_err(io)?;
291    use sha2::Digest;
292    let identity = sha2::Sha256::digest(crate::platform::path_text(&root).as_bytes());
293    let identity = identity
294        .iter()
295        .map(|byte| format!("{byte:02x}"))
296        .collect::<String>();
297    let lock_path = locks.join(format!("{identity}.lock"));
298    let lock = crate::platform::open_no_follow(
299        std::fs::OpenOptions::new()
300            .read(true)
301            .write(true)
302            .create(true)
303            .truncate(false),
304        &lock_path,
305    )
306    .map_err(io)?;
307    lock.lock().map_err(io)?;
308    let sources = discovery::sources(&root)?;
309    compare_named_bases(&root, based_on, &operation)?;
310    let proposed = proposal::propose(&root, &sources, operation)?;
311    let changes = proposal::changes(&sources, &proposed);
312    compare_changes(&root, based_on, &changes)?;
313    discovery::read_sources(root.clone(), &proposed)?;
314    let originals = changes
315        .keys()
316        .map(|file| Ok((file.clone(), disk(file)?)))
317        .collect::<Result<BTreeMap<_, _>, Refusal>>()?;
318    let mut staged = Vec::new();
319    for (file, source) in &changes {
320        if let Some(source) = source {
321            let mut temp =
322                tempfile::NamedTempFile::new_in(file.parent().expect("definition directory"))
323                    .map_err(io)?;
324            std::io::Write::write_all(&mut temp, source.as_bytes()).map_err(io)?;
325            staged.push((file.clone(), temp));
326        }
327    }
328    // Validation and staging may take time: compare again immediately before persistence.
329    compare_changes(&root, based_on, &changes)?;
330    let written = (|| -> Result<(), Refusal> {
331        for (file, temp) in staged {
332            crate::platform::paths::replace_open_file(temp, &file).map_err(io)?;
333        }
334        for (file, source) in &changes {
335            if source.is_none() {
336                crate::platform::paths::remove_regular(file).map_err(io)?;
337            }
338        }
339        Ok(())
340    })();
341    if let Err(error) = written {
342        for (file, source) in originals {
343            if let Some(source) = source {
344                crate::platform::paths::restore_file(&file, source.as_bytes()).map_err(io)?;
345            } else if let Err(error) = crate::platform::paths::remove_regular(&file)
346                && error.kind() != std::io::ErrorKind::NotFound
347            {
348                return Err(io(error));
349            }
350        }
351        return Err(error);
352    }
353    Ok(changes
354        .into_iter()
355        .map(|(file, source)| {
356            (
357                file.strip_prefix(&root).expect("project file").to_owned(),
358                source,
359            )
360        })
361        .collect())
362}
363fn change_part(
364    doc: &mut toml_edit::DocumentMut,
365    part: &ArtifactName,
366    add: bool,
367) -> Result<(), Refusal> {
368    if doc.get("parts").is_none() {
369        if !add {
370            return Err(forbidden(format!("{part} is not a part of this Artifact.")));
371        }
372        doc["parts"] = toml_edit::value(toml_edit::Array::new());
373    }
374    let parts = doc["parts"].as_array_mut().expect("validated parts");
375    let index = parts
376        .iter()
377        .position(|value| value.as_str() == Some(part.as_str()));
378    match (add, index) {
379        (true, None) => parts.push(part.as_str()),
380        (false, Some(index)) => {
381            parts.remove(index);
382        }
383        (true, Some(_)) => {
384            return Err(forbidden(format!(
385                "{part} is already a part of this Artifact."
386            )));
387        }
388        (false, None) => return Err(forbidden(format!("{part} is not a part of this Artifact."))),
389    }
390    if parts.is_empty() {
391        doc.remove("parts");
392    }
393    Ok(())
394}
395fn node_file(config: &RepoConfig, name: &ArtifactName) -> Result<PathBuf, Refusal> {
396    config
397        .artifacts
398        .get(name)
399        .map(|artifact| config.root.join(artifact.declaration_path()))
400        .ok_or_else(|| forbidden(format!("Unknown Artifact {name}.")))
401}
402fn update(
403    config: &RepoConfig,
404    proposed: &mut BTreeMap<PathBuf, String>,
405    name: &ArtifactName,
406    edit: impl FnOnce(&mut toml_edit::DocumentMut, &Path) -> Result<(), Refusal>,
407) -> Result<(), Refusal> {
408    let file = node_file(config, name)?;
409    let mut doc = proposed[&file]
410        .parse::<toml_edit::DocumentMut>()
411        .expect("validated source");
412    edit(&mut doc, &file)?;
413    proposed.insert(file, doc.to_string());
414    Ok(())
415}
416
417fn check_style(
418    config: &RepoConfig,
419    proposed: &mut BTreeMap<PathBuf, String>,
420    name: &ArtifactName,
421) -> Result<(), Refusal> {
422    update(config, proposed, name, |doc, file| {
423        annotations::validate_style(doc, file, config, name)
424    })
425}
426
427fn placement(
428    config: &RepoConfig,
429    proposed: &BTreeMap<PathBuf, String>,
430    part: &ArtifactName,
431    whole: Option<&ArtifactName>,
432) -> Option<[f64; 2]> {
433    let owner = whole.unwrap_or(part);
434    let file = node_file(config, owner).ok()?;
435    let annotations = annotations::read(proposed.get(&file)?, config, owner);
436    if whole.is_some() {
437        annotations.parts.get(part).copied()
438    } else {
439        annotations.at
440    }
441}