Skip to main content

pfx_load/scene/
rewrite.rs

1use std::path::{Path, PathBuf};
2
3use pfx_scene::{Patch, PatchGroup, Project};
4
5use super::edit::scene_error as refusal;
6use super::{SceneError, build};
7
8fn scene_files(path: &Path) -> Result<(PathBuf, Project, PathBuf), SceneError> {
9    let root = build::project_root(path);
10    let project = build::project(&root)?;
11    let absolute = build::absolute(path);
12    Ok((root, project, absolute))
13}
14
15pub fn migrate(path: impl AsRef<Path>, dry_run: bool) -> Result<PatchGroup, SceneError> {
16    let (root, project, absolute) = scene_files(path.as_ref())?;
17    let mut scene = project
18        .scene(&absolute)
19        .map_err(|found| build::refused(&root, &found))?;
20    if let Some(finish) = scene.finish.as_ref().and_then(|finish| finish.file.clone()) {
21        scene.files.retain(|file| *file != Path::new(&finish));
22    }
23    let mut patches = Vec::new();
24    for file in &scene.files {
25        let full = project.root().join(file);
26        let before = std::fs::read_to_string(&full)
27            .map_err(|error| SceneError::new(&root.join(file), None, error.to_string()))?;
28        let after = project
29            .migrate(&full)
30            .map_err(|found| build::refused(&root, &found))?;
31        if after != before {
32            patches.push(Patch {
33                label: "migrate".to_string(),
34                file: full,
35                before,
36                after,
37            });
38        }
39    }
40    let group = PatchGroup {
41        label: "migrate".to_string(),
42        patches,
43    };
44    if !group.is_empty() {
45        project
46            .scene_with(&absolute, group.after())
47            .map_err(|found| build::refused(&root, &found))?;
48        if !dry_run {
49            group.write().map_err(|error| refusal(&root, error))?;
50        }
51    }
52    Ok(group)
53}
54
55pub fn fix(path: impl AsRef<Path>, dry_run: bool) -> Result<PatchGroup, SceneError> {
56    let (root, project, absolute) = scene_files(path.as_ref())?;
57    let group = project
58        .fix(&absolute)
59        .map_err(|error| refusal(&root, error))?;
60    if !dry_run && !group.is_empty() {
61        group.write().map_err(|error| refusal(&root, error))?;
62    }
63    Ok(group)
64}