1use std::{path::PathBuf, sync::Arc};
2
3use ::settings::Settings;
4use editor::Editor;
5use gpui::{AppContext, ViewContext, WindowContext};
6use language::{Language, Point};
7use modal::{Spawn, TasksModal};
8use project::{Location, TaskSourceKind, WorktreeId};
9use task::{ResolvedTask, TaskContext, TaskTemplate, TaskVariables, VariableName};
10use util::ResultExt;
11use workspace::Workspace;
12
13mod modal;
14mod settings;
15mod status_indicator;
16
17pub use status_indicator::TaskStatusIndicator;
18
19pub fn init(cx: &mut AppContext) {
20 settings::TaskSettings::register(cx);
21 cx.observe_new_views(
22 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
23 workspace
24 .register_action(spawn_task_or_modal)
25 .register_action(move |workspace, action: &modal::Rerun, cx| {
26 if let Some((task_source_kind, mut last_scheduled_task)) =
27 workspace.project().update(cx, |project, cx| {
28 project.task_inventory().read(cx).last_scheduled_task()
29 })
30 {
31 if action.reevaluate_context {
32 let mut original_task = last_scheduled_task.original_task().clone();
33 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
34 original_task.allow_concurrent_runs = allow_concurrent_runs;
35 }
36 if let Some(use_new_terminal) = action.use_new_terminal {
37 original_task.use_new_terminal = use_new_terminal;
38 }
39 let task_context = task_context(workspace, cx);
40 schedule_task(
41 workspace,
42 task_source_kind,
43 &original_task,
44 &task_context,
45 false,
46 cx,
47 )
48 } else {
49 if let Some(resolved) = last_scheduled_task.resolved.as_mut() {
50 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
51 resolved.allow_concurrent_runs = allow_concurrent_runs;
52 }
53 if let Some(use_new_terminal) = action.use_new_terminal {
54 resolved.use_new_terminal = use_new_terminal;
55 }
56 }
57
58 schedule_resolved_task(
59 workspace,
60 task_source_kind,
61 last_scheduled_task,
62 false,
63 cx,
64 );
65 }
66 };
67 });
68 },
69 )
70 .detach();
71}
72
73fn spawn_task_or_modal(workspace: &mut Workspace, action: &Spawn, cx: &mut ViewContext<Workspace>) {
74 match &action.task_name {
75 Some(name) => spawn_task_with_name(name.clone(), cx),
76 None => {
77 let inventory = workspace.project().read(cx).task_inventory().clone();
78 let workspace_handle = workspace.weak_handle();
79 let task_context = task_context(workspace, cx);
80 workspace.toggle_modal(cx, |cx| {
81 TasksModal::new(inventory, task_context, workspace_handle, cx)
82 })
83 }
84 }
85}
86
87fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
88 cx.spawn(|workspace, mut cx| async move {
89 let did_spawn = workspace
90 .update(&mut cx, |workspace, cx| {
91 let (worktree, language) = active_item_selection_properties(workspace, cx);
92 let tasks = workspace.project().update(cx, |project, cx| {
93 project.task_inventory().update(cx, |inventory, cx| {
94 inventory.list_tasks(language, worktree, cx)
95 })
96 });
97 let (task_source_kind, target_task) =
98 tasks.into_iter().find(|(_, task)| task.label == name)?;
99 let task_context = task_context(workspace, cx);
100 schedule_task(
101 workspace,
102 task_source_kind,
103 &target_task,
104 &task_context,
105 false,
106 cx,
107 );
108 Some(())
109 })
110 .ok()
111 .flatten()
112 .is_some();
113 if !did_spawn {
114 workspace
115 .update(&mut cx, |workspace, cx| {
116 spawn_task_or_modal(workspace, &Spawn::default(), cx);
117 })
118 .ok();
119 }
120 })
121 .detach();
122}
123
124fn active_item_selection_properties(
125 workspace: &Workspace,
126 cx: &mut WindowContext,
127) -> (Option<WorktreeId>, Option<Arc<Language>>) {
128 let active_item = workspace.active_item(cx);
129 let worktree_id = active_item
130 .as_ref()
131 .and_then(|item| item.project_path(cx))
132 .map(|path| path.worktree_id);
133 let language = active_item
134 .and_then(|active_item| active_item.act_as::<Editor>(cx))
135 .and_then(|editor| {
136 editor.update(cx, |editor, cx| {
137 let selection = editor.selections.newest::<usize>(cx);
138 let (buffer, buffer_position, _) = editor
139 .buffer()
140 .read(cx)
141 .point_to_buffer_offset(selection.start, cx)?;
142 buffer.read(cx).language_at(buffer_position)
143 })
144 });
145 (worktree_id, language)
146}
147
148fn task_context(workspace: &Workspace, cx: &mut WindowContext<'_>) -> TaskContext {
149 let cwd = task_cwd(workspace, cx).log_err().flatten();
150 let current_editor = workspace
151 .active_item(cx)
152 .and_then(|item| item.act_as::<Editor>(cx));
153 if let Some(current_editor) = current_editor {
154 (|| {
155 let editor = current_editor.read(cx);
156 let selection = editor.selections.newest::<usize>(cx);
157 let (buffer, _, _) = editor
158 .buffer()
159 .read(cx)
160 .point_to_buffer_offset(selection.start, cx)?;
161
162 current_editor.update(cx, |editor, cx| {
163 let snapshot = editor.snapshot(cx);
164 let selection_range = selection.range();
165 let start = snapshot
166 .display_snapshot
167 .buffer_snapshot
168 .anchor_after(selection_range.start)
169 .text_anchor;
170 let end = snapshot
171 .display_snapshot
172 .buffer_snapshot
173 .anchor_after(selection_range.end)
174 .text_anchor;
175 let Point { row, column } = snapshot
176 .display_snapshot
177 .buffer_snapshot
178 .offset_to_point(selection_range.start);
179 let row = row + 1;
180 let column = column + 1;
181 let location = Location {
182 buffer: buffer.clone(),
183 range: start..end,
184 };
185
186 let current_file = location
187 .buffer
188 .read(cx)
189 .file()
190 .and_then(|file| file.as_local())
191 .map(|file| file.abs_path(cx).to_string_lossy().to_string());
192 let worktree_id = location
193 .buffer
194 .read(cx)
195 .file()
196 .map(|file| WorktreeId::from_usize(file.worktree_id()));
197 let context = buffer
198 .read(cx)
199 .language()
200 .and_then(|language| language.context_provider())
201 .and_then(|provider| provider.build_context(location, cx).ok());
202
203 let worktree_path = worktree_id.and_then(|worktree_id| {
204 workspace
205 .project()
206 .read(cx)
207 .worktree_for_id(worktree_id, cx)
208 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
209 });
210
211 let selected_text = buffer.read(cx).chars_for_range(selection_range).collect();
212
213 let mut task_variables = TaskVariables::from_iter([
214 (VariableName::Row, row.to_string()),
215 (VariableName::Column, column.to_string()),
216 (VariableName::SelectedText, selected_text),
217 ]);
218 if let Some(path) = current_file {
219 task_variables.insert(VariableName::File, path);
220 }
221 if let Some(worktree_path) = worktree_path {
222 task_variables.insert(VariableName::WorktreeRoot, worktree_path);
223 }
224 if let Some(language_context) = context {
225 task_variables.extend(language_context);
226 }
227
228 Some(TaskContext {
229 cwd: cwd.clone(),
230 task_variables,
231 })
232 })
233 })()
234 .unwrap_or_else(|| TaskContext {
235 cwd,
236 task_variables: Default::default(),
237 })
238 } else {
239 TaskContext {
240 cwd,
241 task_variables: Default::default(),
242 }
243 }
244}
245
246fn schedule_task(
247 workspace: &Workspace,
248 task_source_kind: TaskSourceKind,
249 task_to_resolve: &TaskTemplate,
250 task_cx: &TaskContext,
251 omit_history: bool,
252 cx: &mut ViewContext<'_, Workspace>,
253) {
254 if let Some(spawn_in_terminal) =
255 task_to_resolve.resolve_task(&task_source_kind.to_id_base(), task_cx)
256 {
257 schedule_resolved_task(
258 workspace,
259 task_source_kind,
260 spawn_in_terminal,
261 omit_history,
262 cx,
263 );
264 }
265}
266
267fn schedule_resolved_task(
268 workspace: &Workspace,
269 task_source_kind: TaskSourceKind,
270 mut resolved_task: ResolvedTask,
271 omit_history: bool,
272 cx: &mut ViewContext<'_, Workspace>,
273) {
274 if let Some(spawn_in_terminal) = resolved_task.resolved.take() {
275 if !omit_history {
276 resolved_task.resolved = Some(spawn_in_terminal.clone());
277 workspace.project().update(cx, |project, cx| {
278 project.task_inventory().update(cx, |inventory, _| {
279 inventory.task_scheduled(task_source_kind, resolved_task);
280 })
281 });
282 }
283 cx.emit(workspace::Event::SpawnTask(spawn_in_terminal));
284 }
285}
286
287fn task_cwd(workspace: &Workspace, cx: &mut WindowContext) -> anyhow::Result<Option<PathBuf>> {
288 let project = workspace.project().read(cx);
289 let available_worktrees = project
290 .worktrees()
291 .filter(|worktree| {
292 let worktree = worktree.read(cx);
293 worktree.is_visible()
294 && worktree.is_local()
295 && worktree.root_entry().map_or(false, |e| e.is_dir())
296 })
297 .collect::<Vec<_>>();
298 let cwd = match available_worktrees.len() {
299 0 => None,
300 1 => Some(available_worktrees[0].read(cx).abs_path()),
301 _ => {
302 let cwd_for_active_entry = project.active_entry().and_then(|entry_id| {
303 available_worktrees.into_iter().find_map(|worktree| {
304 let worktree = worktree.read(cx);
305 if worktree.contains_entry(entry_id) {
306 Some(worktree.abs_path())
307 } else {
308 None
309 }
310 })
311 });
312 anyhow::ensure!(
313 cwd_for_active_entry.is_some(),
314 "Cannot determine task cwd for multiple worktrees"
315 );
316 cwd_for_active_entry
317 }
318 };
319 Ok(cwd.map(|path| path.to_path_buf()))
320}
321
322#[cfg(test)]
323mod tests {
324 use std::sync::Arc;
325
326 use editor::Editor;
327 use gpui::{Entity, TestAppContext};
328 use language::{Language, LanguageConfig, SymbolContextProvider};
329 use project::{FakeFs, Project};
330 use serde_json::json;
331 use task::{TaskContext, TaskVariables, VariableName};
332 use ui::VisualContext;
333 use workspace::{AppState, Workspace};
334
335 use crate::task_context;
336
337 #[gpui::test]
338 async fn test_default_language_context(cx: &mut TestAppContext) {
339 init_test(cx);
340 let fs = FakeFs::new(cx.executor());
341 fs.insert_tree(
342 "/dir",
343 json!({
344 ".zed": {
345 "tasks.json": r#"[
346 {
347 "label": "example task",
348 "command": "echo",
349 "args": ["4"]
350 },
351 {
352 "label": "another one",
353 "command": "echo",
354 "args": ["55"]
355 },
356 ]"#,
357 },
358 "a.ts": "function this_is_a_test() { }",
359 "rust": {
360 "b.rs": "use std; fn this_is_a_rust_file() { }",
361 }
362
363 }),
364 )
365 .await;
366
367 let rust_language = Arc::new(
368 Language::new(
369 LanguageConfig::default(),
370 Some(tree_sitter_rust::language()),
371 )
372 .with_outline_query(
373 r#"(function_item
374 "fn" @context
375 name: (_) @name) @item"#,
376 )
377 .unwrap()
378 .with_context_provider(Some(Arc::new(SymbolContextProvider))),
379 );
380
381 let typescript_language = Arc::new(
382 Language::new(
383 LanguageConfig::default(),
384 Some(tree_sitter_typescript::language_typescript()),
385 )
386 .with_outline_query(
387 r#"(function_declaration
388 "async"? @context
389 "function" @context
390 name: (_) @name
391 parameters: (formal_parameters
392 "(" @context
393 ")" @context)) @item"#,
394 )
395 .unwrap()
396 .with_context_provider(Some(Arc::new(SymbolContextProvider))),
397 );
398 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
399 let worktree_id = project.update(cx, |project, cx| {
400 project.worktrees().next().unwrap().read(cx).id()
401 });
402 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
403
404 let buffer1 = workspace
405 .update(cx, |this, cx| {
406 this.project()
407 .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
408 })
409 .await
410 .unwrap();
411 buffer1.update(cx, |this, cx| {
412 this.set_language(Some(typescript_language), cx)
413 });
414 let editor1 = cx.new_view(|cx| Editor::for_buffer(buffer1, Some(project.clone()), cx));
415 let buffer2 = workspace
416 .update(cx, |this, cx| {
417 this.project().update(cx, |this, cx| {
418 this.open_buffer((worktree_id, "rust/b.rs"), cx)
419 })
420 })
421 .await
422 .unwrap();
423 buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
424 let editor2 = cx.new_view(|cx| Editor::for_buffer(buffer2, Some(project), cx));
425 workspace.update(cx, |this, cx| {
426 this.add_item_to_center(Box::new(editor1.clone()), cx);
427 this.add_item_to_center(Box::new(editor2.clone()), cx);
428 assert_eq!(this.active_item(cx).unwrap().item_id(), editor2.entity_id());
429 assert_eq!(
430 task_context(this, cx),
431 TaskContext {
432 cwd: Some("/dir".into()),
433 task_variables: TaskVariables::from_iter([
434 (VariableName::File, "/dir/rust/b.rs".into()),
435 (VariableName::WorktreeRoot, "/dir".into()),
436 (VariableName::Row, "1".into()),
437 (VariableName::Column, "1".into()),
438 (VariableName::SelectedText, "".into())
439 ])
440 }
441 );
442 // And now, let's select an identifier.
443 editor2.update(cx, |this, cx| {
444 this.change_selections(None, cx, |selections| selections.select_ranges([14..18]))
445 });
446 assert_eq!(
447 task_context(this, cx),
448 TaskContext {
449 cwd: Some("/dir".into()),
450 task_variables: TaskVariables::from_iter([
451 (VariableName::File, "/dir/rust/b.rs".into()),
452 (VariableName::WorktreeRoot, "/dir".into()),
453 (VariableName::Row, "1".into()),
454 (VariableName::Column, "15".into()),
455 (VariableName::SelectedText, "is_i".into()),
456 (VariableName::Symbol, "this_is_a_rust_file".into()),
457 ])
458 }
459 );
460
461 // Now, let's switch the active item to .ts file.
462 this.activate_item(&editor1, cx);
463 assert_eq!(
464 task_context(this, cx),
465 TaskContext {
466 cwd: Some("/dir".into()),
467 task_variables: TaskVariables::from_iter([
468 (VariableName::File, "/dir/a.ts".into()),
469 (VariableName::WorktreeRoot, "/dir".into()),
470 (VariableName::Row, "1".into()),
471 (VariableName::Column, "1".into()),
472 (VariableName::SelectedText, "".into()),
473 (VariableName::Symbol, "this_is_a_test".into()),
474 ])
475 }
476 );
477 });
478 }
479
480 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
481 cx.update(|cx| {
482 let state = AppState::test(cx);
483 language::init(cx);
484 crate::init(cx);
485 editor::init(cx);
486 workspace::init_settings(cx);
487 Project::init_settings(cx);
488 state
489 })
490 }
491}