Skip to main content

vvv_engine/
rewrite.rs

1//! `rewrite`: one edit per selected match, the template expanded with the
2//! match's captures.
3
4use std::collections::BTreeMap;
5use vvv_core::Edit;
6use vvv_core::RelPath;
7
8use crate::change::Change;
9use crate::command::{Command, Context};
10use crate::{EngineError, Planned, Rewrite, RewriteIntent, RewriteOf, SourceFile};
11
12/// Plan a rewrite. Nothing is written; see [`Apply`](crate::Apply).
13impl Command for RewriteIntent {
14    type Output = Planned<Rewrite>;
15
16    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
17        let matches = cx.graph.search(&self.query)?.matches;
18        RewriteOf {
19            intent: self,
20            matches,
21        }
22        .run(cx)
23    }
24}
25
26/// The rewrite an intent makes of matches already found — a caller that
27/// keeps the matches (the picker, showing before and after) searches once.
28/// The intent's selection still narrows them.
29impl Command for RewriteOf {
30    type Output = Planned<Rewrite>;
31
32    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
33        let RewriteOf { intent, matches } = self;
34        let intent = &intent;
35        let matches = intent.selection.narrow(matches)?;
36        let mut files: BTreeMap<RelPath, SourceFile> = BTreeMap::new();
37        let mut change = Change::new();
38        for m in &matches {
39            let file = match files.get(&m.path) {
40                Some(file) => file,
41                None => files
42                    .entry(m.path.clone())
43                    .or_insert(cx.workspace.load(&m.path)?),
44            };
45            let replacement = intent.template.expand(m, file.source()).map_err(|source| {
46                EngineError::Template {
47                    path: m.path.clone(),
48                    line: m.start.line,
49                    source,
50                }
51            })?;
52            change.edit(&m.path, Edit::replace(m.span, replacement));
53        }
54        Planned::of(cx.workspace, change, |_, files| Rewrite {
55            intent: intent.clone(),
56            applied: false,
57            history_id: None,
58            files,
59        })
60    }
61}