graphrt_plugin/
discover.rs1use std::path::{Path, PathBuf};
4
5use sha2::{Digest, Sha256};
6
7use crate::error::PluginError;
8use crate::manifest::{LoadedManifest, manifest_in};
9
10pub const PLUGIN_PATH_ENV: &str = "GRAPHRT_PLUGIN_PATH";
12
13pub fn default_plugin_paths() -> Vec<PathBuf> {
15 let mut paths: Vec<PathBuf> = match std::env::var_os(PLUGIN_PATH_ENV) {
16 Some(v) => std::env::split_paths(&v).filter(|p| !p.as_os_str().is_empty()).collect(),
17 None => Vec::new(),
18 };
19 if let Some(dir) = default_install_dir() {
20 paths.push(dir);
21 }
22 paths
23}
24
25pub fn default_install_dir() -> Option<PathBuf> {
27 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
28 Some(PathBuf::from(home).join(".graphrt").join("plugins"))
29}
30
31pub fn discover(paths: &[PathBuf]) -> Vec<PathBuf> {
35 let mut found = Vec::new();
36 for path in paths {
37 if let Some(manifest) = manifest_in(path) {
38 found.push(manifest);
39 continue;
40 }
41 let Ok(entries) = std::fs::read_dir(path) else { continue };
42 let mut dirs: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();
43 dirs.sort();
44 found.extend(dirs.iter().filter_map(|d| manifest_in(d)));
45 }
46 found
47}
48
49pub fn sha256_file(path: &Path) -> Result<String, PluginError> {
51 use std::io::Read;
52 let io = |e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
53 let mut file = std::fs::File::open(path).map_err(io)?;
54 let mut hasher = Sha256::new();
55 let mut buf = vec![0u8; 64 * 1024];
56 loop {
57 let n = file.read(&mut buf).map_err(io)?;
58 if n == 0 {
59 break;
60 }
61 hasher.update(buf.get(..n).unwrap_or_default());
62 }
63 Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
64}
65
66pub fn verify_checksums(plugin: &LoadedManifest) -> Result<(), PluginError> {
74 for (file, expected) in &plugin.manifest.checksums {
75 let path = plugin.resolve(file);
76 let meta = std::fs::symlink_metadata(&path)
77 .map_err(|e| PluginError::Io { path: path.clone(), message: e.to_string() })?;
78 if !meta.file_type().is_file() {
79 return Err(PluginError::Manifest(format!(
80 "plugin `{}`: checksum path `{file}` must be a regular file (not a symlink or directory)",
81 plugin.manifest.name
82 )));
83 }
84 let actual = sha256_file(&path)?;
85 if !actual.eq_ignore_ascii_case(expected.trim()) {
86 return Err(PluginError::Checksum { plugin: plugin.manifest.name.clone(), file: file.clone() });
87 }
88 }
89 Ok(())
90}
91
92pub fn install_from_dir(src: &Path, dest_root: &Path) -> Result<LoadedManifest, PluginError> {
95 let source = LoadedManifest::from_dir(src)?;
96 verify_checksums(&source)?;
97 let target = dest_root.join(&source.manifest.name);
98 let staging = dest_root.join(format!(".{}.installing", source.manifest.name));
99 let io = |path: &Path, e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
100 std::fs::create_dir_all(dest_root).map_err(|e| io(dest_root, e))?;
101 if staging.exists() {
102 std::fs::remove_dir_all(&staging).map_err(|e| io(&staging, e))?;
103 }
104 copy_dir(&source.dir, &staging)?;
105 if target.exists() {
106 std::fs::remove_dir_all(&target).map_err(|e| io(&target, e))?;
107 }
108 std::fs::rename(&staging, &target).map_err(|e| io(&target, e))?;
109 LoadedManifest::from_dir(&target)
110}
111
112#[cfg(feature = "git")]
115pub fn install_from_git(url: &str, rev: Option<&str>, dest_root: &Path) -> Result<LoadedManifest, PluginError> {
116 if url.starts_with('-') || rev.is_some_and(|r| r.starts_with('-')) {
117 return Err(PluginError::Install("invalid git url or revision".into()));
118 }
119 let tmp = std::env::temp_dir().join(format!(
120 "graphrt-plugin-{}-{}",
121 std::process::id(),
122 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
123 ));
124 let mut cmd = std::process::Command::new("git");
125 cmd.args(["clone", "--depth", "1", "--quiet"]);
126 if let Some(rev) = rev {
127 cmd.args(["--branch", rev]);
128 }
129 cmd.arg("--").arg(url).arg(&tmp);
130 let output = cmd.output().map_err(|e| PluginError::Install(format!("cannot run git: {e}")))?;
131 if !output.status.success() {
132 let _cleanup = std::fs::remove_dir_all(&tmp);
133 return Err(PluginError::Install(format!(
134 "git clone failed: {}",
135 String::from_utf8_lossy(&output.stderr).trim()
136 )));
137 }
138 let result = install_from_dir(&tmp, dest_root);
139 let _cleanup = std::fs::remove_dir_all(&tmp);
140 result
141}
142
143fn copy_dir(src: &Path, dst: &Path) -> Result<(), PluginError> {
144 let io = |path: &Path, e: std::io::Error| PluginError::Io { path: path.to_path_buf(), message: e.to_string() };
145 std::fs::create_dir_all(dst).map_err(|e| io(dst, e))?;
146 for entry in std::fs::read_dir(src).map_err(|e| io(src, e))? {
147 let entry = entry.map_err(|e| io(src, e))?;
148 let name = entry.file_name();
149 if name == ".git" {
150 continue;
151 }
152 let from = entry.path();
153 let to = dst.join(&name);
154 let file_type = entry.file_type().map_err(|e| io(&from, e))?;
155 if file_type.is_dir() {
156 copy_dir(&from, &to)?;
157 } else if file_type.is_file() {
158 std::fs::copy(&from, &to).map_err(|e| io(&from, e))?;
159 }
160 }
162 Ok(())
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 fn temp(name: &str) -> PathBuf {
170 let p = std::env::temp_dir().join(format!("graphrt-plugin-test-{}-{name}", std::process::id()));
171 let _ = std::fs::remove_dir_all(&p);
172 std::fs::create_dir_all(&p).unwrap();
173 p
174 }
175
176 fn write_plugin(dir: &Path, name: &str, checksums: serde_json::Value) {
177 std::fs::create_dir_all(dir).unwrap();
178 std::fs::write(dir.join("run.sh"), "echo hi").unwrap();
179 let manifest = serde_json::json!({
180 "name": name, "runtime": "process", "command": "sh", "args": ["run.sh"], "checksums": checksums
181 });
182 std::fs::write(dir.join("graphrt-plugin.json"), manifest.to_string()).unwrap();
183 }
184
185 #[test]
186 fn discovers_and_installs() {
187 let root = temp("discover");
188 write_plugin(&root.join("b"), "b", serde_json::json!({}));
189 write_plugin(&root.join("a"), "a", serde_json::json!({}));
190 std::fs::create_dir_all(root.join("empty")).unwrap();
191 let found = discover(&[root.clone(), root.join("missing")]);
192 assert_eq!(found.len(), 2);
193 assert!(found[0].ends_with("a/graphrt-plugin.json"));
194 assert_eq!(discover(&[root.join("a")]).len(), 1);
196
197 let dest = temp("install");
198 let installed = install_from_dir(&root.join("a"), &dest).unwrap();
199 assert_eq!(installed.manifest.name, "a");
200 assert!(dest.join("a").join("run.sh").is_file());
201 assert!(install_from_dir(&root.join("a"), &dest).is_ok());
203 }
204
205 #[test]
206 fn checksums_are_enforced() {
207 let root = temp("checksum");
208 let digest = {
209 std::fs::write(root.join("probe"), "echo hi").unwrap();
210 sha256_file(&root.join("probe")).unwrap()
211 };
212 write_plugin(&root.join("ok"), "ok", serde_json::json!({"run.sh": digest}));
213 assert!(verify_checksums(&LoadedManifest::from_dir(&root.join("ok")).unwrap()).is_ok());
214 write_plugin(&root.join("bad"), "bad", serde_json::json!({"run.sh": "00ff"}));
215 let bad = LoadedManifest::from_dir(&root.join("bad")).unwrap();
216 assert!(matches!(verify_checksums(&bad), Err(PluginError::Checksum { .. })));
217 assert!(install_from_dir(&root.join("bad"), &temp("dest-bad")).is_err());
218 }
219
220 #[test]
221 fn sha256_known_value() {
222 let root = temp("sha");
223 std::fs::write(root.join("f"), "abc").unwrap();
224 assert_eq!(
225 sha256_file(&root.join("f")).unwrap(),
226 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
227 );
228 }
229}