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::{Path, PathBuf},
8 sync::Arc,
9};
10
11use anyhow::Result;
12use collections::{HashMap, HashSet, VecDeque};
13use dap::DapRegistry;
14use gpui::{App, AppContext as _, Entity, SharedString, Task};
15use itertools::Itertools;
16use language::{
17 Buffer, 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 _, paths::PathExt as _, post_inc};
29use worktree::WorktreeId;
30
31use crate::{task_store::TaskSettingsLocation, worktree_store::WorktreeStore};
32
33/// Inventory tracks available tasks for a given project.
34#[derive(Debug, Default)]
35pub struct Inventory {
36 last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>,
37 last_scheduled_scenarios: VecDeque<DebugScenario>,
38 templates_from_settings: InventoryFor<TaskTemplate>,
39 scenarios_from_settings: InventoryFor<DebugScenario>,
40}
41
42// Helper trait for better error messages in [InventoryFor]
43trait InventoryContents: Clone {
44 const GLOBAL_SOURCE_FILE: &'static str;
45 const LABEL: &'static str;
46}
47
48impl InventoryContents for TaskTemplate {
49 const GLOBAL_SOURCE_FILE: &'static str = "tasks.json";
50 const LABEL: &'static str = "tasks";
51}
52
53impl InventoryContents for DebugScenario {
54 const GLOBAL_SOURCE_FILE: &'static str = "debug.json";
55
56 const LABEL: &'static str = "debug scenarios";
57}
58
59#[derive(Debug)]
60struct InventoryFor<T> {
61 global: HashMap<PathBuf, Vec<T>>,
62 worktree: HashMap<WorktreeId, HashMap<Arc<Path>, Vec<T>>>,
63}
64
65impl<T: InventoryContents> InventoryFor<T> {
66 fn worktree_scenarios(
67 &self,
68 worktree: WorktreeId,
69 ) -> impl '_ + Iterator<Item = (TaskSourceKind, T)> {
70 self.worktree
71 .get(&worktree)
72 .into_iter()
73 .flatten()
74 .flat_map(|(directory, templates)| {
75 templates.iter().map(move |template| (directory, template))
76 })
77 .map(move |(directory, template)| {
78 (
79 TaskSourceKind::Worktree {
80 id: worktree,
81 directory_in_worktree: directory.to_path_buf(),
82 id_base: Cow::Owned(format!(
83 "local worktree {} from directory {directory:?}",
84 T::LABEL
85 )),
86 },
87 template.clone(),
88 )
89 })
90 }
91
92 fn global_scenarios(&self) -> impl '_ + Iterator<Item = (TaskSourceKind, T)> {
93 self.global.iter().flat_map(|(file_path, templates)| {
94 templates.into_iter().map(|template| {
95 (
96 TaskSourceKind::AbsPath {
97 id_base: Cow::Owned(format!("global {}", T::GLOBAL_SOURCE_FILE)),
98 abs_path: file_path.clone(),
99 },
100 template.clone(),
101 )
102 })
103 })
104 }
105}
106
107impl<T> Default for InventoryFor<T> {
108 fn default() -> Self {
109 Self {
110 global: HashMap::default(),
111 worktree: HashMap::default(),
112 }
113 }
114}
115
116/// Kind of a source the tasks are fetched from, used to display more source information in the UI.
117#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
118pub enum TaskSourceKind {
119 /// bash-like commands spawned by users, not associated with any path
120 UserInput,
121 /// Tasks from the worktree's .zed/task.json
122 Worktree {
123 id: WorktreeId,
124 directory_in_worktree: PathBuf,
125 id_base: Cow<'static, str>,
126 },
127 /// ~/.config/zed/task.json - like global files with task definitions, applicable to any path
128 AbsPath {
129 id_base: Cow<'static, str>,
130 abs_path: PathBuf,
131 },
132 /// Languages-specific tasks coming from extensions.
133 Language { name: SharedString },
134 /// Language-specific tasks coming from LSP servers.
135 Lsp(LanguageServerId),
136}
137
138/// A collection of task contexts, derived from the current state of the workspace.
139/// Only contains worktrees that are visible and with their root being a directory.
140#[derive(Debug, Default)]
141pub struct TaskContexts {
142 /// A context, related to the currently opened item.
143 /// Item can be opened from an invisible worktree, or any other, not necessarily active worktree.
144 pub active_item_context: Option<(Option<WorktreeId>, Option<Location>, TaskContext)>,
145 /// A worktree that corresponds to the active item, or the only worktree in the workspace.
146 pub active_worktree_context: Option<(WorktreeId, TaskContext)>,
147 /// If there are multiple worktrees in the workspace, all non-active ones are included here.
148 pub other_worktree_contexts: Vec<(WorktreeId, TaskContext)>,
149 pub lsp_task_sources: HashMap<LanguageServerName, Vec<BufferId>>,
150 pub latest_selection: Option<text::Anchor>,
151}
152
153impl TaskContexts {
154 pub fn active_context(&self) -> Option<&TaskContext> {
155 self.active_item_context
156 .as_ref()
157 .map(|(_, _, context)| context)
158 .or_else(|| {
159 self.active_worktree_context
160 .as_ref()
161 .map(|(_, context)| context)
162 })
163 }
164
165 pub fn location(&self) -> Option<&Location> {
166 self.active_item_context
167 .as_ref()
168 .and_then(|(_, location, _)| location.as_ref())
169 }
170
171 pub fn file(&self, cx: &App) -> Option<Arc<dyn File>> {
172 self.active_item_context
173 .as_ref()
174 .and_then(|(_, location, _)| location.as_ref())
175 .and_then(|location| location.buffer.read(cx).file().cloned())
176 }
177
178 pub fn worktree(&self) -> Option<WorktreeId> {
179 self.active_item_context
180 .as_ref()
181 .and_then(|(worktree_id, _, _)| worktree_id.as_ref())
182 .or_else(|| {
183 self.active_worktree_context
184 .as_ref()
185 .map(|(worktree_id, _)| worktree_id)
186 })
187 .copied()
188 }
189
190 pub fn task_context_for_worktree_id(&self, worktree_id: WorktreeId) -> Option<&TaskContext> {
191 self.active_worktree_context
192 .iter()
193 .chain(self.other_worktree_contexts.iter())
194 .find(|(id, _)| *id == worktree_id)
195 .map(|(_, context)| context)
196 }
197}
198
199impl TaskSourceKind {
200 pub fn to_id_base(&self) -> String {
201 match self {
202 Self::UserInput => "oneshot".to_string(),
203 Self::AbsPath { id_base, abs_path } => {
204 format!("{id_base}_{}", abs_path.display())
205 }
206 Self::Worktree {
207 id,
208 id_base,
209 directory_in_worktree,
210 } => {
211 format!("{id_base}_{id}_{}", directory_in_worktree.display())
212 }
213 Self::Language { name } => format!("language_{name}"),
214 Self::Lsp(server_id) => format!("lsp_{server_id}"),
215 }
216 }
217}
218
219impl Inventory {
220 pub fn new(cx: &mut App) -> Entity<Self> {
221 cx.new(|_| Self::default())
222 }
223
224 pub fn scenario_scheduled(&mut self, scenario: DebugScenario) {
225 self.last_scheduled_scenarios
226 .retain(|s| s.label != scenario.label);
227 self.last_scheduled_scenarios.push_back(scenario);
228 if self.last_scheduled_scenarios.len() > 5_000 {
229 self.last_scheduled_scenarios.pop_front();
230 }
231 }
232
233 pub fn last_scheduled_scenario(&self) -> Option<&DebugScenario> {
234 self.last_scheduled_scenarios.back()
235 }
236
237 pub fn list_debug_scenarios(
238 &self,
239 task_contexts: &TaskContexts,
240 cx: &mut App,
241 ) -> (Vec<DebugScenario>, Vec<(TaskSourceKind, DebugScenario)>) {
242 let mut scenarios = Vec::new();
243
244 if let Some(worktree_id) = task_contexts
245 .active_worktree_context
246 .iter()
247 .chain(task_contexts.other_worktree_contexts.iter())
248 .map(|context| context.0)
249 .next()
250 {
251 scenarios.extend(self.worktree_scenarios_from_settings(worktree_id));
252 }
253 scenarios.extend(self.global_debug_scenarios_from_settings());
254
255 let (_, new) = self.used_and_current_resolved_tasks(task_contexts, cx);
256 if let Some(location) = task_contexts.location() {
257 let file = location.buffer.read(cx).file();
258 let language = location.buffer.read(cx).language();
259 let language_name = language.as_ref().map(|l| l.name());
260 let adapter = language_settings(language_name, file, cx)
261 .debuggers
262 .first()
263 .map(SharedString::from)
264 .or_else(|| {
265 language.and_then(|l| l.config().debuggers.first().map(SharedString::from))
266 });
267 if let Some(adapter) = adapter {
268 for (kind, task) in new {
269 if let Some(scenario) =
270 DapRegistry::global(cx)
271 .locators()
272 .values()
273 .find_map(|locator| {
274 locator.create_scenario(
275 &task.original_task().clone(),
276 &task.display_label(),
277 adapter.clone().into(),
278 )
279 })
280 {
281 scenarios.push((kind, scenario));
282 }
283 }
284 }
285 }
286
287 (
288 self.last_scheduled_scenarios.iter().cloned().collect(),
289 scenarios,
290 )
291 }
292
293 pub fn task_template_by_label(
294 &self,
295 buffer: Option<Entity<Buffer>>,
296 worktree_id: Option<WorktreeId>,
297 label: &str,
298 cx: &App,
299 ) -> Option<TaskTemplate> {
300 let (buffer_worktree_id, file, language) = buffer
301 .map(|buffer| {
302 let buffer = buffer.read(cx);
303 let file = buffer.file().cloned();
304 (
305 file.as_ref().map(|file| file.worktree_id(cx)),
306 file,
307 buffer.language().cloned(),
308 )
309 })
310 .unwrap_or((None, None, None));
311
312 self.list_tasks(file, language, worktree_id.or(buffer_worktree_id), cx)
313 .into_iter()
314 .find(|(_, template)| template.label == label)
315 .map(|val| val.1)
316 }
317
318 /// Pulls its task sources relevant to the worktree and the language given,
319 /// returns all task templates with their source kinds, worktree tasks first, language tasks second
320 /// and global tasks last. No specific order inside source kinds groups.
321 pub fn list_tasks(
322 &self,
323 file: Option<Arc<dyn File>>,
324 language: Option<Arc<Language>>,
325 worktree: Option<WorktreeId>,
326 cx: &App,
327 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
328 let global_tasks = self.global_templates_from_settings();
329 let worktree_tasks = worktree
330 .into_iter()
331 .flat_map(|worktree| self.worktree_templates_from_settings(worktree));
332 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
333 name: language.name().into(),
334 });
335 let language_tasks = language
336 .filter(|language| {
337 language_settings(Some(language.name()), file.as_ref(), cx)
338 .tasks
339 .enabled
340 })
341 .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
342 .into_iter()
343 .flat_map(|tasks| tasks.0.into_iter())
344 .flat_map(|task| Some((task_source_kind.clone()?, task)));
345
346 worktree_tasks
347 .chain(language_tasks)
348 .chain(global_tasks)
349 .collect()
350 }
351
352 /// Pulls its task sources relevant to the worktree and the language given and resolves them with the [`TaskContexts`] given.
353 /// Joins the new resolutions with the resolved tasks that were used (spawned) before,
354 /// orders them so that the most recently used come first, all equally used ones are ordered so that the most specific tasks come first.
355 /// Deduplicates the tasks by their labels and context and splits the ordered list into two: used tasks and the rest, newly resolved tasks.
356 pub fn used_and_current_resolved_tasks<'a>(
357 &'a self,
358 task_contexts: &'a TaskContexts,
359 cx: &'a App,
360 ) -> (
361 Vec<(TaskSourceKind, ResolvedTask)>,
362 Vec<(TaskSourceKind, ResolvedTask)>,
363 ) {
364 let worktree = task_contexts.worktree();
365 let location = task_contexts.location();
366 let language = location
367 .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
368 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
369 name: language.name().into(),
370 });
371 let file = location.and_then(|location| location.buffer.read(cx).file().cloned());
372
373 let mut task_labels_to_ids = HashMap::<String, HashSet<TaskId>>::default();
374 let mut lru_score = 0_u32;
375 let previously_spawned_tasks = self
376 .last_scheduled_tasks
377 .iter()
378 .rev()
379 .filter(|(task_kind, _)| {
380 if matches!(task_kind, TaskSourceKind::Language { .. }) {
381 Some(task_kind) == task_source_kind.as_ref()
382 } else {
383 true
384 }
385 })
386 .filter(|(_, resolved_task)| {
387 match task_labels_to_ids.entry(resolved_task.resolved_label.clone()) {
388 hash_map::Entry::Occupied(mut o) => {
389 o.get_mut().insert(resolved_task.id.clone());
390 // Neber allow duplicate reused tasks with the same labels
391 false
392 }
393 hash_map::Entry::Vacant(v) => {
394 v.insert(HashSet::from_iter(Some(resolved_task.id.clone())));
395 true
396 }
397 }
398 })
399 .map(|(task_source_kind, resolved_task)| {
400 (
401 task_source_kind.clone(),
402 resolved_task.clone(),
403 post_inc(&mut lru_score),
404 )
405 })
406 .sorted_unstable_by(task_lru_comparator)
407 .map(|(kind, task, _)| (kind, task))
408 .collect::<Vec<_>>();
409
410 let not_used_score = post_inc(&mut lru_score);
411 let global_tasks = self.global_templates_from_settings();
412
413 let language_tasks = language
414 .filter(|language| {
415 language_settings(Some(language.name()), file.as_ref(), cx)
416 .tasks
417 .enabled
418 })
419 .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
420 .into_iter()
421 .flat_map(|tasks| tasks.0.into_iter())
422 .flat_map(|task| Some((task_source_kind.clone()?, task)));
423 let worktree_tasks = worktree
424 .into_iter()
425 .flat_map(|worktree| self.worktree_templates_from_settings(worktree))
426 .chain(language_tasks)
427 .chain(global_tasks);
428
429 let new_resolved_tasks = worktree_tasks
430 .flat_map(|(kind, task)| {
431 let id_base = kind.to_id_base();
432 if let TaskSourceKind::Worktree { id, .. } = &kind {
433 None.or_else(|| {
434 let (_, _, item_context) = task_contexts
435 .active_item_context
436 .as_ref()
437 .filter(|(worktree_id, _, _)| Some(id) == worktree_id.as_ref())?;
438 task.resolve_task(&id_base, item_context)
439 })
440 .or_else(|| {
441 let (_, worktree_context) = task_contexts
442 .active_worktree_context
443 .as_ref()
444 .filter(|(worktree_id, _)| id == worktree_id)?;
445 task.resolve_task(&id_base, worktree_context)
446 })
447 .or_else(|| {
448 if let TaskSourceKind::Worktree { id, .. } = &kind {
449 let worktree_context = task_contexts
450 .other_worktree_contexts
451 .iter()
452 .find(|(worktree_id, _)| worktree_id == id)
453 .map(|(_, context)| context)?;
454 task.resolve_task(&id_base, worktree_context)
455 } else {
456 None
457 }
458 })
459 } else {
460 None.or_else(|| {
461 let (_, _, item_context) = task_contexts.active_item_context.as_ref()?;
462 task.resolve_task(&id_base, item_context)
463 })
464 .or_else(|| {
465 let (_, worktree_context) =
466 task_contexts.active_worktree_context.as_ref()?;
467 task.resolve_task(&id_base, worktree_context)
468 })
469 }
470 .or_else(|| task.resolve_task(&id_base, &TaskContext::default()))
471 .map(move |resolved_task| (kind.clone(), resolved_task, not_used_score))
472 })
473 .filter(|(_, resolved_task, _)| {
474 match task_labels_to_ids.entry(resolved_task.resolved_label.clone()) {
475 hash_map::Entry::Occupied(mut o) => {
476 // Allow new tasks with the same label, if their context is different
477 o.get_mut().insert(resolved_task.id.clone())
478 }
479 hash_map::Entry::Vacant(v) => {
480 v.insert(HashSet::from_iter(Some(resolved_task.id.clone())));
481 true
482 }
483 }
484 })
485 .sorted_unstable_by(task_lru_comparator)
486 .map(|(kind, task, _)| (kind, task))
487 .collect::<Vec<_>>();
488
489 (previously_spawned_tasks, new_resolved_tasks)
490 }
491
492 /// Returns the last scheduled task by task_id if provided.
493 /// Otherwise, returns the last scheduled task.
494 pub fn last_scheduled_task(
495 &self,
496 task_id: Option<&TaskId>,
497 ) -> Option<(TaskSourceKind, ResolvedTask)> {
498 if let Some(task_id) = task_id {
499 self.last_scheduled_tasks
500 .iter()
501 .find(|(_, task)| &task.id == task_id)
502 .cloned()
503 } else {
504 self.last_scheduled_tasks.back().cloned()
505 }
506 }
507
508 /// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
509 pub fn task_scheduled(
510 &mut self,
511 task_source_kind: TaskSourceKind,
512 resolved_task: ResolvedTask,
513 ) {
514 self.last_scheduled_tasks
515 .push_back((task_source_kind, resolved_task));
516 if self.last_scheduled_tasks.len() > 5_000 {
517 self.last_scheduled_tasks.pop_front();
518 }
519 }
520
521 /// Deletes a resolved task from history, using its id.
522 /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
523 pub fn delete_previously_used(&mut self, id: &TaskId) {
524 self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
525 }
526
527 fn global_templates_from_settings(
528 &self,
529 ) -> impl '_ + Iterator<Item = (TaskSourceKind, TaskTemplate)> {
530 self.templates_from_settings.global_scenarios()
531 }
532
533 fn global_debug_scenarios_from_settings(
534 &self,
535 ) -> impl '_ + Iterator<Item = (TaskSourceKind, DebugScenario)> {
536 self.scenarios_from_settings.global_scenarios()
537 }
538
539 fn worktree_scenarios_from_settings(
540 &self,
541 worktree: WorktreeId,
542 ) -> impl '_ + Iterator<Item = (TaskSourceKind, DebugScenario)> {
543 self.scenarios_from_settings.worktree_scenarios(worktree)
544 }
545
546 fn worktree_templates_from_settings(
547 &self,
548 worktree: WorktreeId,
549 ) -> impl '_ + Iterator<Item = (TaskSourceKind, TaskTemplate)> {
550 self.templates_from_settings.worktree_scenarios(worktree)
551 }
552
553 /// Updates in-memory task metadata from the JSON string given.
554 /// Will fail if the JSON is not a valid array of objects, but will continue if any object will not parse into a [`TaskTemplate`].
555 ///
556 /// Global tasks are updated for no worktree provided, otherwise the worktree metadata for a given path will be updated.
557 pub(crate) fn update_file_based_tasks(
558 &mut self,
559 location: TaskSettingsLocation<'_>,
560 raw_tasks_json: Option<&str>,
561 ) -> Result<(), InvalidSettingsError> {
562 let raw_tasks = match parse_json_with_comments::<Vec<serde_json::Value>>(
563 raw_tasks_json.unwrap_or("[]"),
564 ) {
565 Ok(tasks) => tasks,
566 Err(e) => {
567 return Err(InvalidSettingsError::Tasks {
568 path: match location {
569 TaskSettingsLocation::Global(path) => path.to_owned(),
570 TaskSettingsLocation::Worktree(settings_location) => {
571 settings_location.path.join(task_file_name())
572 }
573 },
574 message: format!("Failed to parse tasks file content as a JSON array: {e}"),
575 });
576 }
577 };
578 let new_templates = raw_tasks.into_iter().filter_map(|raw_template| {
579 serde_json::from_value::<TaskTemplate>(raw_template).log_err()
580 });
581
582 let parsed_templates = &mut self.templates_from_settings;
583 match location {
584 TaskSettingsLocation::Global(path) => {
585 parsed_templates
586 .global
587 .entry(path.to_owned())
588 .insert_entry(new_templates.collect());
589 }
590 TaskSettingsLocation::Worktree(location) => {
591 let new_templates = new_templates.collect::<Vec<_>>();
592 if new_templates.is_empty() {
593 if let Some(worktree_tasks) =
594 parsed_templates.worktree.get_mut(&location.worktree_id)
595 {
596 worktree_tasks.remove(location.path);
597 }
598 } else {
599 parsed_templates
600 .worktree
601 .entry(location.worktree_id)
602 .or_default()
603 .insert(Arc::from(location.path), new_templates);
604 }
605 }
606 }
607
608 Ok(())
609 }
610
611 /// Updates in-memory task metadata from the JSON string given.
612 /// Will fail if the JSON is not a valid array of objects, but will continue if any object will not parse into a [`TaskTemplate`].
613 ///
614 /// Global tasks are updated for no worktree provided, otherwise the worktree metadata for a given path will be updated.
615 pub(crate) fn update_file_based_scenarios(
616 &mut self,
617 location: TaskSettingsLocation<'_>,
618 raw_tasks_json: Option<&str>,
619 ) -> Result<(), InvalidSettingsError> {
620 let raw_tasks = match parse_json_with_comments::<Vec<serde_json::Value>>(
621 raw_tasks_json.unwrap_or("[]"),
622 ) {
623 Ok(tasks) => tasks,
624 Err(e) => {
625 return Err(InvalidSettingsError::Debug {
626 path: match location {
627 TaskSettingsLocation::Global(path) => path.to_owned(),
628 TaskSettingsLocation::Worktree(settings_location) => {
629 settings_location.path.join(debug_task_file_name())
630 }
631 },
632 message: format!("Failed to parse tasks file content as a JSON array: {e}"),
633 });
634 }
635 };
636
637 let new_templates = raw_tasks.into_iter().filter_map(|raw_template| {
638 serde_json::from_value::<DebugScenario>(raw_template).log_err()
639 });
640
641 let parsed_scenarios = &mut self.scenarios_from_settings;
642 match location {
643 TaskSettingsLocation::Global(path) => {
644 parsed_scenarios
645 .global
646 .entry(path.to_owned())
647 .insert_entry(new_templates.collect());
648 }
649 TaskSettingsLocation::Worktree(location) => {
650 let new_templates = new_templates.collect::<Vec<_>>();
651 if new_templates.is_empty() {
652 if let Some(worktree_tasks) =
653 parsed_scenarios.worktree.get_mut(&location.worktree_id)
654 {
655 worktree_tasks.remove(location.path);
656 }
657 } else {
658 parsed_scenarios
659 .worktree
660 .entry(location.worktree_id)
661 .or_default()
662 .insert(Arc::from(location.path), new_templates);
663 }
664 }
665 }
666
667 Ok(())
668 }
669}
670
671fn task_lru_comparator(
672 (kind_a, task_a, lru_score_a): &(TaskSourceKind, ResolvedTask, u32),
673 (kind_b, task_b, lru_score_b): &(TaskSourceKind, ResolvedTask, u32),
674) -> cmp::Ordering {
675 lru_score_a
676 // First, display recently used templates above all.
677 .cmp(lru_score_b)
678 // Then, ensure more specific sources are displayed first.
679 .then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
680 // After that, display first more specific tasks, using more template variables.
681 // Bonus points for tasks with symbol variables.
682 .then(task_variables_preference(task_a).cmp(&task_variables_preference(task_b)))
683 // Finally, sort by the resolved label, but a bit more specifically, to avoid mixing letters and digits.
684 .then({
685 NumericPrefixWithSuffix::from_numeric_prefixed_str(&task_a.resolved_label)
686 .cmp(&NumericPrefixWithSuffix::from_numeric_prefixed_str(
687 &task_b.resolved_label,
688 ))
689 .then(task_a.resolved_label.cmp(&task_b.resolved_label))
690 .then(kind_a.cmp(kind_b))
691 })
692}
693
694fn task_source_kind_preference(kind: &TaskSourceKind) -> u32 {
695 match kind {
696 TaskSourceKind::Lsp(..) => 0,
697 TaskSourceKind::Language { .. } => 1,
698 TaskSourceKind::UserInput => 2,
699 TaskSourceKind::Worktree { .. } => 3,
700 TaskSourceKind::AbsPath { .. } => 4,
701 }
702}
703
704fn task_variables_preference(task: &ResolvedTask) -> Reverse<usize> {
705 let task_variables = task.substituted_variables();
706 Reverse(if task_variables.contains(&VariableName::Symbol) {
707 task_variables.len() + 1
708 } else {
709 task_variables.len()
710 })
711}
712
713#[cfg(test)]
714mod test_inventory {
715 use gpui::{Entity, TestAppContext};
716 use itertools::Itertools;
717 use task::TaskContext;
718 use worktree::WorktreeId;
719
720 use crate::Inventory;
721
722 use super::TaskSourceKind;
723
724 pub(super) fn task_template_names(
725 inventory: &Entity<Inventory>,
726 worktree: Option<WorktreeId>,
727 cx: &mut TestAppContext,
728 ) -> Vec<String> {
729 inventory.update(cx, |inventory, cx| {
730 inventory
731 .list_tasks(None, None, worktree, cx)
732 .into_iter()
733 .map(|(_, task)| task.label)
734 .sorted()
735 .collect()
736 })
737 }
738
739 pub(super) fn register_task_used(
740 inventory: &Entity<Inventory>,
741 task_name: &str,
742 cx: &mut TestAppContext,
743 ) {
744 inventory.update(cx, |inventory, cx| {
745 let (task_source_kind, task) = inventory
746 .list_tasks(None, None, None, cx)
747 .into_iter()
748 .find(|(_, task)| task.label == task_name)
749 .unwrap_or_else(|| panic!("Failed to find task with name {task_name}"));
750 let id_base = task_source_kind.to_id_base();
751 inventory.task_scheduled(
752 task_source_kind.clone(),
753 task.resolve_task(&id_base, &TaskContext::default())
754 .unwrap_or_else(|| panic!("Failed to resolve task with name {task_name}")),
755 );
756 });
757 }
758
759 pub(super) async fn list_tasks(
760 inventory: &Entity<Inventory>,
761 worktree: Option<WorktreeId>,
762 cx: &mut TestAppContext,
763 ) -> Vec<(TaskSourceKind, String)> {
764 inventory.update(cx, |inventory, cx| {
765 let task_context = &TaskContext::default();
766 inventory
767 .list_tasks(None, None, worktree, cx)
768 .into_iter()
769 .filter_map(|(source_kind, task)| {
770 let id_base = source_kind.to_id_base();
771 Some((source_kind, task.resolve_task(&id_base, task_context)?))
772 })
773 .map(|(source_kind, resolved_task)| (source_kind, resolved_task.resolved_label))
774 .collect()
775 })
776 }
777}
778
779/// A context provided that tries to provide values for all non-custom [`VariableName`] variants for a currently opened file.
780/// Applied as a base for every custom [`ContextProvider`] unless explicitly oped out.
781pub struct BasicContextProvider {
782 worktree_store: Entity<WorktreeStore>,
783}
784
785impl BasicContextProvider {
786 pub fn new(worktree_store: Entity<WorktreeStore>) -> Self {
787 Self { worktree_store }
788 }
789}
790impl ContextProvider for BasicContextProvider {
791 fn build_context(
792 &self,
793 _: &TaskVariables,
794 location: &Location,
795 _: Option<HashMap<String, String>>,
796 _: Arc<dyn LanguageToolchainStore>,
797 cx: &mut App,
798 ) -> Task<Result<TaskVariables>> {
799 let buffer = location.buffer.read(cx);
800 let buffer_snapshot = buffer.snapshot();
801 let symbols = buffer_snapshot.symbols_containing(location.range.start, None);
802 let symbol = symbols.unwrap_or_default().last().map(|symbol| {
803 let range = symbol
804 .name_ranges
805 .last()
806 .cloned()
807 .unwrap_or(0..symbol.text.len());
808 symbol.text[range].to_string()
809 });
810
811 let current_file = buffer
812 .file()
813 .and_then(|file| file.as_local())
814 .map(|file| file.abs_path(cx).to_sanitized_string());
815 let Point { row, column } = location.range.start.to_point(&buffer_snapshot);
816 let row = row + 1;
817 let column = column + 1;
818 let selected_text = buffer
819 .chars_for_range(location.range.clone())
820 .collect::<String>();
821
822 let mut task_variables = TaskVariables::from_iter([
823 (VariableName::Row, row.to_string()),
824 (VariableName::Column, column.to_string()),
825 ]);
826
827 if let Some(symbol) = symbol {
828 task_variables.insert(VariableName::Symbol, symbol);
829 }
830 if !selected_text.trim().is_empty() {
831 task_variables.insert(VariableName::SelectedText, selected_text);
832 }
833 let worktree_root_dir =
834 buffer
835 .file()
836 .map(|file| file.worktree_id(cx))
837 .and_then(|worktree_id| {
838 self.worktree_store
839 .read(cx)
840 .worktree_for_id(worktree_id, cx)
841 .and_then(|worktree| worktree.read(cx).root_dir())
842 });
843 if let Some(worktree_path) = worktree_root_dir {
844 task_variables.insert(
845 VariableName::WorktreeRoot,
846 worktree_path.to_sanitized_string(),
847 );
848 if let Some(full_path) = current_file.as_ref() {
849 let relative_path = pathdiff::diff_paths(full_path, worktree_path);
850 if let Some(relative_path) = relative_path {
851 task_variables.insert(
852 VariableName::RelativeFile,
853 relative_path.to_sanitized_string(),
854 );
855 }
856 }
857 }
858
859 if let Some(path_as_string) = current_file {
860 let path = Path::new(&path_as_string);
861 if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
862 task_variables.insert(VariableName::Filename, String::from(filename));
863 }
864
865 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
866 task_variables.insert(VariableName::Stem, stem.into());
867 }
868
869 if let Some(dirname) = path.parent().and_then(|s| s.to_str()) {
870 task_variables.insert(VariableName::Dirname, dirname.into());
871 }
872
873 task_variables.insert(VariableName::File, path_as_string);
874 }
875
876 Task::ready(Ok(task_variables))
877 }
878}
879
880/// A ContextProvider that doesn't provide any task variables on it's own, though it has some associated tasks.
881pub struct ContextProviderWithTasks {
882 templates: TaskTemplates,
883}
884
885impl ContextProviderWithTasks {
886 pub fn new(definitions: TaskTemplates) -> Self {
887 Self {
888 templates: definitions,
889 }
890 }
891}
892
893impl ContextProvider for ContextProviderWithTasks {
894 fn associated_tasks(
895 &self,
896 _: Option<Arc<dyn language::File>>,
897 _: &App,
898 ) -> Option<TaskTemplates> {
899 Some(self.templates.clone())
900 }
901}
902
903#[cfg(test)]
904mod tests {
905 use gpui::TestAppContext;
906 use paths::tasks_file;
907 use pretty_assertions::assert_eq;
908 use serde_json::json;
909 use settings::SettingsLocation;
910
911 use crate::task_store::TaskStore;
912
913 use super::test_inventory::*;
914 use super::*;
915
916 #[gpui::test]
917 async fn test_task_list_sorting(cx: &mut TestAppContext) {
918 init_test(cx);
919 let inventory = cx.update(Inventory::new);
920 let initial_tasks = resolved_task_names(&inventory, None, cx);
921 assert!(
922 initial_tasks.is_empty(),
923 "No tasks expected for empty inventory, but got {initial_tasks:?}"
924 );
925 let initial_tasks = task_template_names(&inventory, None, cx);
926 assert!(
927 initial_tasks.is_empty(),
928 "No tasks expected for empty inventory, but got {initial_tasks:?}"
929 );
930 cx.run_until_parked();
931 let expected_initial_state = [
932 "1_a_task".to_string(),
933 "1_task".to_string(),
934 "2_task".to_string(),
935 "3_task".to_string(),
936 ];
937
938 inventory.update(cx, |inventory, _| {
939 inventory
940 .update_file_based_tasks(
941 TaskSettingsLocation::Global(tasks_file()),
942 Some(&mock_tasks_from_names(
943 expected_initial_state.iter().map(|name| name.as_str()),
944 )),
945 )
946 .unwrap();
947 });
948 assert_eq!(
949 task_template_names(&inventory, None, cx),
950 &expected_initial_state,
951 );
952 assert_eq!(
953 resolved_task_names(&inventory, None, cx),
954 &expected_initial_state,
955 "Tasks with equal amount of usages should be sorted alphanumerically"
956 );
957
958 register_task_used(&inventory, "2_task", cx);
959 assert_eq!(
960 task_template_names(&inventory, None, cx),
961 &expected_initial_state,
962 );
963 assert_eq!(
964 resolved_task_names(&inventory, None, cx),
965 vec![
966 "2_task".to_string(),
967 "1_a_task".to_string(),
968 "1_task".to_string(),
969 "3_task".to_string()
970 ],
971 );
972
973 register_task_used(&inventory, "1_task", cx);
974 register_task_used(&inventory, "1_task", cx);
975 register_task_used(&inventory, "1_task", cx);
976 register_task_used(&inventory, "3_task", cx);
977 assert_eq!(
978 task_template_names(&inventory, None, cx),
979 &expected_initial_state,
980 );
981 assert_eq!(
982 resolved_task_names(&inventory, None, cx),
983 vec![
984 "3_task".to_string(),
985 "1_task".to_string(),
986 "2_task".to_string(),
987 "1_a_task".to_string(),
988 ],
989 );
990
991 inventory.update(cx, |inventory, _| {
992 inventory
993 .update_file_based_tasks(
994 TaskSettingsLocation::Global(tasks_file()),
995 Some(&mock_tasks_from_names(
996 ["10_hello", "11_hello"]
997 .into_iter()
998 .chain(expected_initial_state.iter().map(|name| name.as_str())),
999 )),
1000 )
1001 .unwrap();
1002 });
1003 cx.run_until_parked();
1004 let expected_updated_state = [
1005 "10_hello".to_string(),
1006 "11_hello".to_string(),
1007 "1_a_task".to_string(),
1008 "1_task".to_string(),
1009 "2_task".to_string(),
1010 "3_task".to_string(),
1011 ];
1012 assert_eq!(
1013 task_template_names(&inventory, None, cx),
1014 &expected_updated_state,
1015 );
1016 assert_eq!(
1017 resolved_task_names(&inventory, None, cx),
1018 vec![
1019 "3_task".to_string(),
1020 "1_task".to_string(),
1021 "2_task".to_string(),
1022 "1_a_task".to_string(),
1023 "10_hello".to_string(),
1024 "11_hello".to_string(),
1025 ],
1026 );
1027
1028 register_task_used(&inventory, "11_hello", cx);
1029 assert_eq!(
1030 task_template_names(&inventory, None, cx),
1031 &expected_updated_state,
1032 );
1033 assert_eq!(
1034 resolved_task_names(&inventory, None, cx),
1035 vec![
1036 "11_hello".to_string(),
1037 "3_task".to_string(),
1038 "1_task".to_string(),
1039 "2_task".to_string(),
1040 "1_a_task".to_string(),
1041 "10_hello".to_string(),
1042 ],
1043 );
1044 }
1045
1046 #[gpui::test]
1047 async fn test_inventory_static_task_filters(cx: &mut TestAppContext) {
1048 init_test(cx);
1049 let inventory = cx.update(Inventory::new);
1050 let common_name = "common_task_name";
1051 let worktree_1 = WorktreeId::from_usize(1);
1052 let worktree_2 = WorktreeId::from_usize(2);
1053
1054 cx.run_until_parked();
1055 let worktree_independent_tasks = vec![
1056 (
1057 TaskSourceKind::AbsPath {
1058 id_base: "global tasks.json".into(),
1059 abs_path: paths::tasks_file().clone(),
1060 },
1061 common_name.to_string(),
1062 ),
1063 (
1064 TaskSourceKind::AbsPath {
1065 id_base: "global tasks.json".into(),
1066 abs_path: paths::tasks_file().clone(),
1067 },
1068 "static_source_1".to_string(),
1069 ),
1070 (
1071 TaskSourceKind::AbsPath {
1072 id_base: "global tasks.json".into(),
1073 abs_path: paths::tasks_file().clone(),
1074 },
1075 "static_source_2".to_string(),
1076 ),
1077 ];
1078 let worktree_1_tasks = [
1079 (
1080 TaskSourceKind::Worktree {
1081 id: worktree_1,
1082 directory_in_worktree: PathBuf::from(".zed"),
1083 id_base: "local worktree tasks from directory \".zed\"".into(),
1084 },
1085 common_name.to_string(),
1086 ),
1087 (
1088 TaskSourceKind::Worktree {
1089 id: worktree_1,
1090 directory_in_worktree: PathBuf::from(".zed"),
1091 id_base: "local worktree tasks from directory \".zed\"".into(),
1092 },
1093 "worktree_1".to_string(),
1094 ),
1095 ];
1096 let worktree_2_tasks = [
1097 (
1098 TaskSourceKind::Worktree {
1099 id: worktree_2,
1100 directory_in_worktree: PathBuf::from(".zed"),
1101 id_base: "local worktree tasks from directory \".zed\"".into(),
1102 },
1103 common_name.to_string(),
1104 ),
1105 (
1106 TaskSourceKind::Worktree {
1107 id: worktree_2,
1108 directory_in_worktree: PathBuf::from(".zed"),
1109 id_base: "local worktree tasks from directory \".zed\"".into(),
1110 },
1111 "worktree_2".to_string(),
1112 ),
1113 ];
1114
1115 inventory.update(cx, |inventory, _| {
1116 inventory
1117 .update_file_based_tasks(
1118 TaskSettingsLocation::Global(tasks_file()),
1119 Some(&mock_tasks_from_names(
1120 worktree_independent_tasks
1121 .iter()
1122 .map(|(_, name)| name.as_str()),
1123 )),
1124 )
1125 .unwrap();
1126 inventory
1127 .update_file_based_tasks(
1128 TaskSettingsLocation::Worktree(SettingsLocation {
1129 worktree_id: worktree_1,
1130 path: Path::new(".zed"),
1131 }),
1132 Some(&mock_tasks_from_names(
1133 worktree_1_tasks.iter().map(|(_, name)| name.as_str()),
1134 )),
1135 )
1136 .unwrap();
1137 inventory
1138 .update_file_based_tasks(
1139 TaskSettingsLocation::Worktree(SettingsLocation {
1140 worktree_id: worktree_2,
1141 path: Path::new(".zed"),
1142 }),
1143 Some(&mock_tasks_from_names(
1144 worktree_2_tasks.iter().map(|(_, name)| name.as_str()),
1145 )),
1146 )
1147 .unwrap();
1148 });
1149
1150 assert_eq!(
1151 list_tasks_sorted_by_last_used(&inventory, None, cx).await,
1152 worktree_independent_tasks,
1153 "Without a worktree, only worktree-independent tasks should be listed"
1154 );
1155 assert_eq!(
1156 list_tasks_sorted_by_last_used(&inventory, Some(worktree_1), cx).await,
1157 worktree_1_tasks
1158 .iter()
1159 .chain(worktree_independent_tasks.iter())
1160 .cloned()
1161 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
1162 .collect::<Vec<_>>(),
1163 );
1164 assert_eq!(
1165 list_tasks_sorted_by_last_used(&inventory, Some(worktree_2), cx).await,
1166 worktree_2_tasks
1167 .iter()
1168 .chain(worktree_independent_tasks.iter())
1169 .cloned()
1170 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
1171 .collect::<Vec<_>>(),
1172 );
1173
1174 assert_eq!(
1175 list_tasks(&inventory, None, cx).await,
1176 worktree_independent_tasks,
1177 "Without a worktree, only worktree-independent tasks should be listed"
1178 );
1179 assert_eq!(
1180 list_tasks(&inventory, Some(worktree_1), cx).await,
1181 worktree_1_tasks
1182 .iter()
1183 .chain(worktree_independent_tasks.iter())
1184 .cloned()
1185 .collect::<Vec<_>>(),
1186 );
1187 assert_eq!(
1188 list_tasks(&inventory, Some(worktree_2), cx).await,
1189 worktree_2_tasks
1190 .iter()
1191 .chain(worktree_independent_tasks.iter())
1192 .cloned()
1193 .collect::<Vec<_>>(),
1194 );
1195 }
1196
1197 fn init_test(_cx: &mut TestAppContext) {
1198 zlog::init_test();
1199 TaskStore::init(None);
1200 }
1201
1202 fn resolved_task_names(
1203 inventory: &Entity<Inventory>,
1204 worktree: Option<WorktreeId>,
1205 cx: &mut TestAppContext,
1206 ) -> Vec<String> {
1207 inventory.update(cx, |inventory, cx| {
1208 let mut task_contexts = TaskContexts::default();
1209 task_contexts.active_worktree_context =
1210 worktree.map(|worktree| (worktree, TaskContext::default()));
1211 let (used, current) = inventory.used_and_current_resolved_tasks(&task_contexts, cx);
1212 used.into_iter()
1213 .chain(current)
1214 .map(|(_, task)| task.original_task().label.clone())
1215 .collect()
1216 })
1217 }
1218
1219 fn mock_tasks_from_names<'a>(task_names: impl Iterator<Item = &'a str> + 'a) -> String {
1220 serde_json::to_string(&serde_json::Value::Array(
1221 task_names
1222 .map(|task_name| {
1223 json!({
1224 "label": task_name,
1225 "command": "echo",
1226 "args": vec![task_name],
1227 })
1228 })
1229 .collect::<Vec<_>>(),
1230 ))
1231 .unwrap()
1232 }
1233
1234 async fn list_tasks_sorted_by_last_used(
1235 inventory: &Entity<Inventory>,
1236 worktree: Option<WorktreeId>,
1237 cx: &mut TestAppContext,
1238 ) -> Vec<(TaskSourceKind, String)> {
1239 inventory.update(cx, |inventory, cx| {
1240 let mut task_contexts = TaskContexts::default();
1241 task_contexts.active_worktree_context =
1242 worktree.map(|worktree| (worktree, TaskContext::default()));
1243 let (used, current) = inventory.used_and_current_resolved_tasks(&task_contexts, cx);
1244 let mut all = used;
1245 all.extend(current);
1246 all.into_iter()
1247 .map(|(source_kind, task)| (source_kind, task.resolved_label))
1248 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
1249 .collect()
1250 })
1251 }
1252}