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