返回 CodeWhale
test_fixture.rs
根目录 / crates / plugins / src / test_fixture.rs
1 use std::fs;
2 use std::path::{Path, PathBuf};
3
4 use tempfile::TempDir;
5
6 use super::PluginRegistry;
7 use super::discovery::{DiscoveryConfig, discover_with_config};
8
9 pub struct FinalizedStagedBundle {
10 retained: Vec<(fs::File, fs::Permissions)>,
11 }
12
13 impl Drop for FinalizedStagedBundle {
14 fn drop(&mut self) {
15 let failures = self
16 .retained
17 .iter()
18 .filter_map(|(file, permissions)| {
19 super::registry::restore_staged_fixture_target(file, permissions).err()
20 })
21 .collect::<Vec<_>>();
22 if !failures.is_empty() {
23 let message = failures.join("; ");
24 if std::thread::panicking() {
25 eprintln!("failed to restore staged fixture permissions: {message}");
26 } else {
27 panic!("failed to restore staged fixture permissions: {message}");
28 }
29 }
30 }
31 }
32
33 pub fn finalize_staged_bundle(path: &Path) -> Result<FinalizedStagedBundle, String> {
34 fn retain(path: &Path, retained: &mut Vec<(fs::File, fs::Permissions)>) -> Result<(), String> {
35 let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
36 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
37 return Err("staged fixture contains a link or reparse point".to_string());
38 }
39 let file = super::registry::open_staged_fixture_target(path)?;
40 let metadata = file.metadata().map_err(|error| error.to_string())?;
41 if !metadata.is_dir() && !metadata.is_file() {
42 return Err("staged fixture contains an unexpected object".to_string());
43 }
44 retained.push((file, metadata.permissions()));
45 if metadata.is_dir() {
46 for entry in fs::read_dir(path).map_err(|error| error.to_string())? {
47 retain(&entry.map_err(|error| error.to_string())?.path(), retained)?;
48 }
49 }
50 Ok(())
51 }
52
53 let mut fixture = FinalizedStagedBundle {
54 retained: Vec::new(),
55 };
56 retain(path, &mut fixture.retained)?;
57 super::registry::harden_staged_tree(path)?;
58 Ok(fixture)
59 }
60
61 pub struct PluginTempDir(TempDir);
62
63 impl PluginTempDir {
64 pub fn new() -> std::io::Result<Self> {
65 TempDir::new().map(Self)
66 }
67
68 pub fn path(&self) -> &Path {
69 self.0.path()
70 }
71 }
72
73 impl Drop for PluginTempDir {
74 fn drop(&mut self) {
75 fn unlock_directories(path: &Path) -> std::io::Result<()> {
76 let metadata = fs::symlink_metadata(path)?;
77 if !metadata.is_dir()
78 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
79 {
80 return Ok(());
81 }
82 let directory =
83 super::registry::open_staged_fixture_target(path).map_err(std::io::Error::other)?;
84 let permissions = directory.metadata()?.permissions();
85 #[cfg(unix)]
86 let permissions = {
87 use std::os::unix::fs::PermissionsExt;
88 fs::Permissions::from_mode(permissions.mode() | 0o700)
89 };
90 super::registry::restore_staged_fixture_target(&directory, &permissions)
91 .map_err(std::io::Error::other)?;
92 for child in fs::read_dir(path)? {
93 unlock_directories(&child?.path())?;
94 }
95 Ok(())
96 }
97
98 let state = self.path().join("state");
99 let unlock_staged = || -> std::io::Result<()> {
100 let metadata = fs::symlink_metadata(&state)?;
101 if !metadata.is_dir()
102 || codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
103 {
104 return Ok(());
105 }
106 #[cfg(windows)]
107 let _state = codewhale_util::files::WindowsDirectory::open(&state)?;
108 unlock_directories(&state.join(".runtime"))
109 };
110 if let Err(error) = unlock_staged()
111 && error.kind() != std::io::ErrorKind::NotFound
112 {
113 eprintln!(
114 "could not unlock plugin test fixture {}: {error}",
115 self.path().display()
116 );
117 }
118 }
119 }
120
121 pub struct DeclarativePluginFixture {
122 _temp: PluginTempDir,
123 pub workspace: PathBuf,
124 pub marker: PathBuf,
125 pub config: DiscoveryConfig,
126 pub registry: PluginRegistry,
127 }
128
129 impl Default for DeclarativePluginFixture {
130 fn default() -> Self {
131 Self::new()
132 }
133 }
134
135 impl DeclarativePluginFixture {
136 pub fn new() -> Self {
137 let temp = PluginTempDir::new().expect("plugin fixture tempdir");
138 let workspace = temp.path().join("project");
139 let user_plugins_dir = temp.path().join("user");
140 let plugin = user_plugins_dir.join("runtime-demo");
141 let marker = workspace.join("plugin-hook-ran");
142 fs::create_dir_all(&workspace).expect("workspace");
143 fs::create_dir_all(plugin.join("commands")).expect("commands");
144 fs::create_dir_all(plugin.join("agents")).expect("agents");
145 fs::create_dir_all(plugin.join("hooks")).expect("hooks");
146 fs::write(
147 plugin.join("plugin.toml"),
148 "schema_version = 1\n[plugin]\nname = \"runtime-demo\"\nversion = \"1.0.0\"\n[commands]\npath = \"commands\"\n[agents]\npath = \"agents\"\n[hooks]\npath = \"hooks\"\n",
149 )
150 .expect("manifest");
151 fs::write(
152 plugin.join("commands/plugin-hello.md"),
153 "---\ndescription: Send a reviewed plugin greeting\n---\nhello from plugin $ARGUMENTS",
154 )
155 .expect("command");
156 fs::write(
157 plugin.join("agents/plugin-scout.toml"),
158 "id = \"plugin-scout\"\ndisplay_name = \"Plugin Scout\"\ndescription = \"Reviewed staged scout\"\nrole_hint = \"scout\"\n",
159 )
160 .expect("agent");
161 let command = format!("printf plugin-hook-ran > {}", marker.display());
162 fs::write(
163 plugin.join("hooks/hooks.toml"),
164 format!(
165 "enabled = true\n\n[[hooks]]\nname = \"plugin-start\"\nevent = \"session_start\"\ncommand = {}\ncontinue_on_error = false\n",
166 toml::Value::String(command)
167 ),
168 )
169 .expect("hooks");
170
171 let config = DiscoveryConfig {
172 workspace: workspace.clone(),
173 user_plugins_dir,
174 workspace_plugins_dir: workspace.join(".codewhale/plugins"),
175 builtin_plugin_dirs: Vec::new(),
176 state_path: temp.path().join("state/plugin-state.json"),
177 };
178 let mut registry = discover_with_config(&config);
179 registry.trust("runtime-demo").expect("trust plugin");
180 registry.enable("runtime-demo").expect("enable plugin");
181 let registry = discover_with_config(&config);
182 assert!(
183 registry.is_active("runtime-demo"),
184 "restart restores plugin"
185 );
186
187 Self {
188 _temp: temp,
189 workspace,
190 marker,
191 config,
192 registry,
193 }
194 }
195
196 pub fn disable_from_fresh_registry(&self) -> PluginRegistry {
197 let mut registry = discover_with_config(&self.config);
198 registry.disable("runtime-demo").expect("disable plugin");
199 discover_with_config(&self.config)
200 }
201
202 pub fn revoke_from_fresh_registry(&self) -> PluginRegistry {
203 let mut registry = discover_with_config(&self.config);
204 registry
205 .revoke_trust("runtime-demo")
206 .expect("revoke plugin");
207 discover_with_config(&self.config)
208 }
209 }
210
210 lines RUST