toolchain.rs

  1//! Provides support for language toolchains.
  2//!
  3//! A language can have associated toolchains,
  4//! which is a set of tools used to interact with the projects written in said language.
  5//! For example, a Python project can have an associated virtual environment; a Rust project can have a toolchain override.
  6
  7use std::{
  8    path::{Path, PathBuf},
  9    sync::Arc,
 10};
 11
 12use async_trait::async_trait;
 13use collections::HashMap;
 14use fs::Fs;
 15use gpui::{AsyncApp, SharedString};
 16use settings::WorktreeId;
 17use task::ShellKind;
 18
 19use crate::{LanguageName, ManifestName};
 20
 21/// Represents a single toolchain.
 22#[derive(Clone, Eq, Debug)]
 23pub struct Toolchain {
 24    /// User-facing label
 25    pub name: SharedString,
 26    pub path: SharedString,
 27    pub language_name: LanguageName,
 28    /// Full toolchain data (including language-specific details)
 29    pub as_json: serde_json::Value,
 30}
 31
 32/// Declares a scope of a toolchain added by user.
 33///
 34/// When the user adds a toolchain, we give them an option to see that toolchain in:
 35/// - All of their projects
 36/// - A project they're currently in.
 37/// - Only in the subproject they're currently in.
 38#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
 39pub enum ToolchainScope {
 40    Subproject(WorktreeId, Arc<Path>),
 41    Project,
 42    /// Available in all projects on this box. It wouldn't make sense to show suggestions across machines.
 43    Global,
 44}
 45
 46impl ToolchainScope {
 47    pub fn label(&self) -> &'static str {
 48        match self {
 49            ToolchainScope::Subproject(_, _) => "Subproject",
 50            ToolchainScope::Project => "Project",
 51            ToolchainScope::Global => "Global",
 52        }
 53    }
 54
 55    pub fn description(&self) -> &'static str {
 56        match self {
 57            ToolchainScope::Subproject(_, _) => {
 58                "Available only in the subproject you're currently in."
 59            }
 60            ToolchainScope::Project => "Available in all locations in your current project.",
 61            ToolchainScope::Global => "Available in all of your projects on this machine.",
 62        }
 63    }
 64}
 65
 66impl std::hash::Hash for Toolchain {
 67    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 68        let Self {
 69            name,
 70            path,
 71            language_name,
 72            as_json: _,
 73        } = self;
 74        name.hash(state);
 75        path.hash(state);
 76        language_name.hash(state);
 77    }
 78}
 79
 80impl PartialEq for Toolchain {
 81    fn eq(&self, other: &Self) -> bool {
 82        let Self {
 83            name,
 84            path,
 85            language_name,
 86            as_json: _,
 87        } = self;
 88        // Do not use as_json for comparisons; it shouldn't impact equality, as it's not user-surfaced.
 89        // Thus, there could be multiple entries that look the same in the UI.
 90        (name, path, language_name).eq(&(&other.name, &other.path, &other.language_name))
 91    }
 92}
 93
 94#[async_trait]
 95pub trait ToolchainLister: Send + Sync + 'static {
 96    /// List all available toolchains for a given path.
 97    async fn list(
 98        &self,
 99        worktree_root: PathBuf,
100        subroot_relative_path: Arc<Path>,
101        project_env: Option<HashMap<String, String>>,
102    ) -> ToolchainList;
103
104    /// Given a user-created toolchain, resolve lister-specific details.
105    /// Put another way: fill in the details of the toolchain so the user does not have to.
106    async fn resolve(
107        &self,
108        path: PathBuf,
109        project_env: Option<HashMap<String, String>>,
110    ) -> anyhow::Result<Toolchain>;
111
112    async fn activation_script(
113        &self,
114        toolchain: &Toolchain,
115        shell: ShellKind,
116        fs: &dyn Fs,
117    ) -> Vec<String>;
118    /// Returns various "static" bits of information about this toolchain lister. This function should be pure.
119    fn meta(&self) -> ToolchainMetadata;
120}
121
122#[derive(Clone, PartialEq, Eq, Hash)]
123pub struct ToolchainMetadata {
124    /// Returns a term which we should use in UI to refer to toolchains produced by a given `[ToolchainLister]`.
125    pub term: SharedString,
126    /// A user-facing placeholder describing the semantic meaning of a path to a new toolchain.
127    pub new_toolchain_placeholder: SharedString,
128    /// The name of the manifest file for this toolchain.
129    pub manifest_name: ManifestName,
130}
131
132#[async_trait(?Send)]
133pub trait LanguageToolchainStore: Send + Sync + 'static {
134    async fn active_toolchain(
135        self: Arc<Self>,
136        worktree_id: WorktreeId,
137        relative_path: Arc<Path>,
138        language_name: LanguageName,
139        cx: &mut AsyncApp,
140    ) -> Option<Toolchain>;
141}
142
143pub trait LocalLanguageToolchainStore: Send + Sync + 'static {
144    fn active_toolchain(
145        self: Arc<Self>,
146        worktree_id: WorktreeId,
147        relative_path: &Arc<Path>,
148        language_name: LanguageName,
149        cx: &mut AsyncApp,
150    ) -> Option<Toolchain>;
151}
152
153#[async_trait(?Send)]
154impl<T: LocalLanguageToolchainStore> LanguageToolchainStore for T {
155    async fn active_toolchain(
156        self: Arc<Self>,
157        worktree_id: WorktreeId,
158        relative_path: Arc<Path>,
159        language_name: LanguageName,
160        cx: &mut AsyncApp,
161    ) -> Option<Toolchain> {
162        self.active_toolchain(worktree_id, &relative_path, language_name, cx)
163    }
164}
165
166type DefaultIndex = usize;
167#[derive(Default, Clone, Debug)]
168pub struct ToolchainList {
169    pub toolchains: Vec<Toolchain>,
170    pub default: Option<DefaultIndex>,
171    pub groups: Box<[(usize, SharedString)]>,
172}
173
174impl ToolchainList {
175    pub fn toolchains(&self) -> &[Toolchain] {
176        &self.toolchains
177    }
178    pub fn default_toolchain(&self) -> Option<Toolchain> {
179        self.default.and_then(|ix| self.toolchains.get(ix)).cloned()
180    }
181    pub fn group_for_index(&self, index: usize) -> Option<(usize, SharedString)> {
182        if index >= self.toolchains.len() {
183            return None;
184        }
185        let first_equal_or_greater = self
186            .groups
187            .partition_point(|(group_lower_bound, _)| group_lower_bound <= &index);
188        self.groups
189            .get(first_equal_or_greater.checked_sub(1)?)
190            .cloned()
191    }
192}