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 path::{Path, PathBuf},
7 sync::Arc,
8};
9
10use anyhow::Result;
11use collections::{btree_map, BTreeMap, VecDeque};
12use futures::{
13 channel::mpsc::{unbounded, UnboundedSender},
14 StreamExt,
15};
16use gpui::{AppContext, Context, Model, ModelContext, Task};
17use itertools::Itertools;
18use language::{ContextProvider, Language, Location};
19use task::{
20 static_source::StaticSource, ResolvedTask, TaskContext, TaskId, TaskTemplate, TaskTemplates,
21 TaskVariables, VariableName,
22};
23use text::{Point, ToPoint};
24use util::{post_inc, NumericPrefixWithSuffix, ResultExt};
25use worktree::WorktreeId;
26
27use crate::Project;
28
29/// Inventory tracks available tasks for a given project.
30pub struct Inventory {
31 sources: Vec<SourceInInventory>,
32 last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>,
33 update_sender: UnboundedSender<()>,
34 _update_pooler: Task<anyhow::Result<()>>,
35}
36
37struct SourceInInventory {
38 source: StaticSource,
39 kind: TaskSourceKind,
40}
41
42/// Kind of a source the tasks are fetched from, used to display more source information in the UI.
43#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
44pub enum TaskSourceKind {
45 /// bash-like commands spawned by users, not associated with any path
46 UserInput,
47 /// Tasks from the worktree's .zed/task.json
48 Worktree {
49 id: WorktreeId,
50 abs_path: PathBuf,
51 id_base: Cow<'static, str>,
52 },
53 /// ~/.config/zed/task.json - like global files with task definitions, applicable to any path
54 AbsPath {
55 id_base: Cow<'static, str>,
56 abs_path: PathBuf,
57 },
58 /// Languages-specific tasks coming from extensions.
59 Language { name: Arc<str> },
60}
61
62impl TaskSourceKind {
63 pub fn abs_path(&self) -> Option<&Path> {
64 match self {
65 Self::AbsPath { abs_path, .. } | Self::Worktree { abs_path, .. } => Some(abs_path),
66 Self::UserInput | Self::Language { .. } => None,
67 }
68 }
69
70 pub fn worktree(&self) -> Option<WorktreeId> {
71 match self {
72 Self::Worktree { id, .. } => Some(*id),
73 _ => None,
74 }
75 }
76
77 pub fn to_id_base(&self) -> String {
78 match self {
79 TaskSourceKind::UserInput => "oneshot".to_string(),
80 TaskSourceKind::AbsPath { id_base, abs_path } => {
81 format!("{id_base}_{}", abs_path.display())
82 }
83 TaskSourceKind::Worktree {
84 id,
85 id_base,
86 abs_path,
87 } => {
88 format!("{id_base}_{id}_{}", abs_path.display())
89 }
90 TaskSourceKind::Language { name } => format!("language_{name}"),
91 }
92 }
93}
94
95impl Inventory {
96 pub fn new(cx: &mut AppContext) -> Model<Self> {
97 cx.new_model(|cx| {
98 let (update_sender, mut rx) = unbounded();
99 let _update_pooler = cx.spawn(|this, mut cx| async move {
100 while let Some(()) = rx.next().await {
101 this.update(&mut cx, |_, cx| {
102 cx.notify();
103 })?;
104 }
105 Ok(())
106 });
107 Self {
108 sources: Vec::new(),
109 last_scheduled_tasks: VecDeque::new(),
110 update_sender,
111 _update_pooler,
112 }
113 })
114 }
115
116 /// If the task with the same path was not added yet,
117 /// registers a new tasks source to fetch for available tasks later.
118 /// Unless a source is removed, ignores future additions for the same path.
119 pub fn add_source(
120 &mut self,
121 kind: TaskSourceKind,
122 create_source: impl FnOnce(UnboundedSender<()>, &mut AppContext) -> StaticSource,
123 cx: &mut ModelContext<Self>,
124 ) {
125 let abs_path = kind.abs_path();
126 if abs_path.is_some() {
127 if let Some(a) = self.sources.iter().find(|s| s.kind.abs_path() == abs_path) {
128 log::debug!("Source for path {abs_path:?} already exists, not adding. Old kind: {OLD_KIND:?}, new kind: {kind:?}", OLD_KIND = a.kind);
129 return;
130 }
131 }
132 let source = create_source(self.update_sender.clone(), cx);
133 let source = SourceInInventory { source, kind };
134 self.sources.push(source);
135 cx.notify();
136 }
137
138 /// If present, removes the local static source entry that has the given path,
139 /// making corresponding task definitions unavailable in the fetch results.
140 ///
141 /// Now, entry for this path can be re-added again.
142 pub fn remove_local_static_source(&mut self, abs_path: &Path) {
143 self.sources.retain(|s| s.kind.abs_path() != Some(abs_path));
144 }
145
146 /// If present, removes the worktree source entry that has the given worktree id,
147 /// making corresponding task definitions unavailable in the fetch results.
148 ///
149 /// Now, entry for this path can be re-added again.
150 pub fn remove_worktree_sources(&mut self, worktree: WorktreeId) {
151 self.sources.retain(|s| s.kind.worktree() != Some(worktree));
152 }
153
154 /// Pulls its task sources relevant to the worktree and the language given,
155 /// returns all task templates with their source kinds, in no specific order.
156 pub fn list_tasks(
157 &self,
158 language: Option<Arc<Language>>,
159 worktree: Option<WorktreeId>,
160 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
161 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
162 name: language.name(),
163 });
164 let language_tasks = language
165 .and_then(|language| language.context_provider()?.associated_tasks())
166 .into_iter()
167 .flat_map(|tasks| tasks.0.into_iter())
168 .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
169
170 self.sources
171 .iter()
172 .filter(|source| {
173 let source_worktree = source.kind.worktree();
174 worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
175 })
176 .flat_map(|source| {
177 source
178 .source
179 .tasks_to_schedule()
180 .0
181 .into_iter()
182 .map(|task| (&source.kind, task))
183 })
184 .chain(language_tasks)
185 .map(|(task_source_kind, task)| (task_source_kind.clone(), task))
186 .collect()
187 }
188
189 /// Pulls its task sources relevant to the worktree and the language given and resolves them with the [`TaskContext`] given.
190 /// Joins the new resolutions with the resolved tasks that were used (spawned) before,
191 /// orders them so that the most recently used come first, all equally used ones are ordered so that the most specific tasks come first.
192 /// Deduplicates the tasks by their labels and splits the ordered list into two: used tasks and the rest, newly resolved tasks.
193 pub fn used_and_current_resolved_tasks(
194 &self,
195 remote_templates_task: Option<Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>>>,
196 worktree: Option<WorktreeId>,
197 location: Option<Location>,
198 task_context: &TaskContext,
199 cx: &AppContext,
200 ) -> Task<(
201 Vec<(TaskSourceKind, ResolvedTask)>,
202 Vec<(TaskSourceKind, ResolvedTask)>,
203 )> {
204 let language = location
205 .as_ref()
206 .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
207 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
208 name: language.name(),
209 });
210 let language_tasks = language
211 .and_then(|language| language.context_provider()?.associated_tasks())
212 .into_iter()
213 .flat_map(|tasks| tasks.0.into_iter())
214 .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
215
216 let mut lru_score = 0_u32;
217 let mut task_usage = self
218 .last_scheduled_tasks
219 .iter()
220 .rev()
221 .filter(|(task_kind, _)| {
222 if matches!(task_kind, TaskSourceKind::Language { .. }) {
223 Some(task_kind) == task_source_kind.as_ref()
224 } else {
225 true
226 }
227 })
228 .fold(
229 BTreeMap::default(),
230 |mut tasks, (task_source_kind, resolved_task)| {
231 tasks.entry(&resolved_task.id).or_insert_with(|| {
232 (task_source_kind, resolved_task, post_inc(&mut lru_score))
233 });
234 tasks
235 },
236 );
237 let not_used_score = post_inc(&mut lru_score);
238 let mut currently_resolved_tasks = self
239 .sources
240 .iter()
241 .filter(|source| {
242 let source_worktree = source.kind.worktree();
243 worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
244 })
245 .flat_map(|source| {
246 source
247 .source
248 .tasks_to_schedule()
249 .0
250 .into_iter()
251 .map(|task| (&source.kind, task))
252 })
253 .chain(language_tasks.filter(|_| remote_templates_task.is_none()))
254 .filter_map(|(kind, task)| {
255 let id_base = kind.to_id_base();
256 Some((kind, task.resolve_task(&id_base, task_context)?))
257 })
258 .map(|(kind, task)| {
259 let lru_score = task_usage
260 .remove(&task.id)
261 .map(|(_, _, lru_score)| lru_score)
262 .unwrap_or(not_used_score);
263 (kind.clone(), task, lru_score)
264 })
265 .collect::<Vec<_>>();
266 let previously_spawned_tasks = task_usage
267 .into_iter()
268 .map(|(_, (kind, task, lru_score))| (kind.clone(), task.clone(), lru_score))
269 .collect::<Vec<_>>();
270
271 let task_context = task_context.clone();
272 cx.spawn(move |_| async move {
273 let remote_templates = match remote_templates_task {
274 Some(task) => match task.await.log_err() {
275 Some(remote_templates) => remote_templates,
276 None => return (Vec::new(), Vec::new()),
277 },
278 None => Vec::new(),
279 };
280 let remote_tasks = remote_templates.into_iter().filter_map(|(kind, task)| {
281 let id_base = kind.to_id_base();
282 Some((
283 kind,
284 task.resolve_task(&id_base, &task_context)?,
285 not_used_score,
286 ))
287 });
288 currently_resolved_tasks.extend(remote_tasks);
289
290 let mut tasks_by_label = BTreeMap::default();
291 tasks_by_label = previously_spawned_tasks.into_iter().fold(
292 tasks_by_label,
293 |mut tasks_by_label, (source, task, lru_score)| {
294 match tasks_by_label.entry((source, task.resolved_label.clone())) {
295 btree_map::Entry::Occupied(mut o) => {
296 let (_, previous_lru_score) = o.get();
297 if previous_lru_score >= &lru_score {
298 o.insert((task, lru_score));
299 }
300 }
301 btree_map::Entry::Vacant(v) => {
302 v.insert((task, lru_score));
303 }
304 }
305 tasks_by_label
306 },
307 );
308 tasks_by_label = currently_resolved_tasks.iter().fold(
309 tasks_by_label,
310 |mut tasks_by_label, (source, task, lru_score)| {
311 match tasks_by_label.entry((source.clone(), task.resolved_label.clone())) {
312 btree_map::Entry::Occupied(mut o) => {
313 let (previous_task, _) = o.get();
314 let new_template = task.original_task();
315 if new_template != previous_task.original_task() {
316 o.insert((task.clone(), *lru_score));
317 }
318 }
319 btree_map::Entry::Vacant(v) => {
320 v.insert((task.clone(), *lru_score));
321 }
322 }
323 tasks_by_label
324 },
325 );
326
327 let resolved = tasks_by_label
328 .into_iter()
329 .map(|((kind, _), (task, lru_score))| (kind, task, lru_score))
330 .sorted_by(task_lru_comparator)
331 .filter_map(|(kind, task, lru_score)| {
332 if lru_score < not_used_score {
333 Some((kind, task))
334 } else {
335 None
336 }
337 })
338 .collect::<Vec<_>>();
339
340 (
341 resolved,
342 currently_resolved_tasks
343 .into_iter()
344 .sorted_unstable_by(task_lru_comparator)
345 .map(|(kind, task, _)| (kind, task))
346 .collect(),
347 )
348 })
349 }
350
351 /// Returns the last scheduled task by task_id if provided.
352 /// Otherwise, returns the last scheduled task.
353 pub fn last_scheduled_task(
354 &self,
355 task_id: Option<&TaskId>,
356 ) -> Option<(TaskSourceKind, ResolvedTask)> {
357 if let Some(task_id) = task_id {
358 self.last_scheduled_tasks
359 .iter()
360 .find(|(_, task)| &task.id == task_id)
361 .cloned()
362 } else {
363 self.last_scheduled_tasks.back().cloned()
364 }
365 }
366
367 /// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
368 pub fn task_scheduled(
369 &mut self,
370 task_source_kind: TaskSourceKind,
371 resolved_task: ResolvedTask,
372 ) {
373 self.last_scheduled_tasks
374 .push_back((task_source_kind, resolved_task));
375 if self.last_scheduled_tasks.len() > 5_000 {
376 self.last_scheduled_tasks.pop_front();
377 }
378 }
379
380 /// Deletes a resolved task from history, using its id.
381 /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
382 pub fn delete_previously_used(&mut self, id: &TaskId) {
383 self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
384 }
385}
386
387fn task_lru_comparator(
388 (kind_a, task_a, lru_score_a): &(TaskSourceKind, ResolvedTask, u32),
389 (kind_b, task_b, lru_score_b): &(TaskSourceKind, ResolvedTask, u32),
390) -> cmp::Ordering {
391 lru_score_a
392 // First, display recently used templates above all.
393 .cmp(&lru_score_b)
394 // Then, ensure more specific sources are displayed first.
395 .then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
396 // After that, display first more specific tasks, using more template variables.
397 // Bonus points for tasks with symbol variables.
398 .then(task_variables_preference(task_a).cmp(&task_variables_preference(task_b)))
399 // Finally, sort by the resolved label, but a bit more specifically, to avoid mixing letters and digits.
400 .then({
401 NumericPrefixWithSuffix::from_numeric_prefixed_str(&task_a.resolved_label)
402 .cmp(&NumericPrefixWithSuffix::from_numeric_prefixed_str(
403 &task_b.resolved_label,
404 ))
405 .then(task_a.resolved_label.cmp(&task_b.resolved_label))
406 .then(kind_a.cmp(kind_b))
407 })
408}
409
410fn task_source_kind_preference(kind: &TaskSourceKind) -> u32 {
411 match kind {
412 TaskSourceKind::Language { .. } => 1,
413 TaskSourceKind::UserInput => 2,
414 TaskSourceKind::Worktree { .. } => 3,
415 TaskSourceKind::AbsPath { .. } => 4,
416 }
417}
418
419fn task_variables_preference(task: &ResolvedTask) -> Reverse<usize> {
420 let task_variables = task.substituted_variables();
421 Reverse(if task_variables.contains(&VariableName::Symbol) {
422 task_variables.len() + 1
423 } else {
424 task_variables.len()
425 })
426}
427
428#[cfg(test)]
429mod test_inventory {
430 use gpui::{AppContext, Model, TestAppContext};
431 use itertools::Itertools;
432 use task::{
433 static_source::{StaticSource, TrackedFile},
434 TaskContext, TaskTemplate, TaskTemplates,
435 };
436 use worktree::WorktreeId;
437
438 use crate::Inventory;
439
440 use super::{task_source_kind_preference, TaskSourceKind, UnboundedSender};
441
442 #[derive(Debug, Clone, PartialEq, Eq)]
443 pub struct TestTask {
444 name: String,
445 }
446
447 pub(super) fn static_test_source(
448 task_names: impl IntoIterator<Item = String>,
449 updates: UnboundedSender<()>,
450 cx: &mut AppContext,
451 ) -> StaticSource {
452 let tasks = TaskTemplates(
453 task_names
454 .into_iter()
455 .map(|name| TaskTemplate {
456 label: name,
457 command: "test command".to_owned(),
458 ..TaskTemplate::default()
459 })
460 .collect(),
461 );
462 let (tx, rx) = futures::channel::mpsc::unbounded();
463 let file = TrackedFile::new(rx, updates, cx);
464 tx.unbounded_send(serde_json::to_string(&tasks).unwrap())
465 .unwrap();
466 StaticSource::new(file)
467 }
468
469 pub(super) fn task_template_names(
470 inventory: &Model<Inventory>,
471 worktree: Option<WorktreeId>,
472 cx: &mut TestAppContext,
473 ) -> Vec<String> {
474 inventory.update(cx, |inventory, _| {
475 inventory
476 .list_tasks(None, worktree)
477 .into_iter()
478 .map(|(_, task)| task.label)
479 .sorted()
480 .collect()
481 })
482 }
483
484 pub(super) fn register_task_used(
485 inventory: &Model<Inventory>,
486 task_name: &str,
487 cx: &mut TestAppContext,
488 ) {
489 inventory.update(cx, |inventory, _| {
490 let (task_source_kind, task) = inventory
491 .list_tasks(None, None)
492 .into_iter()
493 .find(|(_, task)| task.label == task_name)
494 .unwrap_or_else(|| panic!("Failed to find task with name {task_name}"));
495 let id_base = task_source_kind.to_id_base();
496 inventory.task_scheduled(
497 task_source_kind.clone(),
498 task.resolve_task(&id_base, &TaskContext::default())
499 .unwrap_or_else(|| panic!("Failed to resolve task with name {task_name}")),
500 );
501 });
502 }
503
504 pub(super) async fn list_tasks(
505 inventory: &Model<Inventory>,
506 worktree: Option<WorktreeId>,
507 cx: &mut TestAppContext,
508 ) -> Vec<(TaskSourceKind, String)> {
509 let (used, current) = inventory
510 .update(cx, |inventory, cx| {
511 inventory.used_and_current_resolved_tasks(
512 None,
513 worktree,
514 None,
515 &TaskContext::default(),
516 cx,
517 )
518 })
519 .await;
520 let mut all = used;
521 all.extend(current);
522 all.into_iter()
523 .map(|(source_kind, task)| (source_kind, task.resolved_label))
524 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
525 .collect()
526 }
527}
528
529/// A context provided that tries to provide values for all non-custom [`VariableName`] variants for a currently opened file.
530/// Applied as a base for every custom [`ContextProvider`] unless explicitly oped out.
531pub struct BasicContextProvider {
532 project: Model<Project>,
533}
534
535impl BasicContextProvider {
536 pub fn new(project: Model<Project>) -> Self {
537 Self { project }
538 }
539}
540
541impl ContextProvider for BasicContextProvider {
542 fn build_context(
543 &self,
544 _: &TaskVariables,
545 location: &Location,
546 cx: &mut AppContext,
547 ) -> Result<TaskVariables> {
548 let buffer = location.buffer.read(cx);
549 let buffer_snapshot = buffer.snapshot();
550 let symbols = buffer_snapshot.symbols_containing(location.range.start, None);
551 let symbol = symbols.unwrap_or_default().last().map(|symbol| {
552 let range = symbol
553 .name_ranges
554 .last()
555 .cloned()
556 .unwrap_or(0..symbol.text.len());
557 symbol.text[range].to_string()
558 });
559
560 let current_file = buffer
561 .file()
562 .and_then(|file| file.as_local())
563 .map(|file| file.abs_path(cx).to_string_lossy().to_string());
564 let Point { row, column } = location.range.start.to_point(&buffer_snapshot);
565 let row = row + 1;
566 let column = column + 1;
567 let selected_text = buffer
568 .chars_for_range(location.range.clone())
569 .collect::<String>();
570
571 let mut task_variables = TaskVariables::from_iter([
572 (VariableName::Row, row.to_string()),
573 (VariableName::Column, column.to_string()),
574 ]);
575
576 if let Some(symbol) = symbol {
577 task_variables.insert(VariableName::Symbol, symbol);
578 }
579 if !selected_text.trim().is_empty() {
580 task_variables.insert(VariableName::SelectedText, selected_text);
581 }
582 let worktree_abs_path = buffer
583 .file()
584 .map(|file| WorktreeId::from_usize(file.worktree_id()))
585 .and_then(|worktree_id| {
586 self.project
587 .read(cx)
588 .worktree_for_id(worktree_id, cx)
589 .map(|worktree| worktree.read(cx).abs_path())
590 });
591 if let Some(worktree_path) = worktree_abs_path {
592 task_variables.insert(
593 VariableName::WorktreeRoot,
594 worktree_path.to_string_lossy().to_string(),
595 );
596 if let Some(full_path) = current_file.as_ref() {
597 let relative_path = pathdiff::diff_paths(full_path, worktree_path);
598 if let Some(relative_path) = relative_path {
599 task_variables.insert(
600 VariableName::RelativeFile,
601 relative_path.to_string_lossy().into_owned(),
602 );
603 }
604 }
605 }
606
607 if let Some(path_as_string) = current_file {
608 let path = Path::new(&path_as_string);
609 if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
610 task_variables.insert(VariableName::Filename, String::from(filename));
611 }
612
613 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
614 task_variables.insert(VariableName::Stem, stem.into());
615 }
616
617 if let Some(dirname) = path.parent().and_then(|s| s.to_str()) {
618 task_variables.insert(VariableName::Dirname, dirname.into());
619 }
620
621 task_variables.insert(VariableName::File, path_as_string);
622 }
623
624 Ok(task_variables)
625 }
626}
627
628/// A ContextProvider that doesn't provide any task variables on it's own, though it has some associated tasks.
629pub struct ContextProviderWithTasks {
630 templates: TaskTemplates,
631}
632
633impl ContextProviderWithTasks {
634 pub fn new(definitions: TaskTemplates) -> Self {
635 Self {
636 templates: definitions,
637 }
638 }
639}
640
641impl ContextProvider for ContextProviderWithTasks {
642 fn associated_tasks(&self) -> Option<TaskTemplates> {
643 Some(self.templates.clone())
644 }
645}
646
647#[cfg(test)]
648mod tests {
649 use gpui::TestAppContext;
650
651 use super::test_inventory::*;
652 use super::*;
653
654 #[gpui::test]
655 async fn test_task_list_sorting(cx: &mut TestAppContext) {
656 let inventory = cx.update(Inventory::new);
657 let initial_tasks = resolved_task_names(&inventory, None, cx).await;
658 assert!(
659 initial_tasks.is_empty(),
660 "No tasks expected for empty inventory, but got {initial_tasks:?}"
661 );
662 let initial_tasks = task_template_names(&inventory, None, cx);
663 assert!(
664 initial_tasks.is_empty(),
665 "No tasks expected for empty inventory, but got {initial_tasks:?}"
666 );
667
668 inventory.update(cx, |inventory, cx| {
669 inventory.add_source(
670 TaskSourceKind::UserInput,
671 |tx, cx| static_test_source(vec!["3_task".to_string()], tx, cx),
672 cx,
673 );
674 });
675 inventory.update(cx, |inventory, cx| {
676 inventory.add_source(
677 TaskSourceKind::UserInput,
678 |tx, cx| {
679 static_test_source(
680 vec![
681 "1_task".to_string(),
682 "2_task".to_string(),
683 "1_a_task".to_string(),
684 ],
685 tx,
686 cx,
687 )
688 },
689 cx,
690 );
691 });
692 cx.run_until_parked();
693 let expected_initial_state = [
694 "1_a_task".to_string(),
695 "1_task".to_string(),
696 "2_task".to_string(),
697 "3_task".to_string(),
698 ];
699 assert_eq!(
700 task_template_names(&inventory, None, cx),
701 &expected_initial_state,
702 );
703 assert_eq!(
704 resolved_task_names(&inventory, None, cx).await,
705 &expected_initial_state,
706 "Tasks with equal amount of usages should be sorted alphanumerically"
707 );
708
709 register_task_used(&inventory, "2_task", cx);
710 assert_eq!(
711 task_template_names(&inventory, None, cx),
712 &expected_initial_state,
713 );
714 assert_eq!(
715 resolved_task_names(&inventory, None, cx).await,
716 vec![
717 "2_task".to_string(),
718 "2_task".to_string(),
719 "1_a_task".to_string(),
720 "1_task".to_string(),
721 "3_task".to_string()
722 ],
723 );
724
725 register_task_used(&inventory, "1_task", cx);
726 register_task_used(&inventory, "1_task", cx);
727 register_task_used(&inventory, "1_task", cx);
728 register_task_used(&inventory, "3_task", cx);
729 assert_eq!(
730 task_template_names(&inventory, None, cx),
731 &expected_initial_state,
732 );
733 assert_eq!(
734 resolved_task_names(&inventory, None, cx).await,
735 vec![
736 "3_task".to_string(),
737 "1_task".to_string(),
738 "2_task".to_string(),
739 "3_task".to_string(),
740 "1_task".to_string(),
741 "2_task".to_string(),
742 "1_a_task".to_string(),
743 ],
744 );
745
746 inventory.update(cx, |inventory, cx| {
747 inventory.add_source(
748 TaskSourceKind::UserInput,
749 |tx, cx| {
750 static_test_source(vec!["10_hello".to_string(), "11_hello".to_string()], tx, cx)
751 },
752 cx,
753 );
754 });
755 cx.run_until_parked();
756 let expected_updated_state = [
757 "10_hello".to_string(),
758 "11_hello".to_string(),
759 "1_a_task".to_string(),
760 "1_task".to_string(),
761 "2_task".to_string(),
762 "3_task".to_string(),
763 ];
764 assert_eq!(
765 task_template_names(&inventory, None, cx),
766 &expected_updated_state,
767 );
768 assert_eq!(
769 resolved_task_names(&inventory, None, cx).await,
770 vec![
771 "3_task".to_string(),
772 "1_task".to_string(),
773 "2_task".to_string(),
774 "3_task".to_string(),
775 "1_task".to_string(),
776 "2_task".to_string(),
777 "1_a_task".to_string(),
778 "10_hello".to_string(),
779 "11_hello".to_string(),
780 ],
781 );
782
783 register_task_used(&inventory, "11_hello", cx);
784 assert_eq!(
785 task_template_names(&inventory, None, cx),
786 &expected_updated_state,
787 );
788 assert_eq!(
789 resolved_task_names(&inventory, None, cx).await,
790 vec![
791 "11_hello".to_string(),
792 "3_task".to_string(),
793 "1_task".to_string(),
794 "2_task".to_string(),
795 "11_hello".to_string(),
796 "3_task".to_string(),
797 "1_task".to_string(),
798 "2_task".to_string(),
799 "1_a_task".to_string(),
800 "10_hello".to_string(),
801 ],
802 );
803 }
804
805 #[gpui::test]
806 async fn test_inventory_static_task_filters(cx: &mut TestAppContext) {
807 let inventory_with_statics = cx.update(Inventory::new);
808 let common_name = "common_task_name";
809 let path_1 = Path::new("path_1");
810 let path_2 = Path::new("path_2");
811 let worktree_1 = WorktreeId::from_usize(1);
812 let worktree_path_1 = Path::new("worktree_path_1");
813 let worktree_2 = WorktreeId::from_usize(2);
814 let worktree_path_2 = Path::new("worktree_path_2");
815
816 inventory_with_statics.update(cx, |inventory, cx| {
817 inventory.add_source(
818 TaskSourceKind::UserInput,
819 |tx, cx| {
820 static_test_source(
821 vec!["user_input".to_string(), common_name.to_string()],
822 tx,
823 cx,
824 )
825 },
826 cx,
827 );
828 inventory.add_source(
829 TaskSourceKind::AbsPath {
830 id_base: "test source".into(),
831 abs_path: path_1.to_path_buf(),
832 },
833 |tx, cx| {
834 static_test_source(
835 vec!["static_source_1".to_string(), common_name.to_string()],
836 tx,
837 cx,
838 )
839 },
840 cx,
841 );
842 inventory.add_source(
843 TaskSourceKind::AbsPath {
844 id_base: "test source".into(),
845 abs_path: path_2.to_path_buf(),
846 },
847 |tx, cx| {
848 static_test_source(
849 vec!["static_source_2".to_string(), common_name.to_string()],
850 tx,
851 cx,
852 )
853 },
854 cx,
855 );
856 inventory.add_source(
857 TaskSourceKind::Worktree {
858 id: worktree_1,
859 abs_path: worktree_path_1.to_path_buf(),
860 id_base: "test_source".into(),
861 },
862 |tx, cx| {
863 static_test_source(
864 vec!["worktree_1".to_string(), common_name.to_string()],
865 tx,
866 cx,
867 )
868 },
869 cx,
870 );
871 inventory.add_source(
872 TaskSourceKind::Worktree {
873 id: worktree_2,
874 abs_path: worktree_path_2.to_path_buf(),
875 id_base: "test_source".into(),
876 },
877 |tx, cx| {
878 static_test_source(
879 vec!["worktree_2".to_string(), common_name.to_string()],
880 tx,
881 cx,
882 )
883 },
884 cx,
885 );
886 });
887 cx.run_until_parked();
888 let worktree_independent_tasks = vec![
889 (
890 TaskSourceKind::AbsPath {
891 id_base: "test source".into(),
892 abs_path: path_1.to_path_buf(),
893 },
894 "static_source_1".to_string(),
895 ),
896 (
897 TaskSourceKind::AbsPath {
898 id_base: "test source".into(),
899 abs_path: path_1.to_path_buf(),
900 },
901 common_name.to_string(),
902 ),
903 (
904 TaskSourceKind::AbsPath {
905 id_base: "test source".into(),
906 abs_path: path_2.to_path_buf(),
907 },
908 common_name.to_string(),
909 ),
910 (
911 TaskSourceKind::AbsPath {
912 id_base: "test source".into(),
913 abs_path: path_2.to_path_buf(),
914 },
915 "static_source_2".to_string(),
916 ),
917 (TaskSourceKind::UserInput, common_name.to_string()),
918 (TaskSourceKind::UserInput, "user_input".to_string()),
919 ];
920 let worktree_1_tasks = [
921 (
922 TaskSourceKind::Worktree {
923 id: worktree_1,
924 abs_path: worktree_path_1.to_path_buf(),
925 id_base: "test_source".into(),
926 },
927 common_name.to_string(),
928 ),
929 (
930 TaskSourceKind::Worktree {
931 id: worktree_1,
932 abs_path: worktree_path_1.to_path_buf(),
933 id_base: "test_source".into(),
934 },
935 "worktree_1".to_string(),
936 ),
937 ];
938 let worktree_2_tasks = [
939 (
940 TaskSourceKind::Worktree {
941 id: worktree_2,
942 abs_path: worktree_path_2.to_path_buf(),
943 id_base: "test_source".into(),
944 },
945 common_name.to_string(),
946 ),
947 (
948 TaskSourceKind::Worktree {
949 id: worktree_2,
950 abs_path: worktree_path_2.to_path_buf(),
951 id_base: "test_source".into(),
952 },
953 "worktree_2".to_string(),
954 ),
955 ];
956
957 let all_tasks = worktree_1_tasks
958 .iter()
959 .chain(worktree_2_tasks.iter())
960 // worktree-less tasks come later in the list
961 .chain(worktree_independent_tasks.iter())
962 .cloned()
963 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
964 .collect::<Vec<_>>();
965
966 assert_eq!(
967 list_tasks(&inventory_with_statics, None, cx).await,
968 all_tasks
969 );
970 assert_eq!(
971 list_tasks(&inventory_with_statics, Some(worktree_1), cx).await,
972 worktree_1_tasks
973 .iter()
974 .chain(worktree_independent_tasks.iter())
975 .cloned()
976 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
977 .collect::<Vec<_>>(),
978 );
979 assert_eq!(
980 list_tasks(&inventory_with_statics, Some(worktree_2), cx).await,
981 worktree_2_tasks
982 .iter()
983 .chain(worktree_independent_tasks.iter())
984 .cloned()
985 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
986 .collect::<Vec<_>>(),
987 );
988 }
989
990 pub(super) async fn resolved_task_names(
991 inventory: &Model<Inventory>,
992 worktree: Option<WorktreeId>,
993 cx: &mut TestAppContext,
994 ) -> Vec<String> {
995 let (used, current) = inventory
996 .update(cx, |inventory, cx| {
997 inventory.used_and_current_resolved_tasks(
998 None,
999 worktree,
1000 None,
1001 &TaskContext::default(),
1002 cx,
1003 )
1004 })
1005 .await;
1006 used.into_iter()
1007 .chain(current)
1008 .map(|(_, task)| task.original_task().label.clone())
1009 .collect()
1010 }
1011}