//! Dev containers as the backend sees them: the Dev Containers CLI, and which containers a //! window is open in. use ide_core::{IdeError, IdeResult}; use parking_lot::Mutex; use std::path::{Path, PathBuf}; use std::sync::Arc; /// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`. pub fn cli(data_dir: &Path) -> IdeResult { ide_tools::Tools::new(data_dir) .info("devcontainer", &[]) .ok() .and_then(|t| t.path) .map(ide_core::IpcPath::into_path_buf) .ok_or_else(|| { IdeError::unavailable( "The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.", ) }) } /// The containers a window is attached to (Reopen in Container), by id. A container may be held /// by more than one window. #[derive(Default)] pub struct AttachedContainers(Mutex>); impl AttachedContainers { /// Marks `id` attached until the returned guard is dropped. pub fn hold(self: &Arc, id: &str) -> AttachedContainer { self.0.lock().push(id.to_owned()); AttachedContainer { set: self.clone(), id: id.to_owned() } } /// Whether a window is attached to the container `id` (a full id or a prefix of one). pub fn contains(&self, id: &str) -> bool { !id.is_empty() && self.0.lock().iter().any(|held| held.starts_with(id) || id.starts_with(held.as_str())) } } /// A window's attachment to a container, released on drop. pub struct AttachedContainer { set: Arc, id: String, } impl Drop for AttachedContainer { fn drop(&mut self) { let mut held = self.set.0.lock(); if let Some(at) = held.iter().position(|id| *id == self.id) { held.remove(at); } } } #[cfg(test)] mod tests { use super::*; #[test] fn a_container_stays_attached_until_every_window_released_it() { let set = Arc::new(AttachedContainers::default()); let id = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8"; let (first, second) = (set.hold(id), set.hold(id)); assert!(set.contains(id) && set.contains(&id[..12])); assert!(!set.contains("ffffffffffff") && !set.contains("")); drop(first); assert!(set.contains(id)); drop(second); assert!(!set.contains(id)); } }