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, File, 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 file: Option<Arc<dyn File>>,
159 language: Option<Arc<Language>>,
160 worktree: Option<WorktreeId>,
161 cx: &AppContext,
162 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
163 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
164 name: language.name(),
165 });
166 let language_tasks = language
167 .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
168 .into_iter()
169 .flat_map(|tasks| tasks.0.into_iter())
170 .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
171
172 self.sources
173 .iter()
174 .filter(|source| {
175 let source_worktree = source.kind.worktree();
176 worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
177 })
178 .flat_map(|source| {
179 source
180 .source
181 .tasks_to_schedule()
182 .0
183 .into_iter()
184 .map(|task| (&source.kind, task))
185 })
186 .chain(language_tasks)
187 .map(|(task_source_kind, task)| (task_source_kind.clone(), task))
188 .collect()
189 }
190
191 /// Pulls its task sources relevant to the worktree and the language given and resolves them with the [`TaskContext`] given.
192 /// Joins the new resolutions with the resolved tasks that were used (spawned) before,
193 /// orders them so that the most recently used come first, all equally used ones are ordered so that the most specific tasks come first.
194 /// Deduplicates the tasks by their labels and splits the ordered list into two: used tasks and the rest, newly resolved tasks.
195 pub fn used_and_current_resolved_tasks(
196 &self,
197 remote_templates_task: Option<Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>>>,
198 worktree: Option<WorktreeId>,
199 location: Option<Location>,
200 task_context: &TaskContext,
201 cx: &AppContext,
202 ) -> Task<(
203 Vec<(TaskSourceKind, ResolvedTask)>,
204 Vec<(TaskSourceKind, ResolvedTask)>,
205 )> {
206 let language = location
207 .as_ref()
208 .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
209 let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
210 name: language.name(),
211 });
212 let file = location
213 .as_ref()
214 .and_then(|location| location.buffer.read(cx).file().cloned());
215 let language_tasks = language
216 .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
217 .into_iter()
218 .flat_map(|tasks| tasks.0.into_iter())
219 .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
220
221 let mut lru_score = 0_u32;
222 let mut task_usage = self
223 .last_scheduled_tasks
224 .iter()
225 .rev()
226 .filter(|(task_kind, _)| {
227 if matches!(task_kind, TaskSourceKind::Language { .. }) {
228 Some(task_kind) == task_source_kind.as_ref()
229 } else {
230 true
231 }
232 })
233 .fold(
234 BTreeMap::default(),
235 |mut tasks, (task_source_kind, resolved_task)| {
236 tasks.entry(&resolved_task.id).or_insert_with(|| {
237 (task_source_kind, resolved_task, post_inc(&mut lru_score))
238 });
239 tasks
240 },
241 );
242 let not_used_score = post_inc(&mut lru_score);
243 let mut currently_resolved_tasks = self
244 .sources
245 .iter()
246 .filter(|source| {
247 let source_worktree = source.kind.worktree();
248 worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
249 })
250 .flat_map(|source| {
251 source
252 .source
253 .tasks_to_schedule()
254 .0
255 .into_iter()
256 .map(|task| (&source.kind, task))
257 })
258 .chain(language_tasks.filter(|_| remote_templates_task.is_none()))
259 .filter_map(|(kind, task)| {
260 let id_base = kind.to_id_base();
261 Some((kind, task.resolve_task(&id_base, task_context)?))
262 })
263 .map(|(kind, task)| {
264 let lru_score = task_usage
265 .remove(&task.id)
266 .map(|(_, _, lru_score)| lru_score)
267 .unwrap_or(not_used_score);
268 (kind.clone(), task, lru_score)
269 })
270 .collect::<Vec<_>>();
271 let previously_spawned_tasks = task_usage
272 .into_iter()
273 .map(|(_, (kind, task, lru_score))| (kind.clone(), task.clone(), lru_score))
274 .collect::<Vec<_>>();
275
276 let task_context = task_context.clone();
277 cx.spawn(move |_| async move {
278 let remote_templates = match remote_templates_task {
279 Some(task) => match task.await.log_err() {
280 Some(remote_templates) => remote_templates,
281 None => return (Vec::new(), Vec::new()),
282 },
283 None => Vec::new(),
284 };
285 let remote_tasks = remote_templates.into_iter().filter_map(|(kind, task)| {
286 let id_base = kind.to_id_base();
287 Some((
288 kind,
289 task.resolve_task(&id_base, &task_context)?,
290 not_used_score,
291 ))
292 });
293 currently_resolved_tasks.extend(remote_tasks);
294
295 let mut tasks_by_label = BTreeMap::default();
296 tasks_by_label = previously_spawned_tasks.into_iter().fold(
297 tasks_by_label,
298 |mut tasks_by_label, (source, task, lru_score)| {
299 match tasks_by_label.entry((source, task.resolved_label.clone())) {
300 btree_map::Entry::Occupied(mut o) => {
301 let (_, previous_lru_score) = o.get();
302 if previous_lru_score >= &lru_score {
303 o.insert((task, lru_score));
304 }
305 }
306 btree_map::Entry::Vacant(v) => {
307 v.insert((task, lru_score));
308 }
309 }
310 tasks_by_label
311 },
312 );
313 tasks_by_label = currently_resolved_tasks.iter().fold(
314 tasks_by_label,
315 |mut tasks_by_label, (source, task, lru_score)| {
316 match tasks_by_label.entry((source.clone(), task.resolved_label.clone())) {
317 btree_map::Entry::Occupied(mut o) => {
318 let (previous_task, _) = o.get();
319 let new_template = task.original_task();
320 if new_template != previous_task.original_task() {
321 o.insert((task.clone(), *lru_score));
322 }
323 }
324 btree_map::Entry::Vacant(v) => {
325 v.insert((task.clone(), *lru_score));
326 }
327 }
328 tasks_by_label
329 },
330 );
331
332 let resolved = tasks_by_label
333 .into_iter()
334 .map(|((kind, _), (task, lru_score))| (kind, task, lru_score))
335 .sorted_by(task_lru_comparator)
336 .filter_map(|(kind, task, lru_score)| {
337 if lru_score < not_used_score {
338 Some((kind, task))
339 } else {
340 None
341 }
342 })
343 .collect::<Vec<_>>();
344
345 (
346 resolved,
347 currently_resolved_tasks
348 .into_iter()
349 .sorted_unstable_by(task_lru_comparator)
350 .map(|(kind, task, _)| (kind, task))
351 .collect(),
352 )
353 })
354 }
355
356 /// Returns the last scheduled task by task_id if provided.
357 /// Otherwise, returns the last scheduled task.
358 pub fn last_scheduled_task(
359 &self,
360 task_id: Option<&TaskId>,
361 ) -> Option<(TaskSourceKind, ResolvedTask)> {
362 if let Some(task_id) = task_id {
363 self.last_scheduled_tasks
364 .iter()
365 .find(|(_, task)| &task.id == task_id)
366 .cloned()
367 } else {
368 self.last_scheduled_tasks.back().cloned()
369 }
370 }
371
372 /// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
373 pub fn task_scheduled(
374 &mut self,
375 task_source_kind: TaskSourceKind,
376 resolved_task: ResolvedTask,
377 ) {
378 self.last_scheduled_tasks
379 .push_back((task_source_kind, resolved_task));
380 if self.last_scheduled_tasks.len() > 5_000 {
381 self.last_scheduled_tasks.pop_front();
382 }
383 }
384
385 /// Deletes a resolved task from history, using its id.
386 /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
387 pub fn delete_previously_used(&mut self, id: &TaskId) {
388 self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
389 }
390}
391
392fn task_lru_comparator(
393 (kind_a, task_a, lru_score_a): &(TaskSourceKind, ResolvedTask, u32),
394 (kind_b, task_b, lru_score_b): &(TaskSourceKind, ResolvedTask, u32),
395) -> cmp::Ordering {
396 lru_score_a
397 // First, display recently used templates above all.
398 .cmp(&lru_score_b)
399 // Then, ensure more specific sources are displayed first.
400 .then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
401 // After that, display first more specific tasks, using more template variables.
402 // Bonus points for tasks with symbol variables.
403 .then(task_variables_preference(task_a).cmp(&task_variables_preference(task_b)))
404 // Finally, sort by the resolved label, but a bit more specifically, to avoid mixing letters and digits.
405 .then({
406 NumericPrefixWithSuffix::from_numeric_prefixed_str(&task_a.resolved_label)
407 .cmp(&NumericPrefixWithSuffix::from_numeric_prefixed_str(
408 &task_b.resolved_label,
409 ))
410 .then(task_a.resolved_label.cmp(&task_b.resolved_label))
411 .then(kind_a.cmp(kind_b))
412 })
413}
414
415fn task_source_kind_preference(kind: &TaskSourceKind) -> u32 {
416 match kind {
417 TaskSourceKind::Language { .. } => 1,
418 TaskSourceKind::UserInput => 2,
419 TaskSourceKind::Worktree { .. } => 3,
420 TaskSourceKind::AbsPath { .. } => 4,
421 }
422}
423
424fn task_variables_preference(task: &ResolvedTask) -> Reverse<usize> {
425 let task_variables = task.substituted_variables();
426 Reverse(if task_variables.contains(&VariableName::Symbol) {
427 task_variables.len() + 1
428 } else {
429 task_variables.len()
430 })
431}
432
433#[cfg(test)]
434mod test_inventory {
435 use gpui::{AppContext, Model, TestAppContext};
436 use itertools::Itertools;
437 use task::{
438 static_source::{StaticSource, TrackedFile},
439 TaskContext, TaskTemplate, TaskTemplates,
440 };
441 use worktree::WorktreeId;
442
443 use crate::Inventory;
444
445 use super::{task_source_kind_preference, TaskSourceKind, UnboundedSender};
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, cx| {
475 inventory
476 .list_tasks(None, None, worktree, cx)
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, cx| {
490 let (task_source_kind, task) = inventory
491 .list_tasks(None, None, None, cx)
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(
643 &self,
644 _: Option<Arc<dyn language::File>>,
645 _: &AppContext,
646 ) -> Option<TaskTemplates> {
647 Some(self.templates.clone())
648 }
649}
650
651#[cfg(test)]
652mod tests {
653 use gpui::TestAppContext;
654
655 use super::test_inventory::*;
656 use super::*;
657
658 #[gpui::test]
659 async fn test_task_list_sorting(cx: &mut TestAppContext) {
660 let inventory = cx.update(Inventory::new);
661 let initial_tasks = resolved_task_names(&inventory, None, cx).await;
662 assert!(
663 initial_tasks.is_empty(),
664 "No tasks expected for empty inventory, but got {initial_tasks:?}"
665 );
666 let initial_tasks = task_template_names(&inventory, None, cx);
667 assert!(
668 initial_tasks.is_empty(),
669 "No tasks expected for empty inventory, but got {initial_tasks:?}"
670 );
671
672 inventory.update(cx, |inventory, cx| {
673 inventory.add_source(
674 TaskSourceKind::UserInput,
675 |tx, cx| static_test_source(vec!["3_task".to_string()], tx, cx),
676 cx,
677 );
678 });
679 inventory.update(cx, |inventory, cx| {
680 inventory.add_source(
681 TaskSourceKind::UserInput,
682 |tx, cx| {
683 static_test_source(
684 vec![
685 "1_task".to_string(),
686 "2_task".to_string(),
687 "1_a_task".to_string(),
688 ],
689 tx,
690 cx,
691 )
692 },
693 cx,
694 );
695 });
696 cx.run_until_parked();
697 let expected_initial_state = [
698 "1_a_task".to_string(),
699 "1_task".to_string(),
700 "2_task".to_string(),
701 "3_task".to_string(),
702 ];
703 assert_eq!(
704 task_template_names(&inventory, None, cx),
705 &expected_initial_state,
706 );
707 assert_eq!(
708 resolved_task_names(&inventory, None, cx).await,
709 &expected_initial_state,
710 "Tasks with equal amount of usages should be sorted alphanumerically"
711 );
712
713 register_task_used(&inventory, "2_task", cx);
714 assert_eq!(
715 task_template_names(&inventory, None, cx),
716 &expected_initial_state,
717 );
718 assert_eq!(
719 resolved_task_names(&inventory, None, cx).await,
720 vec![
721 "2_task".to_string(),
722 "2_task".to_string(),
723 "1_a_task".to_string(),
724 "1_task".to_string(),
725 "3_task".to_string()
726 ],
727 );
728
729 register_task_used(&inventory, "1_task", cx);
730 register_task_used(&inventory, "1_task", cx);
731 register_task_used(&inventory, "1_task", cx);
732 register_task_used(&inventory, "3_task", cx);
733 assert_eq!(
734 task_template_names(&inventory, None, cx),
735 &expected_initial_state,
736 );
737 assert_eq!(
738 resolved_task_names(&inventory, None, cx).await,
739 vec![
740 "3_task".to_string(),
741 "1_task".to_string(),
742 "2_task".to_string(),
743 "3_task".to_string(),
744 "1_task".to_string(),
745 "2_task".to_string(),
746 "1_a_task".to_string(),
747 ],
748 );
749
750 inventory.update(cx, |inventory, cx| {
751 inventory.add_source(
752 TaskSourceKind::UserInput,
753 |tx, cx| {
754 static_test_source(vec!["10_hello".to_string(), "11_hello".to_string()], tx, cx)
755 },
756 cx,
757 );
758 });
759 cx.run_until_parked();
760 let expected_updated_state = [
761 "10_hello".to_string(),
762 "11_hello".to_string(),
763 "1_a_task".to_string(),
764 "1_task".to_string(),
765 "2_task".to_string(),
766 "3_task".to_string(),
767 ];
768 assert_eq!(
769 task_template_names(&inventory, None, cx),
770 &expected_updated_state,
771 );
772 assert_eq!(
773 resolved_task_names(&inventory, None, cx).await,
774 vec![
775 "3_task".to_string(),
776 "1_task".to_string(),
777 "2_task".to_string(),
778 "3_task".to_string(),
779 "1_task".to_string(),
780 "2_task".to_string(),
781 "1_a_task".to_string(),
782 "10_hello".to_string(),
783 "11_hello".to_string(),
784 ],
785 );
786
787 register_task_used(&inventory, "11_hello", cx);
788 assert_eq!(
789 task_template_names(&inventory, None, cx),
790 &expected_updated_state,
791 );
792 assert_eq!(
793 resolved_task_names(&inventory, None, cx).await,
794 vec![
795 "11_hello".to_string(),
796 "3_task".to_string(),
797 "1_task".to_string(),
798 "2_task".to_string(),
799 "11_hello".to_string(),
800 "3_task".to_string(),
801 "1_task".to_string(),
802 "2_task".to_string(),
803 "1_a_task".to_string(),
804 "10_hello".to_string(),
805 ],
806 );
807 }
808
809 #[gpui::test]
810 async fn test_inventory_static_task_filters(cx: &mut TestAppContext) {
811 let inventory_with_statics = cx.update(Inventory::new);
812 let common_name = "common_task_name";
813 let path_1 = Path::new("path_1");
814 let path_2 = Path::new("path_2");
815 let worktree_1 = WorktreeId::from_usize(1);
816 let worktree_path_1 = Path::new("worktree_path_1");
817 let worktree_2 = WorktreeId::from_usize(2);
818 let worktree_path_2 = Path::new("worktree_path_2");
819
820 inventory_with_statics.update(cx, |inventory, cx| {
821 inventory.add_source(
822 TaskSourceKind::UserInput,
823 |tx, cx| {
824 static_test_source(
825 vec!["user_input".to_string(), common_name.to_string()],
826 tx,
827 cx,
828 )
829 },
830 cx,
831 );
832 inventory.add_source(
833 TaskSourceKind::AbsPath {
834 id_base: "test source".into(),
835 abs_path: path_1.to_path_buf(),
836 },
837 |tx, cx| {
838 static_test_source(
839 vec!["static_source_1".to_string(), common_name.to_string()],
840 tx,
841 cx,
842 )
843 },
844 cx,
845 );
846 inventory.add_source(
847 TaskSourceKind::AbsPath {
848 id_base: "test source".into(),
849 abs_path: path_2.to_path_buf(),
850 },
851 |tx, cx| {
852 static_test_source(
853 vec!["static_source_2".to_string(), common_name.to_string()],
854 tx,
855 cx,
856 )
857 },
858 cx,
859 );
860 inventory.add_source(
861 TaskSourceKind::Worktree {
862 id: worktree_1,
863 abs_path: worktree_path_1.to_path_buf(),
864 id_base: "test_source".into(),
865 },
866 |tx, cx| {
867 static_test_source(
868 vec!["worktree_1".to_string(), common_name.to_string()],
869 tx,
870 cx,
871 )
872 },
873 cx,
874 );
875 inventory.add_source(
876 TaskSourceKind::Worktree {
877 id: worktree_2,
878 abs_path: worktree_path_2.to_path_buf(),
879 id_base: "test_source".into(),
880 },
881 |tx, cx| {
882 static_test_source(
883 vec!["worktree_2".to_string(), common_name.to_string()],
884 tx,
885 cx,
886 )
887 },
888 cx,
889 );
890 });
891 cx.run_until_parked();
892 let worktree_independent_tasks = vec![
893 (
894 TaskSourceKind::AbsPath {
895 id_base: "test source".into(),
896 abs_path: path_1.to_path_buf(),
897 },
898 "static_source_1".to_string(),
899 ),
900 (
901 TaskSourceKind::AbsPath {
902 id_base: "test source".into(),
903 abs_path: path_1.to_path_buf(),
904 },
905 common_name.to_string(),
906 ),
907 (
908 TaskSourceKind::AbsPath {
909 id_base: "test source".into(),
910 abs_path: path_2.to_path_buf(),
911 },
912 common_name.to_string(),
913 ),
914 (
915 TaskSourceKind::AbsPath {
916 id_base: "test source".into(),
917 abs_path: path_2.to_path_buf(),
918 },
919 "static_source_2".to_string(),
920 ),
921 (TaskSourceKind::UserInput, common_name.to_string()),
922 (TaskSourceKind::UserInput, "user_input".to_string()),
923 ];
924 let worktree_1_tasks = [
925 (
926 TaskSourceKind::Worktree {
927 id: worktree_1,
928 abs_path: worktree_path_1.to_path_buf(),
929 id_base: "test_source".into(),
930 },
931 common_name.to_string(),
932 ),
933 (
934 TaskSourceKind::Worktree {
935 id: worktree_1,
936 abs_path: worktree_path_1.to_path_buf(),
937 id_base: "test_source".into(),
938 },
939 "worktree_1".to_string(),
940 ),
941 ];
942 let worktree_2_tasks = [
943 (
944 TaskSourceKind::Worktree {
945 id: worktree_2,
946 abs_path: worktree_path_2.to_path_buf(),
947 id_base: "test_source".into(),
948 },
949 common_name.to_string(),
950 ),
951 (
952 TaskSourceKind::Worktree {
953 id: worktree_2,
954 abs_path: worktree_path_2.to_path_buf(),
955 id_base: "test_source".into(),
956 },
957 "worktree_2".to_string(),
958 ),
959 ];
960
961 let all_tasks = worktree_1_tasks
962 .iter()
963 .chain(worktree_2_tasks.iter())
964 // worktree-less tasks come later in the list
965 .chain(worktree_independent_tasks.iter())
966 .cloned()
967 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
968 .collect::<Vec<_>>();
969
970 assert_eq!(
971 list_tasks(&inventory_with_statics, None, cx).await,
972 all_tasks
973 );
974 assert_eq!(
975 list_tasks(&inventory_with_statics, Some(worktree_1), cx).await,
976 worktree_1_tasks
977 .iter()
978 .chain(worktree_independent_tasks.iter())
979 .cloned()
980 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
981 .collect::<Vec<_>>(),
982 );
983 assert_eq!(
984 list_tasks(&inventory_with_statics, Some(worktree_2), cx).await,
985 worktree_2_tasks
986 .iter()
987 .chain(worktree_independent_tasks.iter())
988 .cloned()
989 .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
990 .collect::<Vec<_>>(),
991 );
992 }
993
994 pub(super) async fn resolved_task_names(
995 inventory: &Model<Inventory>,
996 worktree: Option<WorktreeId>,
997 cx: &mut TestAppContext,
998 ) -> Vec<String> {
999 let (used, current) = inventory
1000 .update(cx, |inventory, cx| {
1001 inventory.used_and_current_resolved_tasks(
1002 None,
1003 worktree,
1004 None,
1005 &TaskContext::default(),
1006 cx,
1007 )
1008 })
1009 .await;
1010 used.into_iter()
1011 .chain(current)
1012 .map(|(_, task)| task.original_task().label.clone())
1013 .collect()
1014 }
1015}