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