| 1 | use std::env::VarError; |
| 2 | use std::ffi::{OsStr, OsString}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use super::discovery::DiscoveryConfig; |
| 7 | use super::registry::PluginRegistry; |
| 8 | |
| 9 | /// Immutable environment inherited from the host before workspace dotenv is |
| 10 | /// loaded. Reviewed plugins may resolve only values from this snapshot. |
| 11 | #[derive(Clone, Default)] |
| 12 | pub struct HostEnvironment { |
| 13 | entries: Arc<[(OsString, OsString)]>, |
| 14 | } |
| 15 | |
| 16 | impl std::fmt::Debug for HostEnvironment { |
| 17 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 18 | formatter.write_str("HostEnvironment(<captured environment>)") |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | impl HostEnvironment { |
| 23 | #[must_use] |
| 24 | pub fn capture() -> Self { |
| 25 | Self { |
| 26 | entries: std::env::vars_os().collect::<Vec<_>>().into(), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | #[cfg(any(test, feature = "test-support"))] |
| 31 | #[must_use] |
| 32 | pub fn from_entries(entries: impl IntoIterator<Item = (OsString, OsString)>) -> Self { |
| 33 | Self { |
| 34 | entries: entries.into_iter().collect::<Vec<_>>().into(), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[must_use] |
| 39 | pub fn entries(&self) -> &[(OsString, OsString)] { |
| 40 | &self.entries |
| 41 | } |
| 42 | |
| 43 | #[must_use] |
| 44 | pub fn get_os(&self, name: &OsStr) -> Option<&OsStr> { |
| 45 | self.entries |
| 46 | .iter() |
| 47 | .rev() |
| 48 | .find(|(key, _)| environment_names_equal(key, name)) |
| 49 | .map(|(_, value)| value.as_os_str()) |
| 50 | } |
| 51 | |
| 52 | pub fn var(&self, name: &str) -> Result<String, VarError> { |
| 53 | let Some(value) = self.get_os(OsStr::new(name)) else { |
| 54 | return Err(VarError::NotPresent); |
| 55 | }; |
| 56 | value |
| 57 | .to_str() |
| 58 | .map(str::to_owned) |
| 59 | .ok_or_else(|| VarError::NotUnicode(value.to_os_string())) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | fn environment_names_equal(left: &OsStr, right: &OsStr) -> bool { |
| 64 | #[cfg(windows)] |
| 65 | { |
| 66 | left.to_string_lossy() |
| 67 | .eq_ignore_ascii_case(&right.to_string_lossy()) |
| 68 | } |
| 69 | #[cfg(not(windows))] |
| 70 | { |
| 71 | left == right |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// Process-lifetime plugin discovery inputs captured before repository-local |
| 76 | /// dotenv files can affect the process environment. |
| 77 | #[derive(Debug, Clone)] |
| 78 | pub struct PluginDiscoveryContext { |
| 79 | user_plugins_dir: PathBuf, |
| 80 | state_path: PathBuf, |
| 81 | builtin_plugin_dirs: Arc<[PathBuf]>, |
| 82 | host_environment: Arc<HostEnvironment>, |
| 83 | managed_policy_path: Result<PathBuf, String>, |
| 84 | } |
| 85 | |
| 86 | impl PluginDiscoveryContext { |
| 87 | #[must_use] |
| 88 | pub fn capture_pre_dotenv() -> Arc<Self> { |
| 89 | let user_plugins_dir = super::discovery::default_user_plugins_dir(); |
| 90 | let state_path = user_plugins_dir.join("state.json"); |
| 91 | let host_environment = Arc::new(HostEnvironment::capture()); |
| 92 | let managed_policy_path = super::managed_policy::resolve_managed_policy_path( |
| 93 | &state_path, |
| 94 | Some(host_environment.as_ref()), |
| 95 | ); |
| 96 | Arc::new(Self { |
| 97 | state_path, |
| 98 | user_plugins_dir, |
| 99 | builtin_plugin_dirs: super::builtin::materialized_dirs().into(), |
| 100 | host_environment, |
| 101 | managed_policy_path, |
| 102 | }) |
| 103 | } |
| 104 | |
| 105 | #[cfg(any(test, feature = "test-support"))] |
| 106 | #[must_use] |
| 107 | pub fn from_config_and_environment( |
| 108 | config: &DiscoveryConfig, |
| 109 | host_environment: HostEnvironment, |
| 110 | ) -> Arc<Self> { |
| 111 | let managed_policy_path = super::managed_policy::resolve_managed_policy_path( |
| 112 | &config.state_path, |
| 113 | Some(&host_environment), |
| 114 | ); |
| 115 | Arc::new(Self { |
| 116 | user_plugins_dir: config.user_plugins_dir.clone(), |
| 117 | state_path: config.state_path.clone(), |
| 118 | builtin_plugin_dirs: config.builtin_plugin_dirs.clone().into(), |
| 119 | host_environment: Arc::new(host_environment), |
| 120 | managed_policy_path, |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | pub(super) fn managed_policy_source(&self) -> Result<PathBuf, String> { |
| 125 | self.managed_policy_path.clone() |
| 126 | } |
| 127 | |
| 128 | #[must_use] |
| 129 | pub fn inspect_registry_for_workspace( |
| 130 | self: &Arc<Self>, |
| 131 | workspace: &Path, |
| 132 | ) -> Arc<PluginRegistry> { |
| 133 | let config = DiscoveryConfig { |
| 134 | workspace: workspace.to_path_buf(), |
| 135 | user_plugins_dir: self.user_plugins_dir.clone(), |
| 136 | workspace_plugins_dir: super::discovery::default_workspace_plugins_dir(workspace), |
| 137 | builtin_plugin_dirs: self.builtin_plugin_dirs.to_vec(), |
| 138 | state_path: self.state_path.clone(), |
| 139 | }; |
| 140 | Arc::new(super::discovery::discover_with_context( |
| 141 | &config, |
| 142 | Arc::clone(self), |
| 143 | )) |
| 144 | } |
| 145 | |
| 146 | #[must_use] |
| 147 | pub fn registry_for_workspace(self: &Arc<Self>, workspace: &Path) -> Arc<PluginRegistry> { |
| 148 | let mut registry = self.inspect_registry_for_workspace(workspace); |
| 149 | let registry_mut = Arc::make_mut(&mut registry); |
| 150 | // An upgrade re-roots the built-ins; keep their review (K4). |
| 151 | registry_mut.carry_forward_builtin_trust(); |
| 152 | // Only after carry-forward: retiring superseded built-in records is |
| 153 | // safe once this build holds its own. Unit tests call the collector |
| 154 | // directly so that no test ever mutates a home implicitly. |
| 155 | #[cfg(not(any(test, feature = "test-support")))] |
| 156 | registry_mut.retire_withdrawn_bundles(); |
| 157 | #[cfg(not(any(test, feature = "test-support")))] |
| 158 | registry_mut.collect_garbage_at_startup(); |
| 159 | #[cfg(not(any(test, feature = "test-support")))] |
| 160 | registry_mut.reconcile_missing_stages(); |
| 161 | registry |
| 162 | } |
| 163 | |
| 164 | #[must_use] |
| 165 | pub fn host_environment(&self) -> Arc<HostEnvironment> { |
| 166 | Arc::clone(&self.host_environment) |
| 167 | } |
| 168 | |
| 169 | /// The pre-dotenv user plugins root (`~/.codewhale/plugins`). Exposed for |
| 170 | /// the install on-ramp (#5182), which must fetch into exactly the root |
| 171 | /// this context discovers from. |
| 172 | #[must_use] |
| 173 | pub fn user_plugins_dir(&self) -> &Path { |
| 174 | &self.user_plugins_dir |
| 175 | } |
| 176 | |
| 177 | #[must_use] |
| 178 | pub fn catalog_stamp_for_workspace( |
| 179 | &self, |
| 180 | workspace: &Path, |
| 181 | ) -> super::discovery::PluginCatalogStamp { |
| 182 | let mut roots = vec![ |
| 183 | self.user_plugins_dir.clone(), |
| 184 | super::discovery::default_workspace_plugins_dir(workspace), |
| 185 | ]; |
| 186 | roots.extend(self.builtin_plugin_dirs.iter().cloned()); |
| 187 | super::discovery::PluginCatalogStamp::capture(roots, &self.state_path) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | #[cfg(test)] |
| 192 | mod tests { |
| 193 | use std::ffi::OsString; |
| 194 | use std::fs; |
| 195 | |
| 196 | use super::{HostEnvironment, PluginDiscoveryContext}; |
| 197 | |
| 198 | #[test] |
| 199 | fn host_environment_is_an_immutable_value_snapshot() { |
| 200 | let snapshot = HostEnvironment::from_entries([( |
| 201 | OsString::from("PLUGIN_TOKEN"), |
| 202 | OsString::from("before"), |
| 203 | )]); |
| 204 | |
| 205 | assert_eq!(snapshot.var("PLUGIN_TOKEN").unwrap(), "before"); |
| 206 | assert!(snapshot.var("MISSING").is_err()); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn discovery_roots_are_frozen_before_later_environment_changes() { |
| 211 | let _lock = codewhale_runtime::test_support::lock_test_env(); |
| 212 | let temp = tempfile::tempdir().unwrap(); |
| 213 | let first_home = temp.path().join("first-home"); |
| 214 | let second_home = temp.path().join("second-home"); |
| 215 | let workspace = temp.path().join("workspace"); |
| 216 | fs::create_dir_all(&workspace).unwrap(); |
| 217 | let _first = |
| 218 | codewhale_runtime::test_support::EnvVarGuard::set("CODEWHALE_HOME", &first_home); |
| 219 | let context = PluginDiscoveryContext::capture_pre_dotenv(); |
| 220 | let _second = |
| 221 | codewhale_runtime::test_support::EnvVarGuard::set("CODEWHALE_HOME", &second_home); |
| 222 | |
| 223 | for (home, name) in [(&first_home, "before"), (&second_home, "after")] { |
| 224 | let bundle = home.join("plugins").join(name); |
| 225 | fs::create_dir_all(&bundle).unwrap(); |
| 226 | fs::write( |
| 227 | bundle.join("plugin.toml"), |
| 228 | format!("schema_version = 1\n[plugin]\nname = \"{name}\"\nversion = \"1.0.0\"\n"), |
| 229 | ) |
| 230 | .unwrap(); |
| 231 | } |
| 232 | |
| 233 | let registry = context.registry_for_workspace(&workspace); |
| 234 | assert!(registry.get("before").is_some()); |
| 235 | assert!(registry.get("after").is_none()); |
| 236 | assert_eq!( |
| 237 | registry.state_path(), |
| 238 | Some(first_home.join("plugins/state.json").as_path()) |
| 239 | ); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn contextless_rediscovery_remains_empty_and_tracks_the_requested_workspace() { |
| 244 | let temp = tempfile::tempdir().unwrap(); |
| 245 | let workspace = temp.path().join("workspace"); |
| 246 | let next_workspace = temp.path().join("next-workspace"); |
| 247 | let bundle = next_workspace.join(".codewhale/plugins/ambient"); |
| 248 | fs::create_dir_all(&bundle).unwrap(); |
| 249 | fs::write( |
| 250 | bundle.join("plugin.toml"), |
| 251 | "schema_version = 1\n[plugin]\nname = \"ambient\"\nversion = \"1.0.0\"\n", |
| 252 | ) |
| 253 | .unwrap(); |
| 254 | |
| 255 | let registry = |
| 256 | crate::PluginRegistry::empty(&workspace).rediscover_for_workspace(&next_workspace); |
| 257 | assert!(registry.is_empty()); |
| 258 | assert_eq!(registry.workspace(), next_workspace); |
| 259 | } |
| 260 | } |
| 261 |