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