Skip to main content

pray_core/verify/
mod.rs

1mod format;
2mod integrity;
3mod locked_dest;
4pub mod position;
5mod provisioned;
6
7use crate::hashing::normalize_line_endings;
8use crate::lockfile::{Lockfile, ManagedSpanRecord};
9use crate::render::{render_project, RenderedTarget};
10use crate::render_reconcile::{reconcile_rendered_content, retired_span_checksums};
11use crate::resolve::ResolvedProject;
12use crate::{PrayError, PrayResult};
13use format::format_drift_report;
14pub use format::format_verification_report;
15use integrity::push_package_lock_findings;
16pub use locked_dest::{find_orphan_marker_findings, inspect_locked_destinations};
17use locked_dest::{find_orphan_marker_findings_from_markers, marker_positions};
18use position::{format_position_drift_message, summarize_position_drift};
19use std::collections::{BTreeMap, BTreeSet};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct VerificationFinding {
23    pub kind: String,
24    pub message: String,
25}
26
27#[derive(Debug, Clone, Default)]
28pub struct VerificationReport {
29    pub findings: Vec<VerificationFinding>,
30}
31
32impl VerificationReport {
33    pub fn is_clean(&self) -> bool {
34        self.findings.is_empty()
35    }
36
37    pub fn has_warnings(&self) -> bool {
38        self.findings.iter().any(VerificationFinding::is_warning)
39    }
40
41    pub fn has_errors(&self) -> bool {
42        self.findings.iter().any(VerificationFinding::is_error)
43    }
44}
45
46impl VerificationFinding {
47    pub fn is_warning(&self) -> bool {
48        matches!(self.kind.as_str(), "orphan_marker")
49    }
50
51    pub fn is_error(&self) -> bool {
52        !self.is_warning()
53    }
54}
55
56pub fn inspect_project(
57    project: &ResolvedProject,
58    lockfile: &Lockfile,
59) -> PrayResult<VerificationReport> {
60    let (report, _, _) = collect_verification_report(project, lockfile)?;
61    Ok(report)
62}
63
64pub fn verify_project(
65    project: &ResolvedProject,
66    lockfile: &Lockfile,
67    strict: bool,
68) -> PrayResult<VerificationReport> {
69    let report = inspect_project(project, lockfile)?;
70    if report.is_clean() {
71        return Ok(report);
72    }
73
74    if strict || report.has_errors() {
75        Err(PrayError::Verify(format_verification_report(&report)))
76    } else {
77        Ok(report)
78    }
79}
80
81type CollectedVerification = (
82    VerificationReport,
83    BTreeMap<String, String>,
84    BTreeMap<String, RenderedTarget>,
85);
86
87fn collect_verification_report(
88    project: &ResolvedProject,
89    lockfile: &Lockfile,
90) -> PrayResult<CollectedVerification> {
91    let mut report = VerificationReport::default();
92    let mut rendered_targets = BTreeMap::new();
93    let fresh_targets: BTreeMap<String, RenderedTarget> = render_project(project)?
94        .into_iter()
95        .map(|target| (target.path.to_string_lossy().to_string(), target))
96        .collect();
97    if project.manifest_hash != lockfile.manifest_hash {
98        report.findings.push(VerificationFinding {
99            kind: "verify_error".to_string(),
100            message:
101                "Prayfile changed since `Prayfile.lock` was generated. Run `pray install` to refresh the lockfile."
102                    .to_string(),
103        });
104    }
105
106    push_package_lock_findings(project, lockfile, &mut report.findings);
107
108    let mut target_spans: BTreeMap<String, Vec<&ManagedSpanRecord>> = BTreeMap::new();
109    for span in &lockfile.managed_span {
110        target_spans
111            .entry(span.target.clone())
112            .or_default()
113            .push(span);
114    }
115    for target_path in fresh_targets.keys() {
116        target_spans.entry(target_path.clone()).or_default();
117    }
118
119    for (target_path, spans) in target_spans {
120        let absolute_path = project.project_root.join(&target_path);
121        if !absolute_path.exists() {
122            report.findings.push(VerificationFinding {
123                kind: "verify_error".to_string(),
124                message: format!(
125                    "Rendered file `{}` is missing. Run `pray install` to generate it.",
126                    target_path
127                ),
128            });
129            continue;
130        }
131        let text = crate::render_file::read_destination_text(&absolute_path)?;
132        rendered_targets.insert(target_path.clone(), text.clone());
133        let lines: Vec<&str> = text.lines().collect();
134        let markers = marker_positions(&lines);
135        for span in &spans {
136            match markers.get(&span.id) {
137                None => report.findings.push(VerificationFinding {
138                    kind: "removed_prayer".to_string(),
139                    message: format!(
140                        "`{}` is missing managed marker `{}` for `{}::{}`. Run `pray install` to restore the managed span.",
141                        target_path, span.id, span.package, span.export
142                    ),
143                }),
144                Some((_, _, checksum)) => {
145                    if checksum != &span.ideal_checksum {
146                        report.findings.push(VerificationFinding {
147                            kind: "custom_implementation".to_string(),
148                            message: format!(
149                                "`{}` marker `{}` (`{}::{}`) was edited. Restore the managed block or run `pray install` to regenerate it.",
150                                target_path, span.id, span.package, span.export
151                            ),
152                        });
153                    }
154                }
155            }
156        }
157        let fresh_lines: Vec<&str> = fresh_targets
158            .get(&target_path)
159            .map(|fresh| fresh.content.lines().collect())
160            .unwrap_or_default();
161        if let Some(summary) = summarize_position_drift(
162            &target_path,
163            &spans,
164            &markers,
165            &lines,
166            fresh_targets
167                .contains_key(&target_path)
168                .then_some(fresh_lines.as_slice()),
169            &project.local_files,
170        ) {
171            report.findings.push(VerificationFinding {
172                kind: "position_drift".to_string(),
173                message: format_position_drift_message(&summary),
174            });
175        }
176        for finding in find_orphan_marker_findings_from_markers(&spans, &markers, &target_path) {
177            report.findings.push(finding);
178        }
179    }
180
181    provisioned::push_provisioned_and_local_findings(project, lockfile, &mut report.findings)?;
182
183    Ok((report, rendered_targets, fresh_targets))
184}
185
186pub fn drift_project(
187    project: &ResolvedProject,
188    lockfile: &Lockfile,
189) -> PrayResult<VerificationReport> {
190    let (mut report, rendered_targets, fresh_targets) =
191        collect_verification_report(project, lockfile)?;
192
193    let lock_targets = lockfile_targets(lockfile);
194    for (path, fresh_target) in &fresh_targets {
195        let retired = retired_span_checksums(Some(lockfile), fresh_target);
196        let on_disk = rendered_targets.get(path);
197        let normalized_expected = on_disk.map_or_else(
198            || normalize_line_endings(&fresh_target.content),
199            |text| {
200                normalize_line_endings(&reconcile_rendered_content(
201                    text,
202                    &fresh_target.content,
203                    &retired,
204                ))
205            },
206        );
207        let normalized_on_disk = on_disk.map(|text| normalize_line_endings(text));
208        let matches = normalized_on_disk.as_ref() == Some(&normalized_expected);
209        if !matches {
210            report.findings.push(VerificationFinding {
211                kind: "renderer_drift".to_string(),
212                message: format!("{path} differs from fresh render"),
213            });
214        }
215        if !lock_targets.contains(path) {
216            report.findings.push(VerificationFinding {
217                kind: "renderer_drift".to_string(),
218                message: format!("{path} is not tracked in lockfile"),
219            });
220        }
221    }
222
223    if report.findings.is_empty() {
224        Ok(report)
225    } else {
226        Err(PrayError::Verify(format_drift_report(&report)))
227    }
228}
229
230fn lockfile_targets(lockfile: &Lockfile) -> BTreeSet<String> {
231    lockfile
232        .target
233        .iter()
234        .flat_map(|target| target.outputs.iter().cloned())
235        .collect()
236}