1use std::{
2 path::{Path, PathBuf},
3 sync::Arc,
4};
5
6use ::settings::Settings;
7use anyhow::Context;
8use editor::Editor;
9use gpui::{AppContext, ViewContext, WindowContext};
10use language::{BasicContextProvider, ContextProvider, Language};
11use modal::TasksModal;
12use project::{Location, TaskSourceKind, WorktreeId};
13use task::{ResolvedTask, TaskContext, TaskTemplate, TaskVariables};
14use util::ResultExt;
15use workspace::Workspace;
16
17mod modal;
18mod settings;
19
20pub use modal::Spawn;
21
22pub fn init(cx: &mut AppContext) {
23 settings::TaskSettings::register(cx);
24 cx.observe_new_views(
25 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
26 workspace
27 .register_action(spawn_task_or_modal)
28 .register_action(move |workspace, action: &modal::Rerun, cx| {
29 if let Some((task_source_kind, mut last_scheduled_task)) =
30 workspace.project().update(cx, |project, cx| {
31 project.task_inventory().read(cx).last_scheduled_task()
32 })
33 {
34 if action.reevaluate_context {
35 let mut original_task = last_scheduled_task.original_task().clone();
36 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
37 original_task.allow_concurrent_runs = allow_concurrent_runs;
38 }
39 if let Some(use_new_terminal) = action.use_new_terminal {
40 original_task.use_new_terminal = use_new_terminal;
41 }
42 let task_context = task_context(workspace, cx);
43 schedule_task(
44 workspace,
45 task_source_kind,
46 &original_task,
47 &task_context,
48 false,
49 cx,
50 )
51 } else {
52 if let Some(resolved) = last_scheduled_task.resolved.as_mut() {
53 if let Some(allow_concurrent_runs) = action.allow_concurrent_runs {
54 resolved.allow_concurrent_runs = allow_concurrent_runs;
55 }
56 if let Some(use_new_terminal) = action.use_new_terminal {
57 resolved.use_new_terminal = use_new_terminal;
58 }
59 }
60
61 schedule_resolved_task(
62 workspace,
63 task_source_kind,
64 last_scheduled_task,
65 false,
66 cx,
67 );
68 }
69 };
70 });
71 },
72 )
73 .detach();
74}
75
76fn spawn_task_or_modal(workspace: &mut Workspace, action: &Spawn, cx: &mut ViewContext<Workspace>) {
77 match &action.task_name {
78 Some(name) => spawn_task_with_name(name.clone(), cx),
79 None => {
80 let inventory = workspace.project().read(cx).task_inventory().clone();
81 let workspace_handle = workspace.weak_handle();
82 let task_context = task_context(workspace, cx);
83 workspace.toggle_modal(cx, |cx| {
84 TasksModal::new(inventory, task_context, workspace_handle, cx)
85 })
86 }
87 }
88}
89
90fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
91 cx.spawn(|workspace, mut cx| async move {
92 let did_spawn = workspace
93 .update(&mut cx, |workspace, cx| {
94 let (worktree, language) = active_item_selection_properties(workspace, cx);
95 let tasks = workspace.project().update(cx, |project, cx| {
96 project.task_inventory().update(cx, |inventory, cx| {
97 inventory.list_tasks(language, worktree, cx)
98 })
99 });
100 let (task_source_kind, target_task) =
101 tasks.into_iter().find(|(_, task)| task.label == name)?;
102 let task_context = task_context(workspace, cx);
103 schedule_task(
104 workspace,
105 task_source_kind,
106 &target_task,
107 &task_context,
108 false,
109 cx,
110 );
111 Some(())
112 })
113 .ok()
114 .flatten()
115 .is_some();
116 if !did_spawn {
117 workspace
118 .update(&mut cx, |workspace, cx| {
119 spawn_task_or_modal(workspace, &Spawn::default(), cx);
120 })
121 .ok();
122 }
123 })
124 .detach();
125}
126
127fn active_item_selection_properties(
128 workspace: &Workspace,
129 cx: &mut WindowContext,
130) -> (Option<WorktreeId>, Option<Arc<Language>>) {
131 let active_item = workspace.active_item(cx);
132 let worktree_id = active_item
133 .as_ref()
134 .and_then(|item| item.project_path(cx))
135 .map(|path| path.worktree_id);
136 let language = active_item
137 .and_then(|active_item| active_item.act_as::<Editor>(cx))
138 .and_then(|editor| {
139 editor.update(cx, |editor, cx| {
140 let selection = editor.selections.newest::<usize>(cx);
141 let (buffer, buffer_position, _) = editor
142 .buffer()
143 .read(cx)
144 .point_to_buffer_offset(selection.start, cx)?;
145 buffer.read(cx).language_at(buffer_position)
146 })
147 });
148 (worktree_id, language)
149}
150
151fn task_context(workspace: &Workspace, cx: &mut WindowContext<'_>) -> TaskContext {
152 fn task_context_impl(workspace: &Workspace, cx: &mut WindowContext<'_>) -> Option<TaskContext> {
153 let cwd = task_cwd(workspace, cx).log_err().flatten();
154 let editor = workspace
155 .active_item(cx)
156 .and_then(|item| item.act_as::<Editor>(cx))?;
157
158 let (selection, buffer, editor_snapshot) = editor.update(cx, |editor, cx| {
159 let selection = editor.selections.newest::<usize>(cx);
160 let (buffer, _, _) = editor
161 .buffer()
162 .read(cx)
163 .point_to_buffer_offset(selection.start, cx)?;
164 let snapshot = editor.snapshot(cx);
165 Some((selection, buffer, snapshot))
166 })?;
167 let language_context_provider = buffer
168 .read(cx)
169 .language()
170 .and_then(|language| language.context_provider())
171 .unwrap_or_else(|| Arc::new(BasicContextProvider));
172 let selection_range = selection.range();
173 let start = editor_snapshot
174 .display_snapshot
175 .buffer_snapshot
176 .anchor_after(selection_range.start)
177 .text_anchor;
178 let end = editor_snapshot
179 .display_snapshot
180 .buffer_snapshot
181 .anchor_after(selection_range.end)
182 .text_anchor;
183 let worktree_abs_path = buffer
184 .read(cx)
185 .file()
186 .map(|file| WorktreeId::from_usize(file.worktree_id()))
187 .and_then(|worktree_id| {
188 workspace
189 .project()
190 .read(cx)
191 .worktree_for_id(worktree_id, cx)
192 .map(|worktree| worktree.read(cx).abs_path())
193 });
194 let location = Location {
195 buffer,
196 range: start..end,
197 };
198 let task_variables = combine_task_variables(
199 worktree_abs_path.as_deref(),
200 location,
201 language_context_provider.as_ref(),
202 cx,
203 )
204 .log_err()?;
205 Some(TaskContext {
206 cwd,
207 task_variables,
208 })
209 }
210
211 task_context_impl(workspace, cx).unwrap_or_default()
212}
213
214fn combine_task_variables(
215 worktree_abs_path: Option<&Path>,
216 location: Location,
217 context_provider: &dyn ContextProvider,
218 cx: &mut WindowContext<'_>,
219) -> anyhow::Result<TaskVariables> {
220 if context_provider.is_basic() {
221 context_provider
222 .build_context(worktree_abs_path, &location, cx)
223 .context("building basic provider context")
224 } else {
225 let mut basic_context = BasicContextProvider
226 .build_context(worktree_abs_path, &location, cx)
227 .context("building basic default context")?;
228 basic_context.extend(
229 context_provider
230 .build_context(worktree_abs_path, &location, cx)
231 .context("building provider context ")?,
232 );
233 Ok(basic_context)
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::{BasicContextProvider, Language, LanguageConfig};
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;
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(BasicContextProvider))),
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(BasicContextProvider))),
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, 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 ])
430 }
431 );
432 // And now, let's select an identifier.
433 editor2.update(cx, |this, cx| {
434 this.change_selections(None, cx, |selections| selections.select_ranges([14..18]))
435 });
436 assert_eq!(
437 task_context(this, cx),
438 TaskContext {
439 cwd: Some("/dir".into()),
440 task_variables: TaskVariables::from_iter([
441 (VariableName::File, "/dir/rust/b.rs".into()),
442 (VariableName::WorktreeRoot, "/dir".into()),
443 (VariableName::Row, "1".into()),
444 (VariableName::Column, "15".into()),
445 (VariableName::SelectedText, "is_i".into()),
446 (VariableName::Symbol, "this_is_a_rust_file".into()),
447 ])
448 }
449 );
450
451 // Now, let's switch the active item to .ts file.
452 this.activate_item(&editor1, cx);
453 assert_eq!(
454 task_context(this, cx),
455 TaskContext {
456 cwd: Some("/dir".into()),
457 task_variables: TaskVariables::from_iter([
458 (VariableName::File, "/dir/a.ts".into()),
459 (VariableName::WorktreeRoot, "/dir".into()),
460 (VariableName::Row, "1".into()),
461 (VariableName::Column, "1".into()),
462 (VariableName::Symbol, "this_is_a_test".into()),
463 ])
464 }
465 );
466 });
467 }
468
469 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
470 cx.update(|cx| {
471 let state = AppState::test(cx);
472 file_icons::init((), cx);
473 language::init(cx);
474 crate::init(cx);
475 editor::init(cx);
476 workspace::init_settings(cx);
477 Project::init_settings(cx);
478 state
479 })
480 }
481}