Skip to main content

pray_core/
package_spec_hash.rs

1use super::PackageSpec;
2use crate::hashing::sha256_prefixed;
3use crate::PrayResult;
4use std::collections::BTreeMap;
5
6impl PackageSpec {
7    pub fn canonicalized(&self) -> Self {
8        let mut package = self.clone();
9        package.files.sort();
10        package.authors.sort();
11        package.maintainers.sort();
12        package.targets.sort();
13        package.dependencies.sort_by(|left, right| {
14            left.name
15                .cmp(&right.name)
16                .then(left.constraint.cmp(&right.constraint))
17                .then(left.optional.cmp(&right.optional))
18        });
19        package
20    }
21
22    pub fn validate_relative_paths(&self) -> PrayResult<()> {
23        use crate::paths::validate_package_relative_path;
24        use std::path::Path;
25        for file in &self.files {
26            validate_package_relative_path(Path::new(file))?;
27        }
28        for export in self.exports.values() {
29            validate_package_relative_path(Path::new(&export.path))?;
30            if let Some(default_path) = &export.default_path {
31                validate_package_relative_path(Path::new(default_path))?;
32            }
33        }
34        for skill in self.skills.values() {
35            validate_package_relative_path(Path::new(&skill.path))?;
36        }
37        for template in self.templates.values() {
38            validate_package_relative_path(Path::new(&template.path))?;
39        }
40        Ok(())
41    }
42
43    pub fn tree_hash_for_root(&self, root: &std::path::Path) -> PrayResult<String> {
44        self.validate_relative_paths()?;
45        let file_bytes = crate::resolve_exports::load_package_file_bytes(root, self)?;
46        Self::tree_hash_from_file_bytes(&file_bytes)
47    }
48
49    pub fn tree_hash_from_file_bytes(file_bytes: &BTreeMap<String, Vec<u8>>) -> PrayResult<String> {
50        let mut entries = file_bytes
51            .iter()
52            .map(|(path, bytes)| (path.clone(), sha256_prefixed(bytes)))
53            .collect::<Vec<_>>();
54        entries.sort_by(|left, right| left.0.cmp(&right.0));
55
56        let mut serialized = String::new();
57        for (path, hash) in entries {
58            serialized.push_str("file\0regular\0");
59            serialized.push_str(&path);
60            serialized.push('\0');
61            serialized.push_str(&hash);
62            serialized.push('\n');
63        }
64        Ok(sha256_prefixed(serialized.as_bytes()))
65    }
66}