task_inventory.rs

   1//! Project-wide storage of the tasks available, capable of updating itself from the sources set.
   2
   3use std::{
   4    borrow::Cow,
   5    cmp::{self, Reverse},
   6    collections::hash_map,
   7    path::PathBuf,
   8    sync::Arc,
   9};
  10
  11use anyhow::Result;
  12use collections::{HashMap, HashSet, VecDeque};
  13use dap::DapRegistry;
  14use gpui::{App, AppContext as _, Context, Entity, SharedString, Task, WeakEntity};
  15use itertools::Itertools;
  16use language::{
  17    Buffer, ContextLocation, ContextProvider, File, Language, LanguageToolchainStore, Location,
  18    language_settings::language_settings,
  19};
  20use lsp::{LanguageServerId, LanguageServerName};
  21use paths::{debug_task_file_name, task_file_name};
  22use settings::{InvalidSettingsError, parse_json_with_comments};
  23use task::{
  24    DebugScenario, ResolvedTask, TaskContext, TaskId, TaskTemplate, TaskTemplates, TaskVariables,
  25    VariableName,
  26};
  27use text::{BufferId, Point, ToPoint};
  28use util::{NumericPrefixWithSuffix, ResultExt as _, post_inc, rel_path::RelPath};
  29use worktree::WorktreeId;
  30
  31use crate::{task_store::TaskSettingsLocation, worktree_store::WorktreeStore};
  32
  33#[derive(Clone, Debug, Default)]
  34pub struct DebugScenarioContext {
  35    pub task_context: TaskContext,
  36    pub worktree_id: Option<WorktreeId>,
  37    pub active_buffer: Option<WeakEntity<Buffer>>,
  38}
  39
  40/// Inventory tracks available tasks for a given project.
  41pub struct Inventory {
  42    last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>,
  43    last_scheduled_scenarios: VecDeque<(DebugScenario, DebugScenarioContext)>,
  44    templates_from_settings: InventoryFor<TaskTemplate>,
  45    scenarios_from_settings: InventoryFor<DebugScenario>,
  46}
  47
  48impl std::fmt::Debug for Inventory {
  49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  50        f.debug_struct("Inventory")
  51            .field("last_scheduled_tasks", &self.last_scheduled_tasks)
  52            .field("last_scheduled_scenarios", &self.last_scheduled_scenarios)
  53            .field("templates_from_settings", &self.templates_from_settings)
  54            .field("scenarios_from_settings", &self.scenarios_from_settings)
  55            .finish()
  56    }
  57}
  58
  59// Helper trait for better error messages in [InventoryFor]
  60trait InventoryContents: Clone {
  61    const GLOBAL_SOURCE_FILE: &'static str;
  62    const LABEL: &'static str;
  63}
  64
  65impl InventoryContents for TaskTemplate {
  66    const GLOBAL_SOURCE_FILE: &'static str = "tasks.json";
  67    const LABEL: &'static str = "tasks";
  68}
  69
  70impl InventoryContents for DebugScenario {
  71    const GLOBAL_SOURCE_FILE: &'static str = "debug.json";
  72
  73    const LABEL: &'static str = "debug scenarios";
  74}
  75
  76#[derive(Debug)]
  77struct InventoryFor<T> {
  78    global: HashMap<PathBuf, Vec<T>>,
  79    worktree: HashMap<WorktreeId, HashMap<Arc<RelPath>, Vec<T>>>,
  80}
  81
  82impl<T: InventoryContents> InventoryFor<T> {
  83    fn worktree_scenarios(
  84        &self,
  85        worktree: WorktreeId,
  86    ) -> impl '_ + Iterator<Item = (TaskSourceKind, T)> {
  87        self.worktree
  88            .get(&worktree)
  89            .into_iter()
  90            .flatten()
  91            .flat_map(|(directory, templates)| {
  92                templates.iter().map(move |template| (directory, template))
  93            })
  94            .map(move |(directory, template)| {
  95                (
  96                    TaskSourceKind::Worktree {
  97                        id: worktree,
  98                        directory_in_worktree: directory.clone(),
  99                        id_base: Cow::Owned(format!(
 100                            "local worktree {} from directory {directory:?}",
 101                            T::LABEL
 102                        )),
 103                    },
 104                    template.clone(),
 105                )
 106            })
 107    }
 108
 109    fn global_scenarios(&self) -> impl '_ + Iterator<Item = (TaskSourceKind, T)> {
 110        self.global.iter().flat_map(|(file_path, templates)| {
 111            templates.iter().map(|template| {
 112                (
 113                    TaskSourceKind::AbsPath {
 114                        id_base: Cow::Owned(format!("global {}", T::GLOBAL_SOURCE_FILE)),
 115                        abs_path: file_path.clone(),
 116                    },
 117                    template.clone(),
 118                )
 119            })
 120        })
 121    }
 122}
 123
 124impl<T> Default for InventoryFor<T> {
 125    fn default() -> Self {
 126        Self {
 127            global: HashMap::default(),
 128            worktree: HashMap::default(),
 129        }
 130    }
 131}
 132
 133/// Kind of a source the tasks are fetched from, used to display more source information in the UI.
 134#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
 135pub enum TaskSourceKind {
 136    /// bash-like commands spawned by users, not associated with any path
 137    UserInput,
 138    /// Tasks from the worktree's .zed/task.json
 139    Worktree {
 140        id: WorktreeId,
 141        directory_in_worktree: Arc<RelPath>,
 142        id_base: Cow<'static, str>,
 143    },
 144    /// ~/.config/zed/task.json - like global files with task definitions, applicable to any path
 145    AbsPath {
 146        id_base: Cow<'static, str>,
 147        abs_path: PathBuf,
 148    },
 149    /// Languages-specific tasks coming from extensions.
 150    Language { name: SharedString },
 151    /// Language-specific tasks coming from LSP servers.
 152    Lsp {
 153        language_name: SharedString,
 154        server: LanguageServerId,
 155    },
 156}
 157
 158/// A collection of task contexts, derived from the current state of the workspace.
 159/// Only contains worktrees that are visible and with their root being a directory.
 160#[derive(Debug, Default)]
 161pub struct TaskContexts {
 162    /// A context, related to the currently opened item.
 163    /// Item can be opened from an invisible worktree, or any other, not necessarily active worktree.
 164    pub active_item_context: Option<(Option<WorktreeId>, Option<Location>, TaskContext)>,
 165    /// A worktree that corresponds to the active item, or the only worktree in the workspace.
 166    pub active_worktree_context: Option<(WorktreeId, TaskContext)>,
 167    /// If there are multiple worktrees in the workspace, all non-active ones are included here.
 168    pub other_worktree_contexts: Vec<(WorktreeId, TaskContext)>,
 169    pub lsp_task_sources: HashMap<LanguageServerName, Vec<BufferId>>,
 170    pub latest_selection: Option<text::Anchor>,
 171}
 172
 173impl TaskContexts {
 174    pub fn active_context(&self) -> Option<&TaskContext> {
 175        self.active_item_context
 176            .as_ref()
 177            .map(|(_, _, context)| context)
 178            .or_else(|| {
 179                self.active_worktree_context
 180                    .as_ref()
 181                    .map(|(_, context)| context)
 182            })
 183    }
 184
 185    pub fn location(&self) -> Option<&Location> {
 186        self.active_item_context
 187            .as_ref()
 188            .and_then(|(_, location, _)| location.as_ref())
 189    }
 190
 191    pub fn file(&self, cx: &App) -> Option<Arc<dyn File>> {
 192        self.active_item_context
 193            .as_ref()
 194            .and_then(|(_, location, _)| location.as_ref())
 195            .and_then(|location| location.buffer.read(cx).file().cloned())
 196    }
 197
 198    pub fn worktree(&self) -> Option<WorktreeId> {
 199        self.active_item_context
 200            .as_ref()
 201            .and_then(|(worktree_id, _, _)| worktree_id.as_ref())
 202            .or_else(|| {
 203                self.active_worktree_context
 204                    .as_ref()
 205                    .map(|(worktree_id, _)| worktree_id)
 206            })
 207            .copied()
 208    }
 209
 210    pub fn task_context_for_worktree_id(&self, worktree_id: WorktreeId) -> Option<&TaskContext> {
 211        self.active_worktree_context
 212            .iter()
 213            .chain(self.other_worktree_contexts.iter())
 214            .find(|(id, _)| *id == worktree_id)
 215            .map(|(_, context)| context)
 216    }
 217}
 218
 219impl TaskSourceKind {
 220    pub fn to_id_base(&self) -> String {
 221        match self {
 222            Self::UserInput => "oneshot".to_string(),
 223            Self::AbsPath { id_base, abs_path } => {
 224                format!("{id_base}_{}", abs_path.display())
 225            }
 226            Self::Worktree {
 227                id,
 228                id_base,
 229                directory_in_worktree,
 230            } => {
 231                format!("{id_base}_{id}_{}", directory_in_worktree.as_unix_str())
 232            }
 233            Self::Language { name } => format!("language_{name}"),
 234            Self::Lsp {
 235                server,
 236                language_name,
 237            } => format!("lsp_{language_name}_{server}"),
 238        }
 239    }
 240}
 241
 242impl Inventory {
 243    pub fn new(cx: &mut App) -> Entity<Self> {
 244        cx.new(|_| Self {
 245            last_scheduled_tasks: VecDeque::default(),
 246            last_scheduled_scenarios: VecDeque::default(),
 247            templates_from_settings: InventoryFor::default(),
 248            scenarios_from_settings: InventoryFor::default(),
 249        })
 250    }
 251
 252    pub fn scenario_scheduled(
 253        &mut self,
 254        scenario: DebugScenario,
 255        task_context: TaskContext,
 256        worktree_id: Option<WorktreeId>,
 257        active_buffer: Option<WeakEntity<Buffer>>,
 258    ) {
 259        self.last_scheduled_scenarios
 260            .retain(|(s, _)| s.label != scenario.label);
 261        self.last_scheduled_scenarios.push_front((
 262            scenario,
 263            DebugScenarioContext {
 264                task_context,
 265                worktree_id,
 266                active_buffer,
 267            },
 268        ));
 269        if self.last_scheduled_scenarios.len() > 5_000 {
 270            self.last_scheduled_scenarios.pop_front();
 271        }
 272    }
 273
 274    pub fn last_scheduled_scenario(&self) -> Option<&(DebugScenario, DebugScenarioContext)> {
 275        self.last_scheduled_scenarios.back()
 276    }
 277
 278    pub fn list_debug_scenarios(
 279        &self,
 280        task_contexts: &TaskContexts,
 281        lsp_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
 282        current_resolved_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
 283        add_current_language_tasks: bool,
 284        cx: &mut App,
 285    ) -> Task<(
 286        Vec<(DebugScenario, DebugScenarioContext)>,
 287        Vec<(TaskSourceKind, DebugScenario)>,
 288    )> {
 289        let mut scenarios = Vec::new();
 290
 291        if let Some(worktree_id) = task_contexts
 292            .active_worktree_context
 293            .iter()
 294            .chain(task_contexts.other_worktree_contexts.iter())
 295            .map(|context| context.0)
 296            .next()
 297        {
 298            scenarios.extend(self.worktree_scenarios_from_settings(worktree_id));
 299        }
 300        scenarios.extend(self.global_debug_scenarios_from_settings());
 301
 302        let last_scheduled_scenarios = self.last_scheduled_scenarios.iter().cloned().collect();
 303
 304        let adapter = task_contexts.location().and_then(|location| {
 305            let (file, language) = {
 306                let buffer = location.buffer.read(cx);
 307                (buffer.file(), buffer.language())
 308            };
 309            let language_name = language.as_ref().map(|l| l.name());
 310            let adapter = language_settings(language_name, file, cx)
 311                .debuggers
 312                .first()
 313                .map(SharedString::from)
 314                .or_else(|| {
 315                    language.and_then(|l| l.config().debuggers.first().map(SharedString::from))
 316                });
 317            adapter.map(|adapter| (adapter, DapRegistry::global(cx).locators()))
 318        });
 319        cx.background_spawn(async move {
 320            if let Some((adapter, locators)) = adapter {
 321                for (kind, task) in
 322                    lsp_tasks
 323                        .into_iter()
 324                        .chain(current_resolved_tasks.into_iter().filter(|(kind, _)| {
 325                            add_current_language_tasks
 326                                || !matches!(kind, TaskSourceKind::Language { .. })
 327                        }))
 328                {
 329                    let adapter = adapter.clone().into();
 330
 331                    for locator in locators.values() {
 332                        if let Some(scenario) = locator
 333                            .create_scenario(task.original_task(), task.display_label(), &adapter)
 334                            .await
 335                        {
 336                            scenarios.push((kind, scenario));
 337                            break;
 338                        }
 339                    }
 340                }
 341            }
 342            (last_scheduled_scenarios, scenarios)
 343        })
 344    }
 345
 346    pub fn task_template_by_label(
 347        &self,
 348        buffer: Option<Entity<Buffer>>,
 349        worktree_id: Option<WorktreeId>,
 350        label: &str,
 351        cx: &App,
 352    ) -> Task<Option<TaskTemplate>> {
 353        let (buffer_worktree_id, file, language) = buffer
 354            .map(|buffer| {
 355                let buffer = buffer.read(cx);
 356                let file = buffer.file().cloned();
 357                (
 358                    file.as_ref().map(|file| file.worktree_id(cx)),
 359                    file,
 360                    buffer.language().cloned(),
 361                )
 362            })
 363            .unwrap_or((None, None, None));
 364
 365        let tasks = self.list_tasks(file, language, worktree_id.or(buffer_worktree_id), cx);
 366        let label = label.to_owned();
 367        cx.background_spawn(async move {
 368            tasks
 369                .await
 370                .into_iter()
 371                .find(|(_, template)| template.label == label)
 372                .map(|val| val.1)
 373        })
 374    }
 375
 376    /// Pulls its task sources relevant to the worktree and the language given,
 377    /// returns all task templates with their source kinds, worktree tasks first, language tasks second
 378    /// and global tasks last. No specific order inside source kinds groups.
 379    pub fn list_tasks(
 380        &self,
 381        file: Option<Arc<dyn File>>,
 382        language: Option<Arc<Language>>,
 383        worktree: Option<WorktreeId>,
 384        cx: &App,
 385    ) -> Task<Vec<(TaskSourceKind, TaskTemplate)>> {
 386        let global_tasks = self.global_templates_from_settings().collect::<Vec<_>>();
 387        let mut worktree_tasks = worktree
 388            .into_iter()
 389            .flat_map(|worktree| self.worktree_templates_from_settings(worktree))
 390            .collect::<Vec<_>>();
 391
 392        let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
 393            name: language.name().into(),
 394        });
 395        let language_tasks = language
 396            .filter(|language| {
 397                language_settings(Some(language.name()), file.as_ref(), cx)
 398                    .tasks
 399                    .enabled
 400            })
 401            .and_then(|language| {
 402                language
 403                    .context_provider()
 404                    .map(|provider| provider.associated_tasks(file, cx))
 405            });
 406        cx.background_spawn(async move {
 407            if let Some(t) = language_tasks {
 408                worktree_tasks.extend(t.await.into_iter().flat_map(|tasks| {
 409                    tasks
 410                        .0
 411                        .into_iter()
 412                        .filter_map(|task| Some((task_source_kind.clone()?, task)))
 413                }));
 414            }
 415            worktree_tasks.extend(global_tasks);
 416            worktree_tasks
 417        })
 418    }
 419
 420    /// Pulls its task sources relevant to the worktree and the language given and resolves them with the [`TaskContexts`] given.
 421    /// Joins the new resolutions with the resolved tasks that were used (spawned) before,
 422    /// orders them so that the most recently used come first, all equally used ones are ordered so that the most specific tasks come first.
 423    /// Deduplicates the tasks by their labels and context and splits the ordered list into two: used tasks and the rest, newly resolved tasks.
 424    pub fn used_and_current_resolved_tasks(
 425        &self,
 426        task_contexts: Arc<TaskContexts>,
 427        cx: &mut Context<Self>,
 428    ) -> Task<(
 429        Vec<(TaskSourceKind, ResolvedTask)>,
 430        Vec<(TaskSourceKind, ResolvedTask)>,
 431    )> {
 432        let worktree = task_contexts.worktree();
 433        let location = task_contexts.location();
 434        let language = location.and_then(|location| location.buffer.read(cx).language());
 435        let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
 436            name: language.name().into(),
 437        });
 438        let file = location.and_then(|location| location.buffer.read(cx).file().cloned());
 439
 440        let mut task_labels_to_ids = HashMap::<String, HashSet<TaskId>>::default();
 441        let mut lru_score = 0_u32;
 442        let previously_spawned_tasks = self
 443            .last_scheduled_tasks
 444            .iter()
 445            .rev()
 446            .filter(|(task_kind, _)| {
 447                if matches!(task_kind, TaskSourceKind::Language { .. }) {
 448                    Some(task_kind) == task_source_kind.as_ref()
 449                } else {
 450                    true
 451                }
 452            })
 453            .filter(|(_, resolved_task)| {
 454                match task_labels_to_ids.entry(resolved_task.resolved_label.clone()) {
 455                    hash_map::Entry::Occupied(mut o) => {
 456                        o.get_mut().insert(resolved_task.id.clone());
 457                        // Neber allow duplicate reused tasks with the same labels
 458                        false
 459                    }
 460                    hash_map::Entry::Vacant(v) => {
 461                        v.insert(HashSet::from_iter(Some(resolved_task.id.clone())));
 462                        true
 463                    }
 464                }
 465            })
 466            .map(|(task_source_kind, resolved_task)| {
 467                (
 468                    task_source_kind.clone(),
 469                    resolved_task.clone(),
 470                    post_inc(&mut lru_score),
 471                )
 472            })
 473            .sorted_unstable_by(task_lru_comparator)
 474            .map(|(kind, task, _)| (kind, task))
 475            .collect::<Vec<_>>();
 476
 477        let not_used_score = post_inc(&mut lru_score);
 478        let global_tasks = self.global_templates_from_settings().collect::<Vec<_>>();
 479        let associated_tasks = language
 480            .filter(|language| {
 481                language_settings(Some(language.name()), file.as_ref(), cx)
 482                    .tasks
 483                    .enabled
 484            })
 485            .and_then(|language| {
 486                language
 487                    .context_provider()
 488                    .map(|provider| provider.associated_tasks(file, cx))
 489            });
 490        let worktree_tasks = worktree
 491            .into_iter()
 492            .flat_map(|worktree| self.worktree_templates_from_settings(worktree))
 493            .collect::<Vec<_>>();
 494        let task_contexts = task_contexts.clone();
 495        cx.background_spawn(async move {
 496            let language_tasks = if let Some(task) = associated_tasks {
 497                task.await.map(|templates| {
 498                    templates
 499                        .0
 500                        .into_iter()
 501                        .flat_map(|task| Some((task_source_kind.clone()?, task)))
 502                })
 503            } else {
 504                None
 505            };
 506
 507            let worktree_tasks = worktree_tasks
 508                .into_iter()
 509                .chain(language_tasks.into_iter().flatten())
 510                .chain(global_tasks);
 511
 512            let new_resolved_tasks = worktree_tasks
 513                .flat_map(|(kind, task)| {
 514                    let id_base = kind.to_id_base();
 515
 516                    if let TaskSourceKind::Worktree { id, .. } = &kind {
 517                        None.or_else(|| {
 518                            let (_, _, item_context) =
 519                                task_contexts.active_item_context.as_ref().filter(
 520                                    |(worktree_id, _, _)| Some(id) == worktree_id.as_ref(),
 521                                )?;
 522                            task.resolve_task(&id_base, item_context)
 523                        })
 524                        .or_else(|| {
 525                            let (_, worktree_context) = task_contexts
 526                                .active_worktree_context
 527                                .as_ref()
 528                                .filter(|(worktree_id, _)| id == worktree_id)?;
 529                            task.resolve_task(&id_base, worktree_context)
 530                        })
 531                        .or_else(|| {
 532                            if let TaskSourceKind::Worktree { id, .. } = &kind {
 533                                let worktree_context = task_contexts
 534                                    .other_worktree_contexts
 535                                    .iter()
 536                                    .find(|(worktree_id, _)| worktree_id == id)
 537                                    .map(|(_, context)| context)?;
 538                                task.resolve_task(&id_base, worktree_context)
 539                            } else {
 540                                None
 541                            }
 542                        })
 543                    } else {
 544                        None.or_else(|| {
 545                            let (_, _, item_context) =
 546                                task_contexts.active_item_context.as_ref()?;
 547                            task.resolve_task(&id_base, item_context)
 548                        })
 549                        .or_else(|| {
 550                            let (_, worktree_context) =
 551                                task_contexts.active_worktree_context.as_ref()?;
 552                            task.resolve_task(&id_base, worktree_context)
 553                        })
 554                    }
 555                    .or_else(|| task.resolve_task(&id_base, &TaskContext::default()))
 556                    .map(move |resolved_task| (kind.clone(), resolved_task, not_used_score))
 557                })
 558                .filter(|(_, resolved_task, _)| {
 559                    match task_labels_to_ids.entry(resolved_task.resolved_label.clone()) {
 560                        hash_map::Entry::Occupied(mut o) => {
 561                            // Allow new tasks with the same label, if their context is different
 562                            o.get_mut().insert(resolved_task.id.clone())
 563                        }
 564                        hash_map::Entry::Vacant(v) => {
 565                            v.insert(HashSet::from_iter(Some(resolved_task.id.clone())));
 566                            true
 567                        }
 568                    }
 569                })
 570                .sorted_unstable_by(task_lru_comparator)
 571                .map(|(kind, task, _)| (kind, task))
 572                .collect::<Vec<_>>();
 573
 574            (previously_spawned_tasks, new_resolved_tasks)
 575        })
 576    }
 577
 578    /// Returns the last scheduled task by task_id if provided.
 579    /// Otherwise, returns the last scheduled task.
 580    pub fn last_scheduled_task(
 581        &self,
 582        task_id: Option<&TaskId>,
 583    ) -> Option<(TaskSourceKind, ResolvedTask)> {
 584        if let Some(task_id) = task_id {
 585            self.last_scheduled_tasks
 586                .iter()
 587                .find(|(_, task)| &task.id == task_id)
 588                .cloned()
 589        } else {
 590            self.last_scheduled_tasks.back().cloned()
 591        }
 592    }
 593
 594    /// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
 595    pub fn task_scheduled(
 596        &mut self,
 597        task_source_kind: TaskSourceKind,
 598        resolved_task: ResolvedTask,
 599    ) {
 600        self.last_scheduled_tasks
 601            .push_back((task_source_kind, resolved_task));
 602        if self.last_scheduled_tasks.len() > 5_000 {
 603            self.last_scheduled_tasks.pop_front();
 604        }
 605    }
 606
 607    /// Deletes a resolved task from history, using its id.
 608    /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
 609    pub fn delete_previously_used(&mut self, id: &TaskId) {
 610        self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
 611    }
 612
 613    fn global_templates_from_settings(
 614        &self,
 615    ) -> impl '_ + Iterator<Item = (TaskSourceKind, TaskTemplate)> {
 616        self.templates_from_settings.global_scenarios()
 617    }
 618
 619    fn global_debug_scenarios_from_settings(
 620        &self,
 621    ) -> impl '_ + Iterator<Item = (TaskSourceKind, DebugScenario)> {
 622        self.scenarios_from_settings.global_scenarios()
 623    }
 624
 625    fn worktree_scenarios_from_settings(
 626        &self,
 627        worktree: WorktreeId,
 628    ) -> impl '_ + Iterator<Item = (TaskSourceKind, DebugScenario)> {
 629        self.scenarios_from_settings.worktree_scenarios(worktree)
 630    }
 631
 632    fn worktree_templates_from_settings(
 633        &self,
 634        worktree: WorktreeId,
 635    ) -> impl '_ + Iterator<Item = (TaskSourceKind, TaskTemplate)> {
 636        self.templates_from_settings.worktree_scenarios(worktree)
 637    }
 638
 639    /// Updates in-memory task metadata from the JSON string given.
 640    /// Will fail if the JSON is not a valid array of objects, but will continue if any object will not parse into a [`TaskTemplate`].
 641    ///
 642    /// Global tasks are updated for no worktree provided, otherwise the worktree metadata for a given path will be updated.
 643    pub fn update_file_based_tasks(
 644        &mut self,
 645        location: TaskSettingsLocation<'_>,
 646        raw_tasks_json: Option<&str>,
 647    ) -> Result<(), InvalidSettingsError> {
 648        let raw_tasks = match parse_json_with_comments::<Vec<serde_json::Value>>(
 649            raw_tasks_json.unwrap_or("[]"),
 650        ) {
 651            Ok(tasks) => tasks,
 652            Err(e) => {
 653                return Err(InvalidSettingsError::Tasks {
 654                    path: match location {
 655                        TaskSettingsLocation::Global(path) => path.to_owned(),
 656                        TaskSettingsLocation::Worktree(settings_location) => {
 657                            settings_location.path.as_std_path().join(task_file_name())
 658                        }
 659                    },
 660                    message: format!("Failed to parse tasks file content as a JSON array: {e}"),
 661                });
 662            }
 663        };
 664
 665        let mut validation_errors = Vec::new();
 666        let new_templates = raw_tasks.into_iter().filter_map(|raw_template| {
 667            let template = serde_json::from_value::<TaskTemplate>(raw_template).log_err()?;
 668
 669            // Validate the variable names used in the `TaskTemplate`.
 670            let unknown_variables = template.unknown_variables();
 671            if !unknown_variables.is_empty() {
 672                let variables_list = unknown_variables
 673                    .iter()
 674                    .map(|variable| format!("${variable}"))
 675                    .collect::<Vec<_>>()
 676                    .join(", ");
 677
 678                validation_errors.push(format!(
 679                    "Task '{}' uses unknown variables: {}",
 680                    template.label, variables_list
 681                ));
 682
 683                // Skip this template, since it uses unknown variable names, but
 684                // continue processing others.
 685                return None;
 686            }
 687
 688            Some(template)
 689        });
 690
 691        let parsed_templates = &mut self.templates_from_settings;
 692        match location {
 693            TaskSettingsLocation::Global(path) => {
 694                parsed_templates
 695                    .global
 696                    .entry(path.to_owned())
 697                    .insert_entry(new_templates.collect());
 698                self.last_scheduled_tasks.retain(|(kind, _)| {
 699                    if let TaskSourceKind::AbsPath { abs_path, .. } = kind {
 700                        abs_path != path
 701                    } else {
 702                        true
 703                    }
 704                });
 705            }
 706            TaskSettingsLocation::Worktree(location) => {
 707                let new_templates = new_templates.collect::<Vec<_>>();
 708                if new_templates.is_empty() {
 709                    if let Some(worktree_tasks) =
 710                        parsed_templates.worktree.get_mut(&location.worktree_id)
 711                    {
 712                        worktree_tasks.remove(location.path);
 713                    }
 714                } else {
 715                    parsed_templates
 716                        .worktree
 717                        .entry(location.worktree_id)
 718                        .or_default()
 719                        .insert(Arc::from(location.path), new_templates);
 720                }
 721                self.last_scheduled_tasks.retain(|(kind, _)| {
 722                    if let TaskSourceKind::Worktree {
 723                        directory_in_worktree,
 724                        id,
 725                        ..
 726                    } = kind
 727                    {
 728                        *id != location.worktree_id
 729                            || directory_in_worktree.as_ref() != location.path
 730                    } else {
 731                        true
 732                    }
 733                });
 734            }
 735        }
 736
 737        if !validation_errors.is_empty() {
 738            return Err(InvalidSettingsError::Tasks {
 739                path: match &location {
 740                    TaskSettingsLocation::Global(path) => path.to_path_buf(),
 741                    TaskSettingsLocation::Worktree(location) => {
 742                        location.path.as_std_path().join(task_file_name())
 743                    }
 744                },
 745                message: validation_errors.join("\n"),
 746            });
 747        }
 748
 749        Ok(())
 750    }
 751
 752    /// Updates in-memory task metadata from the JSON string given.
 753    /// Will fail if the JSON is not a valid array of objects, but will continue if any object will not parse into a [`TaskTemplate`].
 754    ///
 755    /// Global tasks are updated for no worktree provided, otherwise the worktree metadata for a given path will be updated.
 756    pub fn update_file_based_scenarios(
 757        &mut self,
 758        location: TaskSettingsLocation<'_>,
 759        raw_tasks_json: Option<&str>,
 760    ) -> Result<(), InvalidSettingsError> {
 761        let raw_tasks = match parse_json_with_comments::<Vec<serde_json::Value>>(
 762            raw_tasks_json.unwrap_or("[]"),
 763        ) {
 764            Ok(tasks) => tasks,
 765            Err(e) => {
 766                return Err(InvalidSettingsError::Debug {
 767                    path: match location {
 768                        TaskSettingsLocation::Global(path) => path.to_owned(),
 769                        TaskSettingsLocation::Worktree(settings_location) => settings_location
 770                            .path
 771                            .as_std_path()
 772                            .join(debug_task_file_name()),
 773                    },
 774                    message: format!("Failed to parse tasks file content as a JSON array: {e}"),
 775                });
 776            }
 777        };
 778
 779        let new_templates = raw_tasks
 780            .into_iter()
 781            .filter_map(|raw_template| {
 782                serde_json::from_value::<DebugScenario>(raw_template).log_err()
 783            })
 784            .collect::<Vec<_>>();
 785
 786        let parsed_scenarios = &mut self.scenarios_from_settings;
 787        let mut new_definitions: HashMap<_, _> = new_templates
 788            .iter()
 789            .map(|template| (template.label.clone(), template.clone()))
 790            .collect();
 791        let previously_existing_scenarios;
 792
 793        match location {
 794            TaskSettingsLocation::Global(path) => {
 795                previously_existing_scenarios = parsed_scenarios
 796                    .global_scenarios()
 797                    .map(|(_, scenario)| scenario.label)
 798                    .collect::<HashSet<_>>();
 799                parsed_scenarios
 800                    .global
 801                    .entry(path.to_owned())
 802                    .insert_entry(new_templates);
 803            }
 804            TaskSettingsLocation::Worktree(location) => {
 805                previously_existing_scenarios = parsed_scenarios
 806                    .worktree_scenarios(location.worktree_id)
 807                    .map(|(_, scenario)| scenario.label)
 808                    .collect::<HashSet<_>>();
 809
 810                if new_templates.is_empty() {
 811                    if let Some(worktree_tasks) =
 812                        parsed_scenarios.worktree.get_mut(&location.worktree_id)
 813                    {
 814                        worktree_tasks.remove(location.path);
 815                    }
 816                } else {
 817                    parsed_scenarios
 818                        .worktree
 819                        .entry(location.worktree_id)
 820                        .or_default()
 821                        .insert(Arc::from(location.path), new_templates);
 822                }
 823            }
 824        }
 825        self.last_scheduled_scenarios.retain_mut(|(scenario, _)| {
 826            if !previously_existing_scenarios.contains(&scenario.label) {
 827                return true;
 828            }
 829            if let Some(new_definition) = new_definitions.remove(&scenario.label) {
 830                *scenario = new_definition;
 831                true
 832            } else {
 833                false
 834            }
 835        });
 836
 837        Ok(())
 838    }
 839}
 840
 841fn task_lru_comparator(
 842    (kind_a, task_a, lru_score_a): &(TaskSourceKind, ResolvedTask, u32),
 843    (kind_b, task_b, lru_score_b): &(TaskSourceKind, ResolvedTask, u32),
 844) -> cmp::Ordering {
 845    lru_score_a
 846        // First, display recently used templates above all.
 847        .cmp(lru_score_b)
 848        // Then, ensure more specific sources are displayed first.
 849        .then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
 850        // After that, display first more specific tasks, using more template variables.
 851        // Bonus points for tasks with symbol variables.
 852        .then(task_variables_preference(task_a).cmp(&task_variables_preference(task_b)))
 853        // Finally, sort by the resolved label, but a bit more specifically, to avoid mixing letters and digits.
 854        .then({
 855            NumericPrefixWithSuffix::from_numeric_prefixed_str(&task_a.resolved_label)
 856                .cmp(&NumericPrefixWithSuffix::from_numeric_prefixed_str(
 857                    &task_b.resolved_label,
 858                ))
 859                .then(task_a.resolved_label.cmp(&task_b.resolved_label))
 860                .then(kind_a.cmp(kind_b))
 861        })
 862}
 863
 864pub fn task_source_kind_preference(kind: &TaskSourceKind) -> u32 {
 865    match kind {
 866        TaskSourceKind::Lsp { .. } => 0,
 867        TaskSourceKind::Language { .. } => 1,
 868        TaskSourceKind::UserInput => 2,
 869        TaskSourceKind::Worktree { .. } => 3,
 870        TaskSourceKind::AbsPath { .. } => 4,
 871    }
 872}
 873
 874fn task_variables_preference(task: &ResolvedTask) -> Reverse<usize> {
 875    let task_variables = task.substituted_variables();
 876    Reverse(if task_variables.contains(&VariableName::Symbol) {
 877        task_variables.len() + 1
 878    } else {
 879        task_variables.len()
 880    })
 881}
 882
 883/// A context provided that tries to provide values for all non-custom [`VariableName`] variants for a currently opened file.
 884/// Applied as a base for every custom [`ContextProvider`] unless explicitly oped out.
 885pub struct BasicContextProvider {
 886    worktree_store: Entity<WorktreeStore>,
 887}
 888
 889impl BasicContextProvider {
 890    pub fn new(worktree_store: Entity<WorktreeStore>) -> Self {
 891        Self { worktree_store }
 892    }
 893}
 894
 895impl ContextProvider for BasicContextProvider {
 896    fn build_context(
 897        &self,
 898        _: &TaskVariables,
 899        location: ContextLocation<'_>,
 900        _: Option<HashMap<String, String>>,
 901        _: Arc<dyn LanguageToolchainStore>,
 902        cx: &mut App,
 903    ) -> Task<Result<TaskVariables>> {
 904        let location = location.file_location;
 905        let buffer = location.buffer.read(cx);
 906        let buffer_snapshot = buffer.snapshot();
 907        let symbols = buffer_snapshot.symbols_containing(location.range.start, None);
 908        let symbol = symbols.last().map(|symbol| {
 909            let range = symbol
 910                .name_ranges
 911                .last()
 912                .cloned()
 913                .unwrap_or(0..symbol.text.len());
 914            symbol.text[range].to_string()
 915        });
 916
 917        let current_file = buffer.file().and_then(|file| file.as_local());
 918        let Point { row, column } = location.range.start.to_point(&buffer_snapshot);
 919        let row = row + 1;
 920        let column = column + 1;
 921        let selected_text = buffer
 922            .chars_for_range(location.range.clone())
 923            .collect::<String>();
 924
 925        let mut task_variables = TaskVariables::from_iter([
 926            (VariableName::Row, row.to_string()),
 927            (VariableName::Column, column.to_string()),
 928        ]);
 929
 930        if let Some(symbol) = symbol {
 931            task_variables.insert(VariableName::Symbol, symbol);
 932        }
 933        if !selected_text.trim().is_empty() {
 934            task_variables.insert(VariableName::SelectedText, selected_text);
 935        }
 936        let worktree = buffer
 937            .file()
 938            .map(|file| file.worktree_id(cx))
 939            .and_then(|worktree_id| {
 940                self.worktree_store
 941                    .read(cx)
 942                    .worktree_for_id(worktree_id, cx)
 943            });
 944
 945        if let Some(worktree) = worktree {
 946            let worktree = worktree.read(cx);
 947            let path_style = worktree.path_style();
 948            task_variables.insert(
 949                VariableName::WorktreeRoot,
 950                worktree.abs_path().to_string_lossy().into_owned(),
 951            );
 952            if let Some(current_file) = current_file.as_ref() {
 953                let relative_path = current_file.path();
 954                task_variables.insert(
 955                    VariableName::RelativeFile,
 956                    relative_path.display(path_style).to_string(),
 957                );
 958                if let Some(relative_dir) = relative_path.parent() {
 959                    task_variables.insert(
 960                        VariableName::RelativeDir,
 961                        if relative_dir.is_empty() {
 962                            String::from(".")
 963                        } else {
 964                            relative_dir.display(path_style).to_string()
 965                        },
 966                    );
 967                }
 968            }
 969        }
 970
 971        if let Some(current_file) = current_file {
 972            let path = current_file.abs_path(cx);
 973            if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
 974                task_variables.insert(VariableName::Filename, String::from(filename));
 975            }
 976
 977            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
 978                task_variables.insert(VariableName::Stem, stem.into());
 979            }
 980
 981            if let Some(dirname) = path.parent().and_then(|s| s.to_str()) {
 982                task_variables.insert(VariableName::Dirname, dirname.into());
 983            }
 984
 985            task_variables.insert(VariableName::File, path.to_string_lossy().into_owned());
 986        }
 987
 988        Task::ready(Ok(task_variables))
 989    }
 990}
 991
 992/// A ContextProvider that doesn't provide any task variables on it's own, though it has some associated tasks.
 993pub struct ContextProviderWithTasks {
 994    templates: TaskTemplates,
 995}
 996
 997impl ContextProviderWithTasks {
 998    pub fn new(definitions: TaskTemplates) -> Self {
 999        Self {
1000            templates: definitions,
1001        }
1002    }
1003}
1004
1005impl ContextProvider for ContextProviderWithTasks {
1006    fn associated_tasks(&self, _: Option<Arc<dyn File>>, _: &App) -> Task<Option<TaskTemplates>> {
1007        Task::ready(Some(self.templates.clone()))
1008    }
1009}