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    apply_bases(project, based_on, operation, false)
288}
289
290/// Apply an editor's snapshot. Newly created files are implicitly based on absence; an
291/// existing file must have been shown. Validation and conflicts stay in the same transaction.
292pub 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    // Validation and staging may take time: compare again immediately before persistence.
367    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}
440pub(super) fn parse_document(
441    source: &str,
442) -> (artifactize_tools::artf::Masked, toml_edit::DocumentMut) {
443    let masked = artifactize_tools::artf::mask(source).expect("validated source");
444    let doc = masked
445        .toml
446        .parse::<toml_edit::DocumentMut>()
447        .expect("validated source");
448    (masked, doc)
449}
450
451fn update(
452    config: &RepoConfig,
453    proposed: &mut BTreeMap<PathBuf, String>,
454    name: &ArtifactName,
455    edit: impl FnOnce(&mut toml_edit::DocumentMut, &Path, &str) -> Result<(), Refusal>,
456) -> Result<(), Refusal> {
457    let file = node_file(config, name)?;
458    let original = proposed[&file].clone();
459    let (masked, mut doc) = parse_document(&original);
460    edit(&mut doc, &file, &original)?;
461    proposed.insert(file, masked.unmask(&doc.to_string(), &original));
462    Ok(())
463}
464
465fn check_style(
466    config: &RepoConfig,
467    proposed: &mut BTreeMap<PathBuf, String>,
468    name: &ArtifactName,
469) -> Result<(), Refusal> {
470    update(config, proposed, name, |doc, file, source| {
471        annotations::validate_style(doc, file, source, config, name)
472    })
473}
474
475fn placement(
476    config: &RepoConfig,
477    proposed: &BTreeMap<PathBuf, String>,
478    part: &ArtifactName,
479    whole: Option<&ArtifactName>,
480) -> Option<[f64; 2]> {
481    let owner = whole.unwrap_or(part);
482    let file = node_file(config, owner).ok()?;
483    let annotations = annotations::read(proposed.get(&file)?, config, owner);
484    if whole.is_some() {
485        annotations.parts.get(part).copied()
486    } else {
487        annotations.at
488    }
489}